-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathKubernetesApiClient.rb
1461 lines (1381 loc) · 66.9 KB
/
KubernetesApiClient.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/bin/ruby
# frozen_string_literal: true
class KubernetesApiClient
require "json"
require "logger"
require "net/http"
require "net/https"
require "uri"
require "time"
require_relative "oms_common"
require_relative "constants"
require_relative "WatchStream"
require_relative "kubernetes_container_inventory"
@@ApiVersion = "v1"
@@ApiVersionApps = "v1"
@@ApiGroupApps = "apps"
@@ApiGroupHPA = "autoscaling"
@@ApiVersionHPA = "v1"
@@CaFile = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
@@ClusterName = nil
@@ClusterId = nil
@@IsNodeMaster = nil
@@IsAROV3Cluster = nil
#@@IsValidRunningNode = nil
#@@IsLinuxCluster = nil
@@KubeSystemNamespace = "kube-system"
@os_type = ENV["OS_TYPE"]
if !@os_type.nil? && !@os_type.empty? && @os_type.strip.casecmp("windows") == 0
@LogPath = Constants::WINDOWS_LOG_PATH + "kubernetes_client_log.txt"
else
@LogPath = Constants::LINUX_LOG_PATH + "kubernetes_client_log.txt"
end
@Log = Logger.new(@LogPath, 2, 10 * 1048576) #keep last 2 files, max log file size = 10M
@@TokenFileName = "/var/run/secrets/kubernetes.io/serviceaccount/token"
@@TokenStr = nil
@@cpuLimitsTelemetryTimeTracker = DateTime.now.to_time.to_i
@@cpuRequestsTelemetryTimeTracker = DateTime.now.to_time.to_i
@@memoryLimitsTelemetryTimeTracker = DateTime.now.to_time.to_i
@@memoryRequestsTelemetryTimeTracker = DateTime.now.to_time.to_i
@@resourceLimitsTelemetryHash = {}
def initialize
end
class << self
def getKubeResourceInfo(resource, api_group: nil)
headers = {}
response = nil
@Log.info "Getting Kube resource: #{resource}"
begin
resourceUri = getResourceUri(resource, api_group)
if !resourceUri.nil?
uri = URI.parse(resourceUri)
if !File.exist?(@@CaFile)
raise "#{@@CaFile} doesnt exist"
else
Net::HTTP.start(uri.host, uri.port, :use_ssl => true, :ca_file => @@CaFile, :verify_mode => OpenSSL::SSL::VERIFY_PEER, :open_timeout => 20, :read_timeout => 40) do |http|
kubeApiRequest = Net::HTTP::Get.new(uri.request_uri)
kubeApiRequest["Authorization"] = "Bearer " + getTokenStr
@Log.info "KubernetesAPIClient::getKubeResourceInfo : Making request to #{uri.request_uri} @ #{Time.now.utc.iso8601}"
response = http.request(kubeApiRequest)
@Log.info "KubernetesAPIClient::getKubeResourceInfo : Got response of #{response.code} for #{uri.request_uri} @ #{Time.now.utc.iso8601}"
end
end
end
rescue => error
@Log.warn("kubernetes api request failed: #{error} for #{resource} @ #{Time.now.utc.iso8601}")
end
if (!response.nil?)
if (!response.body.nil? && response.body.empty?)
@Log.warn("KubernetesAPIClient::getKubeResourceInfo : Got empty response from Kube API for #{resource} @ #{Time.now.utc.iso8601}")
end
end
return response
end
def getKubeResourceInfoV2(resource, api_group: nil)
headers = {}
response = nil
responseCode = nil
@Log.info "Getting Kube resource: #{resource}"
begin
resourceUri = getResourceUri(resource, api_group)
if !resourceUri.nil?
uri = URI.parse(resourceUri)
if !File.exist?(@@CaFile)
raise "#{@@CaFile} doesnt exist"
else
Net::HTTP.start(uri.host, uri.port, :use_ssl => true, :ca_file => @@CaFile, :verify_mode => OpenSSL::SSL::VERIFY_PEER, :open_timeout => 20, :read_timeout => 40) do |http|
kubeApiRequest = Net::HTTP::Get.new(uri.request_uri)
kubeApiRequest["Authorization"] = "Bearer " + getTokenStr
@Log.info "KubernetesAPIClient::getKubeResourceInfoV2 : Making request to #{uri.request_uri} @ #{Time.now.utc.iso8601}"
response = http.request(kubeApiRequest)
responseCode = response.code
@Log.info "KubernetesAPIClient::getKubeResourceInfoV2 : Got response of #{response.code} for #{uri.request_uri} @ #{Time.now.utc.iso8601}"
end
end
end
rescue => error
@Log.warn("kubernetes api request failed: #{error} for #{resource} @ #{Time.now.utc.iso8601}")
end
if (!response.nil?)
if (!response.body.nil? && response.body.empty?)
@Log.warn("KubernetesAPIClient::getKubeResourceInfoV2 : Got empty response from Kube API for #{resource} @ #{Time.now.utc.iso8601}")
end
end
return responseCode, response
end
def getTokenStr
return @@TokenStr if !@@TokenStr.nil?
begin
if File.exist?(@@TokenFileName) && File.readable?(@@TokenFileName)
@@TokenStr = File.read(@@TokenFileName).strip
return @@TokenStr
else
@Log.warn("Unable to read token string from #{@@TokenFileName}: #{error}")
return nil
end
end
end
def getClusterRegion(env = ENV)
if env["AKS_REGION"]
return env["AKS_REGION"]
else
@Log.warn ("Kubernetes environment variable not set AKS_REGION. Unable to get cluster region.")
return nil
end
end
def getResourceUri(resource, api_group, env = ENV)
begin
if env["KUBERNETES_SERVICE_HOST"] && env["KUBERNETES_PORT_443_TCP_PORT"]
if api_group.nil?
return "https://#{env["KUBERNETES_SERVICE_HOST"]}:#{env["KUBERNETES_PORT_443_TCP_PORT"]}/api/" + @@ApiVersion + "/" + resource
elsif api_group == @@ApiGroupApps
return "https://#{env["KUBERNETES_SERVICE_HOST"]}:#{env["KUBERNETES_PORT_443_TCP_PORT"]}/apis/apps/" + @@ApiVersionApps + "/" + resource
elsif api_group == @@ApiGroupHPA
return "https://#{env["KUBERNETES_SERVICE_HOST"]}:#{env["KUBERNETES_PORT_443_TCP_PORT"]}/apis/" + @@ApiGroupHPA + "/" + @@ApiVersionHPA + "/" + resource
end
else
@Log.warn ("Kubernetes environment variable not set KUBERNETES_SERVICE_HOST: #{env["KUBERNETES_SERVICE_HOST"]} KUBERNETES_PORT_443_TCP_PORT: #{env["KUBERNETES_PORT_443_TCP_PORT"]}. Unable to form resourceUri")
return nil
end
end
end
def getClusterName(env = ENV)
return @@ClusterName if !@@ClusterName.nil?
@@ClusterName = "None"
begin
#try getting resource ID for aks
cluster = env["AKS_RESOURCE_ID"]
if cluster && !cluster.nil? && !cluster.empty?
@@ClusterName = cluster.split("/").last
else
cluster = env["ACS_RESOURCE_NAME"]
if cluster && !cluster.nil? && !cluster.empty?
@@ClusterName = cluster
else
kubesystemResourceUri = "namespaces/" + @@KubeSystemNamespace + "/pods"
@Log.info("KubernetesApiClient::getClusterName : Getting pods from Kube API @ #{Time.now.utc.iso8601}")
podInfo = JSON.parse(getKubeResourceInfo(kubesystemResourceUri).body)
@Log.info("KubernetesApiClient::getClusterName : Done getting pods from Kube API @ #{Time.now.utc.iso8601}")
podInfo["items"].each do |items|
if items["metadata"]["name"].include? "kube-controller-manager"
items["spec"]["containers"][0]["command"].each do |command|
if command.include? "--cluster-name"
@@ClusterName = command.split("=")[1]
end
end
end
end
end
end
rescue => error
@Log.warn("getClusterName failed: #{error}")
end
return @@ClusterName
end
def getClusterId(env = ENV)
return @@ClusterId if !@@ClusterId.nil?
#By default initialize ClusterId to ClusterName.
#<TODO> In ACS/On-prem, we need to figure out how we can generate ClusterId
# Dilipr: Spoof the subid by generating md5 hash of cluster name, and taking some constant parts of it.
# e.g. md5 digest is 128 bits = 32 character in hex. Get first 16 and get a guid, and the next 16 to get resource id
@@ClusterId = getClusterName
begin
cluster = env["AKS_RESOURCE_ID"]
if cluster && !cluster.nil? && !cluster.empty?
@@ClusterId = cluster
end
rescue => error
@Log.warn("getClusterId failed: #{error}")
end
return @@ClusterId
end
def isAROV3Cluster
return @@IsAROV3Cluster if !@@IsAROV3Cluster.nil?
@@IsAROV3Cluster = false
begin
cluster = getClusterId
if !cluster.nil? && !cluster.empty? && cluster.downcase.include?("/microsoft.containerservice/openshiftmanagedclusters")
@@IsAROV3Cluster = true
end
rescue => error
@Log.warn("KubernetesApiClient::IsAROV3Cluster : IsAROV3Cluster failed #{error}")
end
return @@IsAROV3Cluster
end
def isAROv3MasterOrInfraPod(nodeName)
return isAROV3Cluster() && (!nodeName.nil? && (nodeName.downcase.start_with?("infra-") || nodeName.downcase.start_with?("master-")))
end
def isNodeMaster
return @@IsNodeMaster if !@@IsNodeMaster.nil?
@@IsNodeMaster = false
begin
@Log.info("KubernetesApiClient::isNodeMaster : Getting nodes from Kube API @ #{Time.now.utc.iso8601}")
allNodesInfo = JSON.parse(getKubeResourceInfo("nodes").body)
@Log.info("KubernetesApiClient::isNodeMaster : Done getting nodes from Kube API @ #{Time.now.utc.iso8601}")
if !allNodesInfo.nil? && !allNodesInfo.empty?
thisNodeName = OMS::Common.get_hostname
allNodesInfo["items"].each do |item|
if item["metadata"]["name"].casecmp(thisNodeName) == 0
if item["metadata"]["labels"]["kubernetes.io/role"].to_s.include?("master") || item["metadata"]["labels"]["role"].to_s.include?("master")
@@IsNodeMaster = true
end
break
end
end
end
rescue => error
@Log.warn("KubernetesApiClient::isNodeMaster : node role request failed: #{error}")
end
return @@IsNodeMaster
end
def getNodesResourceUri(nodesResourceUri)
begin
# For ARO v3 cluster, filter out all other node roles other than compute
if isAROV3Cluster()
if !nodesResourceUri.nil? && !nodesResourceUri.index("?").nil?
nodesResourceUri = nodesResourceUri + "&labelSelector=node-role.kubernetes.io%2Fcompute%3Dtrue"
else
nodesResourceUri = nodesResourceUri + "labelSelector=node-role.kubernetes.io%2Fcompute%3Dtrue"
end
end
rescue => error
@Log.warn("getNodesResourceUri failed: #{error}")
end
return nodesResourceUri
end
#def isValidRunningNode
# return @@IsValidRunningNode if !@@IsValidRunningNode.nil?
# @@IsValidRunningNode = false
# begin
# thisNodeName = OMS::Common.get_hostname
# if isLinuxCluster
# # Run on agent node [0]
# @@IsValidRunningNode = !isNodeMaster && thisNodeName.to_s.split('-').last == '0'
# else
# # Run on master node [0]
# @@IsValidRunningNode = isNodeMaster && thisNodeName.to_s.split('-').last == '0'
# end
# rescue => error
# @Log.warn("Checking Node Type failed: #{error}")
# end
# if(@@IsValidRunningNode == true)
# @Log.info("Electing current node to talk to k8 api")
# else
# @Log.info("Not Electing current node to talk to k8 api")
# end
# return @@IsValidRunningNode
#end
#def isLinuxCluster
# return @@IsLinuxCluster if !@@IsLinuxCluster.nil?
# @@IsLinuxCluster = true
# begin
# @Log.info("KubernetesApiClient::isLinuxCluster : Getting nodes from Kube API @ #{Time.now.utc.iso8601}")
# allNodesInfo = JSON.parse(getKubeResourceInfo('nodes').body)
# @Log.info("KubernetesApiClient::isLinuxCluster : Done getting nodes from Kube API @ #{Time.now.utc.iso8601}")
# if !allNodesInfo.nil? && !allNodesInfo.empty?
# allNodesInfo['items'].each do |item|
# if !(item['status']['nodeInfo']['operatingSystem'].casecmp('linux') == 0)
# @@IsLinuxCluster = false
# break
# end
# end
# end
# rescue => error
# @Log.warn("KubernetesApiClient::isLinuxCluster : node role request failed: #{error}")
# end
# return @@IsLinuxCluster
#end
# returns an arry of pods (json)
def getPods(namespace)
pods = []
begin
kubesystemResourceUri = "namespaces/" + namespace + "/pods"
podInfo = JSON.parse(getKubeResourceInfo(kubesystemResourceUri).body)
podInfo["items"].each do |items|
pods.push items
end
rescue => error
@Log.warn("List pods request failed: #{error}")
end
return pods
end
# returns a hash of windows node names and their internal IPs
def getWindowsNodes
winNodes = []
begin
# get only windows nodes
resourceUri = getNodesResourceUri("nodes?labelSelector=kubernetes.io%2Fos%3Dwindows")
nodeInventory = JSON.parse(getKubeResourceInfo(resourceUri).body)
@Log.info "KubernetesAPIClient::getWindowsNodes : Got nodes from kube api"
if (!nodeInventory.empty?)
nodeInventory["items"].each do |item|
# check for windows operating system in node metadata
winNode = {}
nodeStatus = item["status"]
nodeMetadata = item["metadata"]
if !nodeStatus.nil? && !nodeStatus["nodeInfo"].nil? && !nodeStatus["nodeInfo"]["operatingSystem"].nil?
operatingSystem = nodeStatus["nodeInfo"]["operatingSystem"]
if (operatingSystem.is_a?(String) && operatingSystem.casecmp("windows") == 0)
nodeStatusAddresses = nodeStatus["addresses"]
if !nodeStatusAddresses.nil?
nodeStatusAddresses.each do |address|
winNode[address["type"]] = address["address"]
end
winNodes.push(winNode)
end
end
end
end
end
return winNodes
rescue => error
@Log.warn("Error in get windows nodes: #{error}")
return nil
end
end
def getWindowsNodesArray
winNodeArray = []
begin
# get only windows nodes
resourceUri = getNodesResourceUri("nodes?labelSelector=kubernetes.io%2Fos%3Dwindows")
nodeInventory = JSON.parse(getKubeResourceInfo(resourceUri).body)
@Log.info "KubernetesAPIClient::getWindowsNodes : Got nodes from kube api"
if (!nodeInventory.empty?)
nodeInventory["items"].each do |item|
# check for windows operating system in node metadata
nodeStatus = item["status"]
nodeMetadata = item["metadata"]
if !nodeStatus.nil? && !nodeStatus["nodeInfo"].nil? && !nodeStatus["nodeInfo"]["operatingSystem"].nil?
operatingSystem = nodeStatus["nodeInfo"]["operatingSystem"]
if (operatingSystem.is_a?(String) && operatingSystem.casecmp("windows") == 0)
# Adding windows nodes to winNodeArray so that it can be used in kubepodinventory to send ContainerInventory data
# to get images and image tags for containers in windows nodes
if !nodeMetadata.nil? && !nodeMetadata["name"].nil?
winNodeArray.push(nodeMetadata["name"])
end
end
end
end
end
rescue => error
@Log.warn("KubernetesApiClient::getWindowsNodesArray:failed with an error: #{error}")
end
return winNodeArray
end
def getContainerIDs(namespace)
containers = Hash.new
begin
kubesystemResourceUri = "namespaces/" + namespace + "/pods"
@Log.info("KubernetesApiClient::getContainerIDs : Getting pods from Kube API @ #{Time.now.utc.iso8601}")
podInfo = JSON.parse(getKubeResourceInfo(kubesystemResourceUri).body)
@Log.info("KubernetesApiClient::getContainerIDs : Done getting pods from Kube API @ #{Time.now.utc.iso8601}")
podInfo["items"].each do |item|
if (!item["status"].nil? && !item["status"].empty? && !item["status"]["containerStatuses"].nil? && !item["status"]["containerStatuses"].empty?)
item["status"]["containerStatuses"].each do |cntr|
containers[cntr["containerID"]] = "kube-system"
end
end
end
rescue => error
@Log.warn("KubernetesApiClient::getContainerIDs : List ContainerIDs request failed: #{error}")
end
return containers
end
def getContainerLogs(namespace, pod, container, showTimeStamp)
containerLogs = ""
begin
kubesystemResourceUri = "namespaces/" + namespace + "/pods/" + pod + "/log" + "?container=" + container
if showTimeStamp
kubesystemResourceUri += "×tamps=true"
end
@Log.info("KubernetesApiClient::getContainerLogs : Getting logs from Kube API @ #{Time.now.utc.iso8601}")
containerLogs = getKubeResourceInfo(kubesystemResourceUri).body
@Log.info("KubernetesApiClient::getContainerLogs : Done getting logs from Kube API @ #{Time.now.utc.iso8601}")
rescue => error
@Log.warn("Pod logs request failed: #{error}")
end
return containerLogs
end
def getContainerLogsSinceTime(namespace, pod, container, since, showTimeStamp)
containerLogs = ""
begin
kubesystemResourceUri = "namespaces/" + namespace + "/pods/" + pod + "/log" + "?container=" + container + "&sinceTime=" + since
kubesystemResourceUri = URI.escape(kubesystemResourceUri, ":.+") # HTML URL Encoding for date
if showTimeStamp
kubesystemResourceUri += "×tamps=true"
end
@Log.info("calling #{kubesystemResourceUri}")
@Log.info("KubernetesApiClient::getContainerLogsSinceTime : Getting logs from Kube API @ #{Time.now.utc.iso8601}")
containerLogs = getKubeResourceInfo(kubesystemResourceUri).body
@Log.info("KubernetesApiClient::getContainerLogsSinceTime : Done getting logs from Kube API @ #{Time.now.utc.iso8601}")
rescue => error
@Log.warn("Pod logs request failed: #{error}")
end
return containerLogs
end
def getPodUid(podNameSpace, podMetadata)
podUid = nil
begin
if podNameSpace.eql?("kube-system") && !podMetadata.key?("ownerReferences")
# The above case seems to be the only case where you have horizontal scaling of pods
# but no controller, in which case cAdvisor picks up kubernetes.io/config.hash
# instead of the actual poduid. Since this uid is not being surface into the UX
# its ok to use this.
# Use kubernetes.io/config.hash to be able to correlate with cadvisor data
if podMetadata["annotations"].nil?
return nil
else
podUid = podMetadata["annotations"]["kubernetes.io/config.hash"]
end
else
podUid = podMetadata["uid"]
end
rescue => errorStr
@Log.warn "KubernetesApiClient::getPodUid:Failed to get poduid: #{errorStr}"
ApplicationInsightsUtility.sendExceptionTelemetry(errorStr)
end
return podUid
end
def getContainerResourceRequestsAndLimits(pod, metricCategory, metricNameToCollect, metricNametoReturn, nodeAllocatableRecord, metricTime = Time.now.utc.iso8601)
metricItems = []
begin
clusterId = getClusterId
podNameSpace = pod["metadata"]["namespace"]
podUid = getPodUid(podNameSpace, pod["metadata"])
if podUid.nil?
return metricItems
end
podName = pod["metadata"]["name"]
nodeName = ""
#for unscheduled (non-started) pods nodeName does NOT exist
if !pod["spec"]["nodeName"].nil?
nodeName = pod["spec"]["nodeName"]
end
# For ARO, skip the pods scheduled on to master or infra nodes to ingest
if isAROv3MasterOrInfraPod(nodeName)
return metricItems
end
podContainers = []
if !pod["spec"]["containers"].nil? && !pod["spec"]["containers"].empty?
podContainers = podContainers + pod["spec"]["containers"]
end
# Adding init containers to the record list as well.
if !pod["spec"]["initContainers"].nil? && !pod["spec"]["initContainers"].empty?
podContainers = podContainers + pod["spec"]["initContainers"]
end
if (!podContainers.nil? && !podContainers.empty? && !pod["spec"]["nodeName"].nil?)
podContainers.each do |container|
containerName = container["name"]
#metricTime = Time.now.utc.iso8601 #2018-01-30T19:36:14Z
if (!container["resources"].nil? && !container["resources"].empty? && !container["resources"][metricCategory].nil? && !container["resources"][metricCategory][metricNameToCollect].nil?)
metricValue = getMetricNumericValue(metricNameToCollect, container["resources"][metricCategory][metricNameToCollect])
metricProps = {}
metricProps["Timestamp"] = metricTime
metricProps["Host"] = nodeName
# Adding this so that it is not set by base omsagent since it was not set earlier and being set by base omsagent
metricProps["Computer"] = nodeName
metricProps["ObjectName"] = "K8SContainer"
metricProps["InstanceName"] = clusterId + "/" + podUid + "/" + containerName
metricCollection = {}
metricCollection["CounterName"] = metricNametoReturn
metricCollection["Value"] = metricValue
metricProps["json_Collections"] = []
metricCollections = []
metricCollections.push(metricCollection)
metricProps["json_Collections"] = metricCollections.to_json
metricItems.push(metricProps)
if isAddonResizerVPAEnabled()
sendReplicasetAgentRequestsAndLimitsTelemetry(podName, podNameSpace, containerName, metricNametoReturn, metricValue)
end
else
#No container level limit for the given metric, so default to node level limit
if (metricCategory == "limits" && !nodeAllocatableRecord.nil? && !nodeAllocatableRecord.empty? && nodeAllocatableRecord.has_key?(metricNameToCollect))
metricValue = getMetricNumericValue(metricNameToCollect, nodeAllocatableRecord[metricNameToCollect])
metricProps = {}
metricProps["Timestamp"] = metricTime
metricProps["Host"] = nodeName
# Adding this so that it is not set by base omsagent since it was not set earlier and being set by base omsagent
metricProps["Computer"] = nodeName
metricProps["ObjectName"] = "K8SContainer"
metricProps["InstanceName"] = clusterId + "/" + podUid + "/" + containerName
metricCollection = {}
metricCollection["CounterName"] = metricNametoReturn
metricCollection["Value"] = metricValue
metricProps["json_Collections"] = []
metricCollections = []
metricCollections.push(metricCollection)
metricProps["json_Collections"] = metricCollections.to_json
metricItems.push(metricProps)
end
end
end
end
rescue => error
@Log.warn("getcontainerResourceRequestsAndLimits failed: #{error} for metric #{metricCategory} #{metricNameToCollect}")
return metricItems
end
return metricItems
end #getContainerResourceRequestAndLimits
def getContainerResourceRequestsAndLimitsAsInsightsMetrics(pod, metricCategory, metricNameToCollect, metricNametoReturn, nodeAllocatableRecord, metricTime = Time.now.utc.iso8601)
metricItems = []
begin
clusterId = getClusterId
clusterName = getClusterName
podNameSpace = pod["metadata"]["namespace"]
if podNameSpace.eql?("kube-system") && !pod["metadata"].key?("ownerReferences")
# The above case seems to be the only case where you have horizontal scaling of pods
# but no controller, in which case cAdvisor picks up kubernetes.io/config.hash
# instead of the actual poduid. Since this uid is not being surface into the UX
# its ok to use this.
# Use kubernetes.io/config.hash to be able to correlate with cadvisor data
if pod["metadata"]["annotations"].nil?
return metricItems
else
podUid = pod["metadata"]["annotations"]["kubernetes.io/config.hash"]
end
else
podUid = pod["metadata"]["uid"]
end
podContainers = []
if !pod["spec"]["containers"].nil? && !pod["spec"]["containers"].empty?
podContainers = podContainers + pod["spec"]["containers"]
end
# Adding init containers to the record list as well.
if !pod["spec"]["initContainers"].nil? && !pod["spec"]["initContainers"].empty?
podContainers = podContainers + pod["spec"]["initContainers"]
end
if (!podContainers.nil? && !podContainers.empty?)
if (!pod["spec"]["nodeName"].nil?)
nodeName = pod["spec"]["nodeName"]
else
nodeName = "" #unscheduled pod. We still want to collect limits & requests for GPU
end
podContainers.each do |container|
metricValue = nil
containerName = container["name"]
#metricTime = Time.now.utc.iso8601 #2018-01-30T19:36:14Z
if (!container["resources"].nil? && !container["resources"].empty? && !container["resources"][metricCategory].nil? && !container["resources"][metricCategory][metricNameToCollect].nil?)
metricValue = getMetricNumericValue(metricNameToCollect, container["resources"][metricCategory][metricNameToCollect])
else
#No container level limit for the given metric, so default to node level limit for non-gpu metrics
if (metricNameToCollect.downcase != "nvidia.com/gpu") && (metricNameToCollect.downcase != "amd.com/gpu")
if !nodeAllocatableRecord.nil? && !nodeAllocatableRecord.empty? && nodeAllocatableRecord.has_key?(metricNameToCollect)
metricValue = getMetricNumericValue(metricNameToCollect, nodeAllocatableRecord[metricNameToCollect])
end
end
end
if (!metricValue.nil?)
metricItem = {}
metricItem["CollectionTime"] = metricTime
metricItem["Computer"] = nodeName
metricItem["Name"] = metricNametoReturn
metricItem["Value"] = metricValue
metricItem["Origin"] = Constants::INSIGHTSMETRICS_TAGS_ORIGIN
metricItem["Namespace"] = Constants::INSIGHTSMETRICS_TAGS_GPU_NAMESPACE
metricTags = {}
metricTags[Constants::INSIGHTSMETRICS_TAGS_CLUSTERID] = clusterId
metricTags[Constants::INSIGHTSMETRICS_TAGS_CLUSTERNAME] = clusterName
metricTags[Constants::INSIGHTSMETRICS_TAGS_CONTAINER_NAME] = podUid + "/" + containerName
#metricTags[Constants::INSIGHTSMETRICS_TAGS_K8SNAMESPACE] = podNameSpace
metricItem["Tags"] = metricTags
metricItems.push(metricItem)
end
end
end
rescue => error
@Log.warn("getcontainerResourceRequestsAndLimitsAsInsightsMetrics failed: #{error} for metric #{metricCategory} #{metricNameToCollect}")
return metricItems
end
return metricItems
end #getContainerResourceRequestAndLimitsAsInsightsMetrics
def parseNodeLimits(metricJSON, metricCategory, metricNameToCollect, metricNametoReturn, metricTime = Time.now.utc.iso8601)
metricItems = []
begin
metricInfo = metricJSON
clusterId = getClusterId
#Since we are getting all node data at the same time and kubernetes doesnt specify a timestamp for the capacity and allocation metrics,
#if we are coming up with the time it should be same for all nodes
#metricTime = Time.now.utc.iso8601 #2018-01-30T19:36:14Z
metricInfo["items"].each do |node|
metricItem = parseNodeLimitsFromNodeItem(node, metricCategory, metricNameToCollect, metricNametoReturn, metricTime)
if !metricItem.nil? && !metricItem.empty?
metricItems.push(metricItem)
end
end
rescue => error
@Log.warn("parseNodeLimits failed: #{error} for metric #{metricCategory} #{metricNameToCollect}")
end
return metricItems
end #parseNodeLimits
def parseNodeLimitsFromNodeItem(node, metricCategory, metricNameToCollect, metricNametoReturn, metricTime = Time.now.utc.iso8601)
metricItem = {}
begin
clusterId = getClusterId
#Since we are getting all node data at the same time and kubernetes doesnt specify a timestamp for the capacity and allocation metrics,
#if we are coming up with the time it should be same for all nodes
#metricTime = Time.now.utc.iso8601 #2018-01-30T19:36:14Z
if (!node["status"][metricCategory].nil?) && (!node["status"][metricCategory][metricNameToCollect].nil?)
# metricCategory can be "capacity" or "allocatable" and metricNameToCollect can be "cpu" or "memory"
metricValue = getMetricNumericValue(metricNameToCollect, node["status"][metricCategory][metricNameToCollect])
metricItem["Timestamp"] = metricTime
metricItem["Host"] = node["metadata"]["name"]
# Adding this so that it is not set by base omsagent since it was not set earlier and being set by base omsagent
metricItem["Computer"] = node["metadata"]["name"]
metricItem["ObjectName"] = "K8SNode"
metricItem["InstanceName"] = clusterId + "/" + node["metadata"]["name"]
metricCollection = {}
metricCollection["CounterName"] = metricNametoReturn
metricCollection["Value"] = metricValue
metricCollections = []
metricCollections.push(metricCollection)
metricItem["json_Collections"] = []
metricItem["json_Collections"] = metricCollections.to_json
end
rescue => error
@Log.warn("parseNodeLimitsFromNodeItem failed: #{error} for metric #{metricCategory} #{metricNameToCollect}")
end
return metricItem
end #parseNodeLimitsFromNodeItem
def parseNodeLimitsAsInsightsMetrics(node, metricCategory, metricNameToCollect, metricNametoReturn, metricTime = Time.now.utc.iso8601)
metricItem = {}
begin
#Since we are getting all node data at the same time and kubernetes doesnt specify a timestamp for the capacity and allocation metrics,
#if we are coming up with the time it should be same for all nodes
#metricTime = Time.now.utc.iso8601 #2018-01-30T19:36:14Z
if (!node["status"][metricCategory].nil?) && (!node["status"][metricCategory][metricNameToCollect].nil?)
clusterId = getClusterId
clusterName = getClusterName
# metricCategory can be "capacity" or "allocatable" and metricNameToCollect can be "cpu" or "memory" or "amd.com/gpu" or "nvidia.com/gpu"
metricValue = getMetricNumericValue(metricNameToCollect, node["status"][metricCategory][metricNameToCollect])
metricItem["CollectionTime"] = metricTime
metricItem["Computer"] = node["metadata"]["name"]
metricItem["Name"] = metricNametoReturn
metricItem["Value"] = metricValue
metricItem["Origin"] = Constants::INSIGHTSMETRICS_TAGS_ORIGIN
metricItem["Namespace"] = Constants::INSIGHTSMETRICS_TAGS_GPU_NAMESPACE
metricTags = {}
metricTags[Constants::INSIGHTSMETRICS_TAGS_CLUSTERID] = clusterId
metricTags[Constants::INSIGHTSMETRICS_TAGS_CLUSTERNAME] = clusterName
metricTags[Constants::INSIGHTSMETRICS_TAGS_GPU_VENDOR] = metricNameToCollect
metricItem["Tags"] = metricTags
end
rescue => error
@Log.warn("parseNodeLimitsAsInsightsMetrics failed: #{error} for metric #{metricCategory} #{metricNameToCollect}")
end
return metricItem
end
def getMetricNumericValue(metricName, metricVal)
metricValue = metricVal.downcase
begin
case metricName
when "memory" #convert to bytes for memory
#https://kubernetes.io/docs/tasks/configure-pod-container/assign-memory-resource/
if (metricValue.end_with?("ki"))
metricValue.chomp!("ki")
metricValue = Float(metricValue) * 1024.0 ** 1
elsif (metricValue.end_with?("mi"))
metricValue.chomp!("mi")
metricValue = Float(metricValue) * 1024.0 ** 2
elsif (metricValue.end_with?("gi"))
metricValue.chomp!("gi")
metricValue = Float(metricValue) * 1024.0 ** 3
elsif (metricValue.end_with?("ti"))
metricValue.chomp!("ti")
metricValue = Float(metricValue) * 1024.0 ** 4
elsif (metricValue.end_with?("pi"))
metricValue.chomp!("pi")
metricValue = Float(metricValue) * 1024.0 ** 5
elsif (metricValue.end_with?("ei"))
metricValue.chomp!("ei")
metricValue = Float(metricValue) * 1024.0 ** 6
elsif (metricValue.end_with?("zi"))
metricValue.chomp!("zi")
metricValue = Float(metricValue) * 1024.0 ** 7
elsif (metricValue.end_with?("yi"))
metricValue.chomp!("yi")
metricValue = Float(metricValue) * 1024.0 ** 8
elsif (metricValue.end_with?("k"))
metricValue.chomp!("k")
metricValue = Float(metricValue) * 1000.0 ** 1
elsif (metricValue.end_with?("m"))
#original value before downcase ending with M is megabyte and value ending with m is milli-byte
metricValue.chomp!("m")
if (metricVal.end_with?("M"))
metricValue = Float(metricValue) * 1000.0 ** 2
else
metricValue = Float(metricValue) / 1000.0
end
elsif (metricValue.end_with?("g"))
metricValue.chomp!("g")
metricValue = Float(metricValue) * 1000.0 ** 3
elsif (metricValue.end_with?("t"))
metricValue.chomp!("t")
metricValue = Float(metricValue) * 1000.0 ** 4
elsif (metricValue.end_with?("p"))
metricValue.chomp!("p")
metricValue = Float(metricValue) * 1000.0 ** 5
elsif (metricValue.end_with?("e"))
metricValue.chomp!("e")
metricValue = Float(metricValue) * 1000.0 ** 6
elsif (metricValue.end_with?("z"))
metricValue.chomp!("z")
metricValue = Float(metricValue) * 1000.0 ** 7
elsif (metricValue.end_with?("y"))
metricValue.chomp!("y")
metricValue = Float(metricValue) * 1000.0 ** 8
else #assuming there are no units specified, it is bytes (the below conversion will fail for other unsupported 'units')
metricValue = Float(metricValue)
end
when "cpu" #convert to nanocores for cpu
#https://kubernetes.io/docs/tasks/configure-pod-container/assign-cpu-resource/
if (metricValue.end_with?("m"))
metricValue.chomp!("m")
metricValue = Float(metricValue) * 1000.0 ** 2
elsif (metricValue.end_with?("k"))
metricValue.chomp!("k")
metricValue = Float(metricValue) * 1000.0
else #assuming no units specified, it is cores that we are converting to nanocores (the below conversion will fail for other unsupported 'units')
metricValue = Float(metricValue) * 1000.0 ** 3
end
when "nvidia.com/gpu"
metricValue = Float(metricValue) * 1.0
when "amd.com/gpu"
metricValue = Float(metricValue) * 1.0
else
@Log.warn("getMetricNumericValue: Unsupported metric #{metricName}. Returning 0 for metric value")
metricValue = 0
end #case statement
rescue => error
@Log.warn("getMetricNumericValue failed: #{error} for metric #{metricName} with value #{metricVal}. Returning 0 for metric value")
return 0
end
return metricValue
end # getMetricNumericValue
def getResourcesAndContinuationTokenV2(uri, api_group: nil)
continuationToken = nil
resourceInventory = nil
responseCode = nil
begin
@Log.info "KubernetesApiClient::getResourcesAndContinuationTokenV2 : Getting resources from Kube API using url: #{uri} @ #{Time.now.utc.iso8601}"
responseCode, resourceInfo = getKubeResourceInfoV2(uri, api_group: api_group)
@Log.info "KubernetesApiClient::getResourcesAndContinuationTokenV2 : Done getting resources from Kube API using url: #{uri} @ #{Time.now.utc.iso8601}"
if !responseCode.nil? && responseCode == "200" && !resourceInfo.nil?
@Log.info "KubernetesApiClient::getResourcesAndContinuationTokenV2:Start:Parsing data for #{uri} using JSON @ #{Time.now.utc.iso8601}"
resourceInventory = JSON.parse(resourceInfo.body)
@Log.info "KubernetesApiClient::getResourcesAndContinuationTokenV2:End:Parsing data for #{uri} using JSON @ #{Time.now.utc.iso8601}"
resourceInfo = nil
end
if (!resourceInventory.nil? && !resourceInventory["metadata"].nil?)
continuationToken = resourceInventory["metadata"]["continue"]
end
rescue => errorStr
@Log.warn "KubernetesApiClient::getResourcesAndContinuationTokenV2:Failed in get resources for #{uri} and continuation token: #{errorStr}"
ApplicationInsightsUtility.sendExceptionTelemetry(errorStr)
resourceInventory = nil
end
return continuationToken, resourceInventory, responseCode
end #getResourcesAndContinuationTokenV2
def getResourcesAndContinuationToken(uri, api_group: nil)
continuationToken = nil
resourceInventory = nil
begin
@Log.info "KubernetesApiClient::getResourcesAndContinuationToken : Getting resources from Kube API using url: #{uri} @ #{Time.now.utc.iso8601}"
resourceInfo = getKubeResourceInfo(uri, api_group: api_group)
@Log.info "KubernetesApiClient::getResourcesAndContinuationToken : Done getting resources from Kube API using url: #{uri} @ #{Time.now.utc.iso8601}"
if !resourceInfo.nil?
@Log.info "KubernetesApiClient::getResourcesAndContinuationToken:Start:Parsing data for #{uri} using JSON @ #{Time.now.utc.iso8601}"
resourceInventory = JSON.parse(resourceInfo.body)
@Log.info "KubernetesApiClient::getResourcesAndContinuationToken:End:Parsing data for #{uri} using JSON @ #{Time.now.utc.iso8601}"
resourceInfo = nil
end
if (!resourceInventory.nil? && !resourceInventory["metadata"].nil?)
continuationToken = resourceInventory["metadata"]["continue"]
end
rescue => errorStr
@Log.warn "KubernetesApiClient::getResourcesAndContinuationToken:Failed in get resources for #{uri} and continuation token: #{errorStr}"
ApplicationInsightsUtility.sendExceptionTelemetry(errorStr)
resourceInventory = nil
end
return continuationToken, resourceInventory
end #getResourcesAndContinuationToken
def getKubeAPIServerUrl(env = ENV)
apiServerUrl = nil
begin
if env["KUBERNETES_SERVICE_HOST"] && env["KUBERNETES_PORT_443_TCP_PORT"]
apiServerUrl = "https://#{env["KUBERNETES_SERVICE_HOST"]}:#{env["KUBERNETES_PORT_443_TCP_PORT"]}"
else
@Log.warn "Kubernetes environment variable not set KUBERNETES_SERVICE_HOST: #{env["KUBERNETES_SERVICE_HOST"]} KUBERNETES_PORT_443_TCP_PORT: #{env["KUBERNETES_PORT_443_TCP_PORT"]}. Unable to form resourceUri"
end
rescue => errorStr
@Log.warn "KubernetesApiClient::getKubeAPIServerUrl:Failed #{errorStr}"
end
return apiServerUrl
end
def getKubeServicesInventoryRecords(serviceList, batchTime = Time.utc.iso8601)
kubeServiceRecords = []
begin
if (!serviceList.nil? && !serviceList.empty? && serviceList.key?("items") && !serviceList["items"].nil? && !serviceList["items"].empty?)
servicesCount = serviceList["items"].length
@Log.info("KubernetesApiClient::getKubeServicesInventoryRecords : number of services in serviceList #{servicesCount} @ #{Time.now.utc.iso8601}")
serviceList["items"].each do |item|
kubeServiceRecord = {}
kubeServiceRecord["CollectionTime"] = batchTime #This is the time that is mapped to become TimeGenerated
kubeServiceRecord["ServiceName"] = item["metadata"]["name"]
kubeServiceRecord["Namespace"] = item["metadata"]["namespace"]
kubeServiceRecord["SelectorLabels"] = [item["spec"]["selector"]]
# added these before emit to avoid memory foot print
# kubeServiceRecord["ClusterId"] = KubernetesApiClient.getClusterId
# kubeServiceRecord["ClusterName"] = KubernetesApiClient.getClusterName
kubeServiceRecord["ClusterIP"] = item["spec"]["clusterIP"]
kubeServiceRecord["ServiceType"] = item["spec"]["type"]
kubeServiceRecords.push(kubeServiceRecord.dup)
end
end
rescue => errorStr
@Log.warn "KubernetesApiClient::getKubeServicesInventoryRecords:Failed with an error : #{errorStr}"
ApplicationInsightsUtility.sendExceptionTelemetry(errorStr)
end
return kubeServiceRecords
end
# Accepts the following options:
# :namespace (string) - the namespace of the entity.
# :name (string) - the name of the entity to watch.
# :label_selector (string) - a selector to restrict the list of returned objects by labels.
# :field_selector (string) - a selector to restrict the list of returned objects by fields.
# :resource_version (string) - shows changes that occur after passed version of a resource.
# :allow_watch_bookmarks (bool) - flag to indicate whether to use bookmark or not.
def watch(resource_name, options = {})
begin
if !File.exist?(@@CaFile)
raise "#{@@CaFile} doesnt exist"
end
http_options = {
use_ssl: true,
open_timeout: 60,
read_timeout: 240, # https://github.com/kubernetes-client/java/issues/1370 https://github.com/kubernetes-client/java/issues/1578
ca_file: @@CaFile,
verify_mode: OpenSSL::SSL::VERIFY_PEER,
}
http_headers = {
Authorization: "Bearer " + getTokenStr,
}
ns = ""
if !options[:namespace].to_s.empty?
ns = "namespaces/#{namespace}/"
end
path = "watch/#{ns}#{resource_name}"
path += "/#{options[:name]}" if options[:name]
api_endpoint = "https://#{ENV["KUBERNETES_SERVICE_HOST"]}:#{ENV["KUBERNETES_PORT_443_TCP_PORT"]}/api/" + @@ApiVersion + "/" + "#{path}"
uri = URI.parse(api_endpoint)
params = {}
WATCH_ARGUMENTS.each { |k, v| params[k] = options[v] if options[v] }
uri.query = URI.encode_www_form(params) if params.any?
watcher = WatchStream.new(
uri,
http_options,
http_headers,
@Log
)
return watcher unless block_given?
begin
watcher.each(&block)
ensure
watcher.finish if watcher
end
rescue => errorStr
@Log.warn "KubernetesApiClient::watch:Failed with an error: #{errorStr}"
end
end
def getOptimizedItem(resource, resourceItem, isWindowsItem = false)
case resource
when "pods"
return getPodOptimizedItem(resourceItem, isWindowsItem)
when "pods-perf"
return getPodPerfOptimizedItem(resourceItem)
when "nodes"
return getNodeOptimizedItem(resourceItem)
when "services"
return getServiceOptimizedItem(resourceItem)
when "deployments"
return getDeploymentOptimizedItem(resourceItem)
when "horizontalpodautoscalers"
return getHpaOptimizedItem(resourceItem)
else
return resourceItem
end
end
def getServiceOptimizedItem(resourceItem)
item = {}
begin
item["metadata"] = {}
if !resourceItem["metadata"].nil?
item["metadata"]["name"] = resourceItem["metadata"]["name"]
item["metadata"]["namespace"] = resourceItem["metadata"]["namespace"]
end
item["spec"] = {}
if !resourceItem["spec"].nil?
item["spec"]["selector"] = []
if !resourceItem["spec"]["selector"].nil?
item["spec"]["selector"] = resourceItem["spec"]["selector"]
end
item["spec"]["clusterIP"] = ""
if !resourceItem["spec"]["clusterIP"].nil?
item["spec"]["clusterIP"] = resourceItem["spec"]["clusterIP"]
end
item["spec"]["type"] = ""
if !resourceItem["spec"]["type"].nil?
item["spec"]["type"] = resourceItem["spec"]["type"]
end
end
rescue => errorStr
@Log.warn "KubernetesApiClient::getServiceOptimizedItem:Failed with an error : #{errorStr}"
end
return item
end
def isWindowsNodeItem(nodeResourceItem)
isWindowsNodeItem = false
begin
nodeStatus = nodeResourceItem["status"]
if !nodeStatus.nil? && !nodeStatus["nodeInfo"].nil? && !nodeStatus["nodeInfo"]["operatingSystem"].nil?