forked from trimble-oss/dba-dash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBADashAgent.cs
172 lines (155 loc) · 7.21 KB
/
DBADashAgent.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
using Microsoft.Data.SqlClient;
using Serilog;
using System;
using System.Reflection;
using System.Runtime.Caching;
using System.Security.Cryptography;
namespace DBADash
{
public class DBADashAgent
{
private readonly MemoryCache cache = MemoryCache.Default;
public string AgentServiceName { get; set; }
public string AgentHostName { get; set; }
public string AgentPath { get; set; }
public string AgentVersion { get; set; }
public string ServiceSQSQueueUrl { get; set; }
public bool MessagingEnabled { get; set; }
/// <summary>
/// This is the ConnectionString of the S3 source connection used to import data from the remote agent. This is stored and associated with the agent in the repository. When sending messages to the agent, this will be used for the message payload as SQS messages are limited in size.
/// </summary>
public string S3Path { get; set; }
private readonly CacheItemPolicy policy = new()
{
SlidingExpiration = TimeSpan.FromMinutes(60)
};
public string AgentIdentifier => Convert.ToBase64String(MD5.HashData(System.Text.Encoding.UTF8.GetBytes(string.Concat(AgentServiceName, AgentHostName, AgentPath))));
///<summary>
///Get the DBADashAgentID from the repository DB. This will collect/update on startup then be cached.
///</summary>
public int GetDBADashAgentID(string connectionString)
{
int agentID;
var cacheKey =
// Caching takes all properties into account + connection string (as we could be writing to multiple repositories and the agent could have different IDs for each). Base off MD5 hash which should be sufficient for this use case.
Convert.ToBase64String(MD5.HashData(System.Text.Encoding.UTF8.GetBytes(string.Concat(connectionString, AgentServiceName, AgentVersion, AgentHostName, AgentPath, ServiceSQSQueueUrl, MessagingEnabled, S3Path))));
if (cache.Contains(cacheKey))
{
agentID = (int)cache[cacheKey];
}
else
{
Log.Information("Update DBADashAgent");
agentID = Update(connectionString);
Log.Information("DBADashAgentID: {0}", agentID);
if (cache.Contains(agentID
.ToString()))
{
// Remove old cache entry which will prevent updates if settings are toggled back and forth
cache.Remove((string)cache[agentID.ToString()]);
Log.Debug("Removed old cache entry for agentID: {0}", agentID);
}
cache.Add(cacheKey, agentID, policy);
cache.Add(agentID.ToString(), cacheKey, policy); // Add reverse lookup so we can identify the cache key to remove if settings are toggled back and forth
}
return agentID;
}
public override bool Equals(object obj)
{
if (obj?.GetType() == typeof(DBADashAgent))
{
var compare = (DBADashAgent)obj;
if (AgentServiceName == compare.AgentServiceName
&& AgentHostName == compare.AgentHostName
&& AgentPath == compare.AgentPath
&& AgentVersion == compare.AgentVersion)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public override int GetHashCode()
{
return $"{AgentServiceName}|{AgentHostName}|{AgentPath}|{AgentVersion}".GetHashCode();
}
private static DBADashAgent currentAgent;
///<summary>
///Return a DBADashAgent object by providing a service name. AgentPath, Version and HostName are set automatically.
///</summary>
public static DBADashAgent GetCurrent()
{
currentAgent ??= GetCurrentAgent();
return currentAgent;
}
private static DBADashAgent GetCurrentAgent()
{
var cfg = BasicConfig.Load<CollectionConfig>();
var version = Assembly.GetEntryAssembly()?.GetName().Version;
return new DBADashAgent()
{
AgentVersion = version?.ToString(),
AgentHostName = Environment.MachineName,
AgentServiceName = cfg.ServiceName,
AgentPath = AppDomain.CurrentDomain.BaseDirectory,
ServiceSQSQueueUrl = cfg.ServiceSQSQueueUrl,
MessagingEnabled = cfg.EnableMessaging
};
}
public static DBADashAgent GetDBADashAgent(string connectionString, int id)
{
using var cn = new SqlConnection(connectionString);
using var cmd = new SqlCommand("dbo.DBADashAgent_Get", cn) { CommandType = System.Data.CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("DBADashAgentID", id);
cn.Open();
using var rdr = cmd.ExecuteReader();
if (rdr.Read())
{
return new DBADashAgent()
{
AgentServiceName = rdr["AgentServiceName"].ToString(),
AgentHostName = rdr["AgentHostName"].ToString(),
AgentPath = rdr["AgentPath"].ToString(),
AgentVersion = rdr["AgentVersion"].ToString(),
ServiceSQSQueueUrl = rdr["ServiceSQSQueueURL"].ToString(),
S3Path = rdr["S3Path"] == DBNull.Value ? null : rdr["S3Path"].ToString(),
MessagingEnabled = rdr["MessagingEnabled"] != DBNull.Value && (bool)rdr["MessagingEnabled"]
};
}
else
{
throw new ArgumentException("Agent not found");
}
}
private int Update(string connectionString)
{
using (var cn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand("dbo.DBADashAgent_Upd", cn) { CommandType = System.Data.CommandType.StoredProcedure })
{
cn.Open();
cmd.Parameters.AddWithValue("AgentServiceName", AgentServiceName);
cmd.Parameters.AddWithValue("AgentHostName", AgentHostName);
cmd.Parameters.AddWithValue("AgentPath", AgentPath);
cmd.Parameters.AddWithValue("AgentVersion", AgentVersion);
var pAgentID = cmd.Parameters.Add("DBADashAgentID", System.Data.SqlDbType.Int);
cmd.Parameters.AddWithValue("ServiceSQSQueueURL", ServiceSQSQueueUrl);
cmd.Parameters.AddWithValue("AgentIdentifier", AgentIdentifier);
if (!string.IsNullOrEmpty(S3Path))
{
cmd.Parameters.AddWithValue("S3Path", S3Path);
}
cmd.Parameters.AddWithValue("MessagingEnabled", MessagingEnabled);
pAgentID.Direction = System.Data.ParameterDirection.Output;
cmd.ExecuteNonQuery();
return (int)pAgentID.Value;
}
}
}
}