/
ApplicationInsightsUtility.rb
307 lines (286 loc) · 12.9 KB
/
ApplicationInsightsUtility.rb
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/local/bin/ruby
# frozen_string_literal: true
class ApplicationInsightsUtility
require_relative "lib/application_insights"
require_relative "omslog"
require_relative "DockerApiClient"
require_relative "oms_common"
require_relative "proxy_utils"
require "yajl/json_gem"
require "base64"
@@HeartBeat = "HeartBeatEvent"
@@Exception = "ExceptionEvent"
@@AcsClusterType = "ACS"
@@AksClusterType = "AKS"
@OmsAdminFilePath = "/etc/opt/microsoft/omsagent/conf/omsadmin.conf"
@@EnvAcsResourceName = "ACS_RESOURCE_NAME"
@@EnvAksRegion = "AKS_REGION"
@@EnvAgentVersion = "AGENT_VERSION"
@@EnvApplicationInsightsKey = "APPLICATIONINSIGHTS_AUTH"
@@EnvApplicationInsightsEndpoint = "APPLICATIONINSIGHTS_ENDPOINT"
@@EnvControllerType = "CONTROLLER_TYPE"
@@EnvContainerRuntime = "CONTAINER_RUNTIME"
@@CustomProperties = {}
@@Tc = nil
@@hostName = (OMS::Common.get_hostname)
@@proxy = (ProxyUtils.getProxyConfiguration)
def initialize
end
class << self
#Set default properties for telemetry event
def initializeUtility()
begin
resourceInfo = ENV["AKS_RESOURCE_ID"]
if resourceInfo.nil? || resourceInfo.empty?
@@CustomProperties["ACSResourceName"] = ENV[@@EnvAcsResourceName]
@@CustomProperties["ClusterType"] = @@AcsClusterType
@@CustomProperties["SubscriptionID"] = ""
@@CustomProperties["ResourceGroupName"] = ""
@@CustomProperties["ClusterName"] = ""
@@CustomProperties["Region"] = ""
else
@@CustomProperties["AKS_RESOURCE_ID"] = resourceInfo
begin
splitStrings = resourceInfo.split("/")
subscriptionId = splitStrings[2]
resourceGroupName = splitStrings[4]
clusterName = splitStrings[8]
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: parsing AKS resourceId: #{resourceInfo}, error: #{errorStr}")
end
@@CustomProperties["ClusterType"] = @@AksClusterType
@@CustomProperties["SubscriptionID"] = subscriptionId
@@CustomProperties["ResourceGroupName"] = resourceGroupName
@@CustomProperties["ClusterName"] = clusterName
@@CustomProperties["Region"] = ENV[@@EnvAksRegion]
end
#Commenting it for now from initilize method, we need to pivot all telemetry off of kubenode docker version
#getDockerInfo()
@@CustomProperties["WorkspaceID"] = getWorkspaceId
@@CustomProperties["AgentVersion"] = ENV[@@EnvAgentVersion]
@@CustomProperties["ControllerType"] = ENV[@@EnvControllerType]
@@CustomProperties["Computer"] = @@hostName
encodedAppInsightsKey = ENV[@@EnvApplicationInsightsKey]
appInsightsEndpoint = ENV[@@EnvApplicationInsightsEndpoint]
@@CustomProperties["WorkspaceCloud"] = getWorkspaceCloud
if !@@proxy.nil? && !@@proxy.empty?
$log.info("proxy configured")
@@CustomProperties["IsProxyConfigured"] = "true"
isProxyConfigured = true
else
@@CustomProperties["IsProxyConfigured"] = "false"
isProxyConfigured = false
$log.info("proxy is not configured")
end
#Check if telemetry is turned off
telemetryOffSwitch = ENV["DISABLE_TELEMETRY"]
if telemetryOffSwitch && !telemetryOffSwitch.nil? && !telemetryOffSwitch.empty? && telemetryOffSwitch.downcase == "true".downcase
$log.warn("AppInsightsUtility: Telemetry is disabled")
@@Tc = ApplicationInsights::TelemetryClient.new
elsif !encodedAppInsightsKey.nil?
decodedAppInsightsKey = Base64.decode64(encodedAppInsightsKey)
#override ai endpoint if its available otherwise use default.
if appInsightsEndpoint && !appInsightsEndpoint.nil? && !appInsightsEndpoint.empty?
$log.info("AppInsightsUtility: Telemetry client uses overrided endpoint url : #{appInsightsEndpoint}")
#telemetrySynchronousSender = ApplicationInsights::Channel::SynchronousSender.new appInsightsEndpoint
#telemetrySynchronousQueue = ApplicationInsights::Channel::SynchronousQueue.new(telemetrySynchronousSender)
#telemetryChannel = ApplicationInsights::Channel::TelemetryChannel.new nil, telemetrySynchronousQueue
if !isProxyConfigured
sender = ApplicationInsights::Channel::AsynchronousSender.new appInsightsEndpoint
else
$log.info("AppInsightsUtility: Telemetry client uses provided proxy configuration since proxy configured")
sender = ApplicationInsights::Channel::AsynchronousSender.new appInsightsEndpoint, @@proxy
end
queue = ApplicationInsights::Channel::AsynchronousQueue.new sender
channel = ApplicationInsights::Channel::TelemetryChannel.new nil, queue
@@Tc = ApplicationInsights::TelemetryClient.new decodedAppInsightsKey, channel
else
if !isProxyConfigured
sender = ApplicationInsights::Channel::AsynchronousSender.new
else
$log.info("AppInsightsUtility: Telemetry client uses provided proxy configuration since proxy configured")
sender = ApplicationInsights::Channel::AsynchronousSender.new nil, @@proxy
end
queue = ApplicationInsights::Channel::AsynchronousQueue.new sender
channel = ApplicationInsights::Channel::TelemetryChannel.new nil, queue
@@Tc = ApplicationInsights::TelemetryClient.new decodedAppInsightsKey, channel
end
# The below are default recommended values. If you change these, ensure you test telemetry flow fully
# flush telemetry if we have 10 or more telemetry items in our queue
#@@Tc.channel.queue.max_queue_length = 10
# send telemetry to the service in batches of 5
#@@Tc.channel.sender.send_buffer_size = 5
# the background worker thread will be active for 5 seconds before it shuts down. if
# during this time items are picked up from the queue, the timer is reset.
#@@Tc.channel.sender.send_time = 5
# the background worker thread will poll the queue every 0.5 seconds for new items
#@@Tc.channel.sender.send_interval = 0.5
end
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: initilizeUtility - error: #{errorStr}")
end
end
def getContainerRuntimeInfo()
containerRuntime = ENV[@@EnvContainerRuntime]
if !containerRuntime.nil? && !containerRuntime.empty?
# DockerVersion field holds either containerRuntime for non-docker or Dockerversion if its docker
@@CustomProperties["DockerVersion"] = containerRuntime
if containerRuntime.casecmp("docker") == 0
dockerInfo = DockerApiClient.dockerInfo
if (!dockerInfo.nil? && !dockerInfo.empty?)
@@CustomProperties["DockerVersion"] = dockerInfo["Version"]
end
end
end
end
def sendHeartBeatEvent(pluginName)
begin
eventName = pluginName + @@HeartBeat
if !(@@Tc.nil?)
@@Tc.track_event eventName, :properties => @@CustomProperties
$log.info("AppInsights Heartbeat Telemetry put successfully into the queue")
end
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: sendHeartBeatEvent - error: #{errorStr}")
end
end
def sendLastProcessedContainerInventoryCountMetric(pluginName, properties)
begin
if !(@@Tc.nil?)
@@Tc.track_metric "LastProcessedContainerInventoryCount", properties["ContainerCount"],
:kind => ApplicationInsights::Channel::Contracts::DataPointType::MEASUREMENT,
:properties => @@CustomProperties
$log.info("AppInsights Container Count Telemetry sput successfully into the queue")
end
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: sendCustomMetric - error: #{errorStr}")
end
end
def sendCustomEvent(eventName, properties)
begin
if @@CustomProperties.empty? || @@CustomProperties.nil?
initializeUtility()
end
telemetryProps = {}
# add common dimensions
@@CustomProperties.each { |k, v| telemetryProps[k] = v }
# add passed-in dimensions if any
if (!properties.nil? && !properties.empty?)
properties.each { |k, v| telemetryProps[k] = v }
end
if !(@@Tc.nil?)
@@Tc.track_event eventName, :properties => telemetryProps
$log.info("AppInsights Custom Event #{eventName} sent successfully")
end
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: sendCustomEvent - error: #{errorStr}")
end
end
def sendExceptionTelemetry(errorStr, properties = nil)
begin
if @@CustomProperties.empty? || @@CustomProperties.nil?
initializeUtility()
elsif @@CustomProperties["DockerVersion"].nil?
getContainerRuntimeInfo()
end
telemetryProps = {}
# add common dimensions
@@CustomProperties.each { |k, v| telemetryProps[k] = v }
# add passed-in dimensions if any
if (!properties.nil? && !properties.empty?)
properties.each { |k, v| telemetryProps[k] = v }
end
if !(@@Tc.nil?)
@@Tc.track_exception errorStr, :properties => telemetryProps
$log.info("AppInsights Exception Telemetry put successfully into the queue")
end
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: sendExceptionTelemetry - error: #{errorStr}")
end
end
#Method to send heartbeat and container inventory count
def sendTelemetry(pluginName, properties)
begin
if @@CustomProperties.empty? || @@CustomProperties.nil?
initializeUtility()
elsif @@CustomProperties["DockerVersion"].nil?
getContainerRuntimeInfo()
end
@@CustomProperties["Computer"] = properties["Computer"]
sendHeartBeatEvent(pluginName)
sendLastProcessedContainerInventoryCountMetric(pluginName, properties)
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: sendTelemetry - error: #{errorStr}")
end
end
#Method to send metric. It will merge passed-in properties with common custom properties
def sendMetricTelemetry(metricName, metricValue, properties)
begin
if (metricName.empty? || metricName.nil?)
$log.warn("SendMetricTelemetry: metricName is missing")
return
end
if @@CustomProperties.empty? || @@CustomProperties.nil?
initializeUtility()
elsif @@CustomProperties["DockerVersion"].nil?
getContainerRuntimeInfo()
end
telemetryProps = {}
# add common dimensions
@@CustomProperties.each { |k, v| telemetryProps[k] = v }
# add passed-in dimensions if any
if (!properties.nil? && !properties.empty?)
properties.each { |k, v| telemetryProps[k] = v }
end
if !(@@Tc.nil?)
@@Tc.track_metric metricName, metricValue,
:kind => ApplicationInsights::Channel::Contracts::DataPointType::MEASUREMENT,
:properties => telemetryProps
$log.info("AppInsights metric Telemetry #{metricName} put successfully into the queue")
end
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: sendMetricTelemetry - error: #{errorStr}")
end
end
def getWorkspaceId()
begin
adminConf = {}
confFile = File.open(@OmsAdminFilePath, "r")
confFile.each_line do |line|
splitStrings = line.split("=")
adminConf[splitStrings[0]] = splitStrings[1]
end
workspaceId = adminConf["WORKSPACE_ID"]
return workspaceId
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: getWorkspaceId - error: #{errorStr}")
end
end
def getWorkspaceCloud()
begin
adminConf = {}
confFile = File.open(@OmsAdminFilePath, "r")
confFile.each_line do |line|
splitStrings = line.split("=")
adminConf[splitStrings[0]] = splitStrings[1]
end
workspaceDomain = adminConf["URL_TLD"].strip
workspaceCloud = "AzureCloud"
if workspaceDomain.casecmp("opinsights.azure.com") == 0
workspaceCloud = "AzureCloud"
elsif workspaceDomain.casecmp("opinsights.azure.cn") == 0
workspaceCloud = "AzureChinaCloud"
elsif workspaceDomain.casecmp("opinsights.azure.us") == 0
workspaceCloud = "AzureUSGovernment"
elsif workspaceDomain.casecmp("opinsights.azure.de") == 0
workspaceCloud = "AzureGermanCloud"
else
workspaceCloud = "Unknown"
end
return workspaceCloud
rescue => errorStr
$log.warn("Exception in AppInsightsUtility: getWorkspaceCloud - error: #{errorStr}")
end
end
end
end