-
Notifications
You must be signed in to change notification settings - Fork 1
/
Worker.cs
98 lines (70 loc) · 2.56 KB
/
Worker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Timers;
using Amazon;
using Amazon.SimpleNotificationService.Model;
using log4net;
namespace SpotStop2SNS
{
public class Worker
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Worker));
private Timer _timer;
private const double InitialDelay = 1000;
private const double ShortInterval = 5000;
private string Topic = ConfigurationManager.AppSettings["Topic"] ?? "SpotInstanceTermination";
private bool _marked = false;
private object _lock = new Object();
private string _arn;
public Worker()
{
Log.Debug("Starting worker.");
var client = AWSClientFactory.CreateAmazonSimpleNotificationServiceClient();
Topic = string.Format(Topic, AWSConfigs.AWSRegion);
var topic = client.ListTopics().Topics.FirstOrDefault(x => x.TopicArn.Contains(Topic));
if (topic == null)
{
Log.Debug("Creating topic " + Topic);
_arn = client.CreateTopic(Topic).TopicArn;
}
else
{
_arn = topic.TopicArn;
}
_timer = new Timer(InitialDelay);
GC.KeepAlive(_timer);
_timer.Elapsed += this.Tick;
_timer.Start();
Log.Debug("Timer started.");
}
public void Tick(object sender, EventArgs args)
{
lock (_lock)
{
if(!_timer.Enabled)
return;
Log.Debug("Tick.");
string s;
try
{
s = new WebClient().DownloadString(new Uri("http://169.254.169.254/latest/meta-data/spot/termination-time"));
}
catch (WebException e)
{
Log.Debug("Exception caught (normal).", e);
return;
}
Log.Debug("String caught: " + s);
_timer.Stop();
var id = new WebClient().DownloadString(new Uri("http://169.254.169.254/latest/meta-data/instance-id"));
var msg = string.Format("Instance {0} marked for termination at {1}.", id, s);
Log.Debug("Publishing:" + msg);
var client = AWSClientFactory.CreateAmazonSimpleNotificationServiceClient();
client.Publish(_arn, msg);
Log.Debug("Ending");
}
}
}
}