/
mod_k8s.c
1665 lines (1491 loc) · 57.4 KB
/
mod_k8s.c
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
/* This software is distributed under the following license:
* http://sflow.net/license.html
*/
#if defined(__cplusplus)
extern "C" {
#endif
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <net/if.h>
#include <linux/types.h>
#include <sys/prctl.h>
#include <sched.h>
#include <openssl/sha.h>
#include <uuid/uuid.h>
#include <fnmatch.h>
#include "hsflowd.h"
#include "cpu_utils.h"
#include "math.h"
// limit the number of chars we will read from each line
// (there can be more than this - my_readline will chop for us)
#define MAX_PROC_LINE_CHARS 320
#include "cJSON.h"
typedef struct _HSPK8sContainerStats {
uint32_t state; // SFLVirDomainState
uint64_t memoryLimit;
uint32_t cpu_count;
double cpu_count_dbl;
uint64_t cpu_total;
uint64_t mem_usage;
SFLHost_nio_counters net;
SFLHost_vrt_dsk_counters dsk;
} HSPK8sContainerStats;
typedef struct _HSPK8sContainer {
char *id;
char *name;
pid_t pid;
bool isSandbox;
HSPK8sContainerStats stats;
} HSPK8sContainer;
typedef struct _HSPVMState_POD {
HSPVMState vm; // superclass: must come first
char *hostname;
uint32_t /*pid_t*/ nspid; // selected from containers
uint32_t state; // SFLVirDomainState - from containers
bool gpu_dev_tried:1;
bool gpu_dev:1;
bool gpu_env_tried:1;
bool gpu_env:1;
time_t last_heard;
time_t last_vnic;
time_t last_cgroup;
char *cgroup_devices;
UTHash *containers;
int cgroup_id;
} HSPVMState_POD;
#define HSP_K8S_READER "/usr/sbin/hsflowd_containerd"
#define HSP_K8S_DATAPREFIX "data>"
#define HSP_K8S_MAX_FNAME_LEN 255
#define HSP_K8S_MAX_LINELEN 512
#define HSP_K8S_SHORTID_LEN 12
#define HSP_K8S_WAIT_NOSOCKET 10
#define HSP_K8S_WAIT_EVENTDROP 5
#define HSP_K8S_WAIT_STARTUP 2
#define HSP_K8S_WAIT_RECHECK 120
#define HSP_K8S_WAIT_STATS 3
#define HSP_K8S_REQ_TIMEOUT 10
#define HSP_NVIDIA_VIS_DEV_ENV "NVIDIA_VISIBLE_DEVICES"
#define HSP_MAJOR_NVIDIA 195
#define MY_MAX_HOSTNAME_CHARS 255 // override sFlow standard of SFL_MAX_HOSTNAME_CHARS (64)
typedef struct _HSPVNICPodEntry {
char *c_hostname;
uint32_t dsIndex;
} HSPVNICPodEntry;
typedef struct _HSPVNIC {
SFLAddress ipAddr;
uint32_t nspid;
uint32_t ifIndex;
UTHash *podEntries;
uint32_t dsIndex;
#define HSPVNIC_DSINDEX_NONUNIQUE 0xFFFFFFFF
} HSPVNIC;
#define HSP_VNIC_REFRESH_TIMEOUT 300
#define HSP_CGROUP_REFRESH_TIMEOUT 600
typedef struct _HSP_mod_K8S {
EVBus *pollBus;
UTHash *podsByHostname;
UTHash *podsByCgroupId;
UTHash *containersByID;
SFLCounters_sample_element vnodeElem;
struct stat myNS;
UTHash *vnicByIP;
uint32_t configRevisionNo;
pid_t readerPid;
int idleSweepCountdown;
char *cgroup_path;
char *cgroup_devices_path;
uint32_t ds_byMAC;
uint32_t ds_byInnerMAC;
uint32_t ds_byIP;
uint32_t ds_byInnerIP;
uint32_t pod_byAddr;
uint32_t pod_byCgroup;
} HSP_mod_K8S;
/*_________________---------------------------__________________
_________________ utils to help debug __________________
-----------------___________________________------------------
*/
char *podStr(HSPVMState_POD *pod, char *buf, int bufLen) {
u_char uuidstr[100];
printUUID((u_char *)pod->vm.uuid, uuidstr, 100);
snprintf(buf, bufLen, "hostname: %s uuid: %s containers: %u",
pod->hostname,
uuidstr,
UTHashN(pod->containers));
return buf;
}
void podHTPrint(UTHash *ht, char *prefix) {
char buf[1024];
HSPVMState_POD *pod;
UTHASH_WALK(ht, pod)
myLog(LOG_INFO, "%s: %s", prefix, podStr(pod, buf, 1024));
}
/*________________---------------------------__________________
________________ readCgroupPaths __________________
----------------___________________________------------------
*/
static void readCgroupPaths(EVMod *mod) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
char mpath[HSP_K8S_MAX_FNAME_LEN+1];
snprintf(mpath, HSP_K8S_MAX_FNAME_LEN, PROCFS_STR "mounts");
FILE *procFile = fopen(mpath, "r");
if(procFile) {
// limit the number of chars we will read from each line
// (there can be more than this - my_readline will chop for us)
char line[MAX_PROC_LINE_CHARS];
int truncated;
while(my_readline(procFile, line, MAX_PROC_LINE_CHARS, &truncated) != EOF) {
char buf[MAX_PROC_LINE_CHARS];
char *p = line;
char *fsType = parseNextTok(&p, " ", NO, '\0', NO, buf, MAX_PROC_LINE_CHARS);
if(my_strequal(fsType, "cgroup2")) {
char *fsPath = parseNextTok(&p, " ", NO, '\0', NO, buf, MAX_PROC_LINE_CHARS);
if(fsPath) {
EVDebug(mod, 1, "found cgroup2 path = %s", fsPath);
mdata->cgroup_path = my_strdup(fsPath);
}
}
// devices controller is still cgroups v1
if(my_strequal(fsType, "cgroup")) {
char *fsPath = parseNextTok(&p, " ", NO, '\0', NO, buf, MAX_PROC_LINE_CHARS);
if(fsPath
&& fnmatch("*/devices", fsPath, 0) == 0) {
EVDebug(mod, 1, "found cgroup devices controller path = %s", fsPath);
mdata->cgroup_devices_path = my_strdup(fsPath);
}
}
}
fclose(procFile);
}
}
/*________________---------------------------__________________
________________ setVNIC_ds __________________
----------------___________________________------------------
*/
static uint32_t setVNIC_ds(EVMod *mod, HSPVNIC *vnic) {
// set the dsIndex to the podEntry->dsIndex if there is only one,
// otherwise indicate that it is not a unique mapping.
vnic->dsIndex = HSPVNIC_DSINDEX_NONUNIQUE; // not-unique
if(UTHashN(vnic->podEntries) == 1) {
HSPVNICPodEntry *podEntry;
UTHASH_WALK(vnic->podEntries, podEntry) {
vnic->dsIndex = podEntry->dsIndex;
}
}
return vnic->dsIndex;
}
/*________________---------------------------__________________
________________ podLinkCB __________________
----------------___________________________------------------
expecting lines of the form:
VNIC: <ifindex> <device> <mac> <ipv4> <ipv6> <nspid>
*/
static void mapIPToPod(EVMod *mod, HSPVMState_POD *pod, SFLAddress *ipAddr, uint32_t ifIndex, uint32_t nspid) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
HSPVNIC search = { .ipAddr = *ipAddr };
HSPVNIC *vnic = UTHashGet(mdata->vnicByIP, &search);
HSPVNICPodEntry *podEntry = NULL;
if(vnic) {
// found VNIC - check for this pod
HSPVNICPodEntry search = { .c_hostname = pod->hostname };
podEntry = UTHashGet(vnic->podEntries, &search);
}
else {
// add new VNIC
vnic = (HSPVNIC *)my_calloc(sizeof(HSPVNIC));
vnic->ipAddr = *ipAddr;
vnic->ifIndex = ifIndex;
vnic->nspid = nspid;
vnic->podEntries = UTHASH_NEW(HSPVNICPodEntry, c_hostname, UTHASH_SKEY);
UTHashAdd(mdata->vnicByIP, vnic);
}
if(!podEntry) {
// add new podEntry
podEntry = (HSPVNICPodEntry *)my_calloc(sizeof(HSPVNICPodEntry));
podEntry->dsIndex = pod->vm.dsIndex;
podEntry->c_hostname = my_strdup(pod->hostname);
UTHashAdd(vnic->podEntries, podEntry);
}
setVNIC_ds(mod, vnic);
if(EVDebug(mod, 1, NULL)) {
char ipstr[64];
EVDebug(mod, 1, "mapIPToPod: ip %s linked by VNIC(nspid=%u ifIndex=%u ds=%u) to pod %s",
SFLAddress_print(ipAddr, ipstr, 64),
vnic->nspid,
vnic->ifIndex,
vnic->dsIndex,
podEntry->c_hostname);
}
}
static int podLinkCB(EVMod *mod, HSPVMState_POD *pod, char *line) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
HSP *sp = (HSP *)EVROOTDATA(mod);
EVDebug(mod, 1, "podLinkCB: line=<%s>", line);
char deviceName[HSP_K8S_MAX_LINELEN];
char macStr[HSP_K8S_MAX_LINELEN];
char ipStr[HSP_K8S_MAX_LINELEN];
char ip6Str[HSP_K8S_MAX_LINELEN];
uint32_t ifIndex;
uint32_t nspid;
if(sscanf(line, "VNIC: %u %s %s %s %s %u", &ifIndex, deviceName, macStr, ipStr, ip6Str, &nspid) == 6) {
u_char mac[6];
if(hexToBinary((u_char *)macStr, mac, 6) == 6) {
SFLAdaptor *adaptor = adaptorListGet(pod->vm.interfaces, deviceName);
if(adaptor == NULL) {
adaptor = nioAdaptorNew(deviceName, mac, ifIndex);
adaptorListAdd(pod->vm.interfaces, adaptor);
// add to "all namespaces" collections too - but only the ones where
// the id is really global. For example, many containers can have
// an "eth0" adaptor so we can't add it to sp->adaptorsByName.
// And because the containers are likely to be ephemeral, don't
// replace the global adaptor if it's already there.
if(UTHashGet(sp->adaptorsByMac, adaptor) == NULL)
if(UTHashAdd(sp->adaptorsByMac, adaptor) != NULL)
myLog(LOG_ERR, "Warning: pod adaptor overwriting adaptorsByMac");
if(UTHashGet(sp->adaptorsByIndex, adaptor) == NULL)
if(UTHashAdd(sp->adaptorsByIndex, adaptor) != NULL)
myLog(LOG_ERR, "Warning: pod adaptor overwriting adaptorsByIndex");
// mark it as a vm/pod device
// and record the dsIndex there for easy mapping later
// provided it is unique. Otherwise set it to all-ones
// to indicate that it should not be used to map to pod.
HSPAdaptorNIO *nio = ADAPTOR_NIO(adaptor);
nio->vm_or_container = YES;
nio->container_nspid = nspid;
if(nio->container_dsIndex != pod->vm.dsIndex) {
if(nio->container_dsIndex == 0)
nio->container_dsIndex = pod->vm.dsIndex;
else {
myLog(LOG_ERR, "Warning: NIC already claimed by container with dsIndex==nio->container_dsIndex");
// mark it as not a unique mapping
nio->container_dsIndex = HSPVNIC_DSINDEX_NONUNIQUE;
}
}
// did we get an ip address too?
SFLAddress ipAddr = { };
SFLAddress ip6Addr = { };
bool gotV4 = parseNumericAddress(ipStr, NULL, &ipAddr, PF_INET);
gotV4 = gotV4 && !SFLAddress_isZero(&ipAddr);
bool gotV6 = parseNumericAddress(ip6Str, NULL, &ip6Addr, PF_INET6);
gotV6 = gotV6 && !SFLAddress_isZero(&ip6Addr);
if(mdata->vnicByIP
&& (gotV4
|| gotV6)) {
// Can use this to associate traffic with this pod
// if this address appears in sampled packet header as
// outer or inner IP
if(gotV6) {
mapIPToPod(mod, pod, &ip6Addr, ifIndex, nspid);
}
if(gotV4) {
ADAPTOR_NIO(adaptor)->ipAddr = ipAddr;
mapIPToPod(mod, pod, &ipAddr, ifIndex, nspid);
}
}
}
}
}
return YES;
}
/*________________---------------------------__________________
________________ readPodInterfaces __________________
----------------___________________________------------------
*/
#include <linux/version.h>
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,0,0) || (__GLIBC__ <= 2 && __GLIBC_MINOR__ < 14))
#ifndef CLONE_NEWNET
#define CLONE_NEWNET 0x40000000 /* New network namespace (lo, device, names sockets, etc) */
#endif
#define MY_SETNS(fd, nstype) syscall(__NR_setns, fd, nstype)
#else
#define MY_SETNS(fd, nstype) setns(fd, nstype)
#endif
int readPodInterfaces(EVMod *mod, HSPVMState_POD *pod) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
uint32_t nspid = pod->nspid;
EVDebug(mod, 2, "readPodInterfaces: pid=%u", nspid);
if(nspid == 0)
return 0;
// do the dirty work after a fork, so we can just exit afterwards,
// same as they do in "ip netns exec"
int pfd[2];
if(pipe(pfd) == -1) {
myLog(LOG_ERR, "pipe() failed : %s", strerror(errno));
exit(EXIT_FAILURE);
}
pid_t cpid;
if((cpid = fork()) == -1) {
myLog(LOG_ERR, "fork() failed : %s", strerror(errno));
exit(EXIT_FAILURE);
}
if(cpid == 0) {
// in child
close(pfd[0]); // close read-end
dup2(pfd[1], 1); // stdout -> write-end
dup2(pfd[1], 2); // stderr -> write-end
close(pfd[1]);
// open /proc/<nspid>/ns/net
char topath[HSP_K8S_MAX_FNAME_LEN+1];
snprintf(topath, HSP_K8S_MAX_FNAME_LEN, PROCFS_STR "/%u/ns/net", nspid);
int nsfd = open(topath, O_RDONLY | O_CLOEXEC);
if(nsfd < 0) {
fprintf(stderr, "cannot open %s : %s", topath, strerror(errno));
exit(EXIT_FAILURE);
}
struct stat statBuf;
if(fstat(nsfd, &statBuf) == 0) {
EVDebug(mod, 2, "pod namespace dev.inode == %u.%u", statBuf.st_dev, statBuf.st_ino);
if(statBuf.st_dev == mdata->myNS.st_dev
&& statBuf.st_ino == mdata->myNS.st_ino) {
EVDebug(mod, 1, "skip my own namespace");
exit(0);
}
}
/* set network namespace
CLONE_NEWNET means nsfd must refer to a network namespace
*/
if(MY_SETNS(nsfd, CLONE_NEWNET) < 0) {
fprintf(stderr, "seting network namespace failed: %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* From "man 2 unshare": This flag has the same effect as the clone(2)
CLONE_NEWNS flag. Unshare the mount namespace, so that the calling
process has a private copy of its namespace which is not shared with
any other process. Specifying this flag automatically implies CLONE_FS
as well. Use of CLONE_NEWNS requires the CAP_SYS_ADMIN capability. */
if(unshare(CLONE_NEWNS) < 0) {
fprintf(stderr, "seting network namespace failed: %s", strerror(errno));
exit(EXIT_FAILURE);
}
int fd = socket(PF_INET, SOCK_DGRAM, 0);
if(fd < 0) {
fprintf(stderr, "error opening socket: %d (%s)\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
// first build lookup from device name to IPv6 address, since we can't get that
// using SIOCGIFADDR below.
// Note: getIfAddrs() is another option but it doesn't provide the locally visible
// MAC address. In fact the MAC is the main reason we have to switch namespaces here,
// otherwise we could just read from /proc/<nspid>/net/dev and /proc/<nspid>/net/if_inet6.
typedef struct {
char *ifName;
SFLAddress ip6;
} HSPIfNameToV6;
UTHash *v6Addrs = UTHASH_NEW(HSPIfNameToV6, ifName, UTHASH_SKEY);
FILE *procV6 = fopen(PROCFS_STR "/net/if_inet6", "r");
if(procV6) {
char line[MAX_PROC_LINE_CHARS];
int lineNo = 0;
int truncated;
while(my_readline(procV6, line, MAX_PROC_LINE_CHARS, &truncated) != EOF) {
// expect lines of the form "<address> <netlink_no> <prefix_len(HEX)> <scope(HEX)> <flags(HEX)> <deviceName>
// (with a header line on the first row)
char devName[MAX_PROC_LINE_CHARS];
u_char addr[MAX_PROC_LINE_CHARS];
u_int devNo, maskBits, scope, flags;
++lineNo;
if(sscanf(line, "%s %x %x %x %x %s",
addr,
&devNo,
&maskBits,
&scope,
&flags,
devName) == 6) {
uint32_t devLen = my_strnlen(devName, MAX_PROC_LINE_CHARS-1);
char *trimmed = trimWhitespace(devName, devLen);
if(trimmed) {
SFLAddress v6addr;
v6addr.type = SFLADDRESSTYPE_IP_V6;
if(hexToBinary(addr, v6addr.address.ip_v6.addr, 16) == 16) {
if(!SFLAddress_isLinkLocal(&v6addr)
&& !SFLAddress_isLoopback(&v6addr)) {
HSPIfNameToV6 *v6Entry = my_calloc(sizeof(HSPIfNameToV6));
v6Entry->ifName = my_strdup(trimmed);
v6Entry->ip6 = v6addr;
UTHashAdd(v6Addrs, v6Entry);
}
}
}
}
}
fclose(procV6);
}
FILE *procFile = fopen(PROCFS_STR "/net/dev", "r");
if(procFile) {
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
char line[MAX_PROC_LINE_CHARS];
int lineNo = 0;
int truncated;
while(my_readline(procFile, line, MAX_PROC_LINE_CHARS, &truncated) != EOF) {
if(lineNo++ < 2) continue; // skip headers
char buf[MAX_PROC_LINE_CHARS];
char *p = line;
char *devName = parseNextTok(&p, " \t:", NO, '\0', NO, buf, MAX_PROC_LINE_CHARS);
if(devName && my_strlen(devName) < IFNAMSIZ) {
strncpy(ifr.ifr_name, devName, sizeof(ifr.ifr_name)-1);
// Get the flags for this interface
if(ioctl(fd,SIOCGIFFLAGS, &ifr) < 0) {
fprintf(stderr, "pod device %s Get SIOCGIFFLAGS failed : %s",
devName,
strerror(errno));
}
else {
int up = (ifr.ifr_flags & IFF_UP) ? YES : NO;
int loopback = (ifr.ifr_flags & IFF_LOOPBACK) ? YES : NO;
if(up && !loopback) {
// try to get ifIndex next, because we only care about
// ifIndex and MAC when looking at pod interfaces
if(ioctl(fd,SIOCGIFINDEX, &ifr) < 0) {
// only complain about this if we are debugging
EVDebug(mod, 1, "pod device %s Get SIOCGIFINDEX failed : %s",
devName,
strerror(errno));
}
else {
int ifIndex = ifr.ifr_ifindex;
SFLAddress ipAddr = {};
SFLAddress ip6Addr = {};
// see if we can get an IP address
if(ioctl(fd,SIOCGIFADDR, &ifr) < 0) {
// only complain about this if we are debugging
EVDebug(mod, 1, "device %s Get SIOCGIFADDR failed : %s",
devName,
strerror(errno));
}
else {
if (ifr.ifr_addr.sa_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&ifr.ifr_addr;
// IP addr is now s->sin_addr
ipAddr.type = SFLADDRESSTYPE_IP_V4;
ipAddr.address.ip_v4.addr = s->sin_addr.s_addr;
}
}
// possibly add a v6 addr
HSPIfNameToV6 search = { .ifName = devName };
HSPIfNameToV6 *v6Entry = UTHashGet(v6Addrs, &search);
if(v6Entry)
ip6Addr = v6Entry->ip6;
// Get the MAC Address for this interface
if(ioctl(fd,SIOCGIFHWADDR, &ifr) < 0) {
EVDebug(mod, 1, "device %s Get SIOCGIFHWADDR failed : %s",
devName,
strerror(errno));
}
else {
u_char macStr[13];
printHex((u_char *)&ifr.ifr_hwaddr.sa_data, 6, macStr, 12, NO);
char ipStr[64];
SFLAddress_print(&ipAddr, ipStr, 64);
char ip6Str[64]; // (from a second-hand store...)
SFLAddress_print(&ip6Addr, ip6Str, 64);
// send this info back up the pipe to my my parent
printf("VNIC: %u %s %s %s %s %u\n", ifIndex, devName, macStr, ipStr, ip6Str, nspid);
}
}
}
}
}
}
}
// don't even bother to close file-descriptors, just bail
exit(0);
}
else {
// in parent
close(pfd[1]); // close write-end
// read from read-end
FILE *ovs;
if((ovs = fdopen(pfd[0], "r")) == NULL) {
myLog(LOG_ERR, "readPodInterfaces: fdopen() failed : %s", strerror(errno));
return 0;
}
char line[MAX_PROC_LINE_CHARS];
int truncated;
while(my_readline(ovs, line, MAX_PROC_LINE_CHARS, &truncated) != EOF)
podLinkCB(mod, pod, line);
fclose(ovs);
wait(NULL); // block here until child is done
}
return pod->vm.interfaces->num_adaptors;
}
/*________________-----------------------__________________
________________ getCounters_POD __________________
----------------_______________________------------------
*/
static void getCounters_POD(EVMod *mod, HSPVMState_POD *pod)
{
HSP *sp = (HSP *)EVROOTDATA(mod);
SFL_COUNTERS_SAMPLE_TYPE cs = { 0 };
HSPVMState *vm = (HSPVMState *)&pod->vm;
if(sp->sFlowSettings == NULL) {
// do nothing if we haven't settled on the config yet
return;
}
// accumulate CPU, mem, diskI/O counters from containers
EVDebug(mod, 2, "getCounters_POD(): pod %s has %u containers",
pod->hostname,
UTHashN(pod->containers));
HSPK8sContainerStats stats = { 0 };
HSPK8sContainer *container;
UTHASH_WALK(pod->containers, container) {
if(container->stats.state == SFL_VIR_DOMAIN_RUNNING) {
stats.state = SFL_VIR_DOMAIN_RUNNING;
}
stats.cpu_count += container->stats.cpu_count;
EVDebug(mod, 2, "getCounters_POD(): container %s has cpu_count %u (total now = %u)",
container->name,
container->stats.cpu_count,
stats.cpu_count);
stats.cpu_total += container->stats.cpu_total;
stats.mem_usage += container->stats.mem_usage;
stats.memoryLimit += container->stats.memoryLimit;
stats.dsk.capacity += container->stats.dsk.capacity;
stats.dsk.allocation += container->stats.dsk.allocation;
stats.dsk.available += container->stats.dsk.available;
stats.dsk.rd_req += container->stats.dsk.rd_req;
stats.dsk.rd_bytes += container->stats.dsk.rd_bytes;
stats.dsk.wr_req += container->stats.dsk.wr_req;
stats.dsk.wr_bytes += container->stats.dsk.wr_bytes;
stats.dsk.errs += container->stats.dsk.errs;
// TODO: accumulate net counters too? (If they appear)
}
// TODO: how to detect that a POD has stopped? No containers running?
pod->state = stats.state;
// host ID
SFLCounters_sample_element hidElem = { 0 };
hidElem.tag = SFLCOUNTERS_HOST_HID;
char *hname = pod->hostname;
hidElem.counterBlock.host_hid.hostname.str = hname;
hidElem.counterBlock.host_hid.hostname.len = my_strlen(hname);
memcpy(hidElem.counterBlock.host_hid.uuid, vm->uuid, 16);
// for pods we can show the same OS attributes as the parent
hidElem.counterBlock.host_hid.machine_type = sp->machine_type;
hidElem.counterBlock.host_hid.os_name = SFLOS_linux;
hidElem.counterBlock.host_hid.os_release.str = sp->os_release;
hidElem.counterBlock.host_hid.os_release.len = my_strlen(sp->os_release);
SFLADD_ELEMENT(&cs, &hidElem);
// host parent
SFLCounters_sample_element parElem = { 0 };
parElem.tag = SFLCOUNTERS_HOST_PAR;
parElem.counterBlock.host_par.dsClass = SFL_DSCLASS_PHYSICAL_ENTITY;
parElem.counterBlock.host_par.dsIndex = HSP_DEFAULT_PHYSICAL_DSINDEX;
SFLADD_ELEMENT(&cs, &parElem);
// VM Net I/O
SFLCounters_sample_element nioElem = { 0 };
nioElem.tag = SFLCOUNTERS_HOST_VRT_NIO;
memcpy(&nioElem.counterBlock.host_vrt_nio, &stats.net, sizeof(stats.net));
SFLADD_ELEMENT(&cs, &nioElem);
// VM cpu counters [ref xenstat.c]
SFLCounters_sample_element cpuElem = { 0 };
cpuElem.tag = SFLCOUNTERS_HOST_VRT_CPU;
cpuElem.counterBlock.host_vrt_cpu.state = pod->state;
cpuElem.counterBlock.host_vrt_cpu.nrVirtCpu = stats.cpu_count ?: (uint32_t)round(stats.cpu_count_dbl);
cpuElem.counterBlock.host_vrt_cpu.cpuTime = (uint32_t)(stats.cpu_total / 1000000); // convert to mS
SFLADD_ELEMENT(&cs, &cpuElem);
SFLCounters_sample_element memElem = { 0 };
memElem.tag = SFLCOUNTERS_HOST_VRT_MEM;
memElem.counterBlock.host_vrt_mem.memory = stats.mem_usage;
memElem.counterBlock.host_vrt_mem.maxMemory = stats.memoryLimit;
SFLADD_ELEMENT(&cs, &memElem);
// VM disk I/O counters
SFLCounters_sample_element dskElem = { 0 };
dskElem.tag = SFLCOUNTERS_HOST_VRT_DSK;
// TODO: fill in capacity, allocation, available fields
memcpy(&dskElem.counterBlock.host_vrt_dsk, &stats.dsk, sizeof(stats.dsk));
SFLADD_ELEMENT(&cs, &dskElem);
// include my slice of the adaptor list (the ones from my private namespace)
SFLCounters_sample_element adaptorsElem = { 0 };
adaptorsElem.tag = SFLCOUNTERS_ADAPTORS;
adaptorsElem.counterBlock.adaptors = vm->interfaces;
SFLADD_ELEMENT(&cs, &adaptorsElem);
// circulate the cs to be annotated by other modules before it is sent out.
HSPPendingCSample ps = { .poller = vm->poller, .cs = &cs };
EVEvent *evt_vm_cs = EVGetEvent(sp->pollBus, HSPEVENT_VM_COUNTER_SAMPLE);
// TODO: can we specify pollBus only? Receiving this on another bus would
// be a disaster as we would not copy the whole structure here.
EVEventTx(sp->rootModule, evt_vm_cs, &ps, sizeof(ps));
if(ps.suppress) {
sp->telemetry[HSP_TELEMETRY_COUNTER_SAMPLES_SUPPRESSED]++;
}
else {
SEMLOCK_DO(sp->sync_agent) {
sfl_poller_writeCountersSample(vm->poller, &cs);
sp->counterSampleQueued = YES;
sp->telemetry[HSP_TELEMETRY_COUNTER_SAMPLES]++;
}
}
}
static void agentCB_getCounters_POD_request(void *magic, SFLPoller *poller, SFL_COUNTERS_SAMPLE_TYPE *cs)
{
}
/*_________________---------------------------__________________
_________________ name_uuid __________________
-----------------___________________________------------------
*/
static void uuidgen_type5(HSP *sp, u_char *uuid, char *name) {
int len = my_strlen(name);
// also hash in agent IP address in case sp->uuid is missing or not unique
int addrLen = sp->agentIP.type == SFLADDRESSTYPE_IP_V6 ? 16 : 4;
char *buf = (char *)UTHeapQNew(len + addrLen);
memcpy(buf, name, len);
memcpy(buf + len, &sp->agentIP.address, addrLen);
uuid_generate_sha1(uuid, (u_char *)sp->uuid, buf, len + addrLen);
}
/*_________________---------------------------__________________
_________________ add and remove VM __________________
-----------------___________________________------------------
*/
static void removePodVNICLookup(EVMod *mod, HSPVMState_POD *pod) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
SFLAdaptor *ad;
ADAPTORLIST_WALK(pod->vm.interfaces, ad) {
HSPAdaptorNIO *nio = ADAPTOR_NIO(ad);
if(nio->ipAddr.type != SFLADDRESSTYPE_UNDEFINED) {
HSPVNIC vnSearch = { };
vnSearch.ipAddr = nio->ipAddr;
HSPVNIC *vnic = UTHashGet(mdata->vnicByIP, &vnSearch);
if(vnic) {
HSPVNICPodEntry peSearch = { .c_hostname = pod->hostname };
HSPVNICPodEntry *podEntry = UTHashDelKey(vnic->podEntries, &peSearch);
if(podEntry) {
my_free(podEntry->c_hostname);
my_free(podEntry);
}
if(UTHashN(vnic->podEntries) == 0) {
// empty VNIC, remove
HSPVNIC *vnic = UTHashDelKey(mdata->vnicByIP, &vnSearch);
if(vnic) {
UTHashFree(vnic->podEntries);
my_free(vnic);
}
}
else {
// recalculate the VNIC dsIndex (maybe now it is unique?)
setVNIC_ds(mod, vnic);
}
}
}
}
}
static void removeAndFreeContainer(EVMod *mod, HSPK8sContainer *container) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
EVDebug(mod, 1, "removeAndFreeContainer: removing container %s=%s", container->name, container->id);
// remove from hash table
if(UTHashDel(mdata->containersByID, container) == NULL) {
myLog(LOG_ERR, "UTHashDel (containerssByID) failed: container %s=%s", container->name, container->id);
}
if(container->id)
my_free(container->id);
if(container->name)
my_free(container->name);
my_free(container);
}
static void removeAndFreeVM_POD(EVMod *mod, HSPVMState_POD *pod) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
EVDebug(mod, 1, "removeAndFreeVM: removing pod with dsIndex=%u", pod->vm.dsIndex);
// remove any VNIC lookups by IP (this semaphore-protected hash table is point
// of contact between poll thread and packet thread).
// (the interfaces will be removed completely in removeAndFreeVM() below)
if(mdata->vnicByIP)
removePodVNICLookup(mod, pod);
HSPK8sContainer *container;
UTHASH_WALK(pod->containers, container)
removeAndFreeContainer(mod, container);
UTHashFree(pod->containers);
// remove from hash tables
if(UTHashDel(mdata->podsByHostname, pod) == NULL) {
myLog(LOG_ERR, "UTHashDel (podsByHostname) failed: pod %s", pod->hostname);
if(debug(1))
podHTPrint(mdata->podsByHostname, "podsByHostname");
}
if(pod->cgroup_id
&& UTHashDel(mdata->podsByCgroupId, pod) == NULL) {
myLog(LOG_ERR, "UTHashDel (podsByCgroupId) failed: pod %s", pod->hostname);
if(debug(1))
podHTPrint(mdata->podsByCgroupId, "podsByCgroupId");
}
if(pod->hostname)
my_free(pod->hostname);
removeAndFreeVM(mod, &pod->vm);
}
static HSPVMState_POD *getPod(EVMod *mod, char *hostname, char *cgpath, bool create) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
HSP *sp = (HSP *)EVROOTDATA(mod);
HSPVMState_POD search = { .hostname = hostname };
HSPVMState_POD *pod = UTHashGet(mdata->podsByHostname, &search);
if(pod == NULL
&& create) {
char uuid[16];
// turn hostname string into a type 5 UUID
uuidgen_type5(sp, (u_char *)uuid, hostname);
// and use that to look up the datasource
pod = (HSPVMState_POD *)getVM(mod, uuid, YES, sizeof(HSPVMState_POD), VMTYPE_POD, agentCB_getCounters_POD_request);
assert(pod != NULL);
if(pod) {
pod->state = SFL_VIR_DOMAIN_RUNNING;
pod->hostname = my_strdup(hostname);
// add to collections
UTHashAdd(mdata->podsByHostname, pod);
// collection of child containers
pod->containers = UTHASH_NEW(HSPK8sContainer, id, UTHASH_SKEY);
if(cgpath
&& mdata->cgroup_path) {
// get inode that TCP DIAG will report as 'cgroup_id'
char path[HSP_K8S_MAX_FNAME_LEN];
snprintf(path, HSP_K8S_MAX_FNAME_LEN, "%s/%s", mdata->cgroup_path, cgpath);
struct stat statBuf = {};
if(stat(path, &statBuf) == 0) {
pod->cgroup_id = statBuf.st_ino;
EVDebug(mod, 1, "Learned cgroup_id = %u for pod %s",
pod->cgroup_id,
pod->hostname);
// remember this for packet sample lookup
UTHashAdd(mdata->podsByCgroupId, pod);
}
}
}
}
return pod;
}
static bool podDone(EVMod *mod, HSPVMState_POD *pod) {
return (pod
&& pod->state != SFL_VIR_DOMAIN_RUNNING);
}
/*_________________---------------------------__________________
_________________ add and remove container __________________
-----------------___________________________------------------
*/
static HSPVMState_POD *podAddContainer(EVMod *mod, HSPVMState_POD *pod, HSPK8sContainer *container) {
return UTHashGetOrAdd(pod->containers, container);
}
static HSPK8sContainer *getContainer(EVMod *mod, char *id, bool create) {
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
if(id == NULL)
return NULL;
HSPK8sContainer cont = { .id = id };
HSPK8sContainer *container = UTHashGet(mdata->containersByID, &cont);
if(container == NULL
&& create) {
container = (HSPK8sContainer *)UTHeapQNew(sizeof(HSPK8sContainer));
container->id = my_strdup(id);
// add to collection
UTHashAdd(mdata->containersByID, container);
}
return container;
}
/*_________________---------------------------__________________
_________________ updatePodAdaptors __________________
-----------------___________________________------------------
*/
static void updatePodAdaptors(EVMod *mod, HSPVMState_POD *pod) {
HSP *sp = (HSP *)EVROOTDATA(mod);
HSPVMState *vm = &pod->vm;
if(vm) {
// reset the information that we are about to refresh
adaptorListMarkAll(vm->interfaces);
// then refresh it
readPodInterfaces(mod, pod);
// and clean up
deleteMarkedAdaptors_adaptorList(sp, vm->interfaces);
adaptorListFreeMarked(vm->interfaces);
}
}
/*_________________-----------------------------__________________
_________________ updatePodCgroupPaths __________________
-----------------_____________________________------------------
*/
static void updatePodCgroupPaths(EVMod *mod, HSPVMState_POD *pod) {
if(pod->nspid == 0)
return;
HSPVMState *vm = &pod->vm;
if(vm) {
// open /proc/<pid>/cgroup
char cgpath[HSP_K8S_MAX_FNAME_LEN+1];
snprintf(cgpath, HSP_K8S_MAX_FNAME_LEN, PROCFS_STR "/%u/cgroup", pod->nspid);
FILE *procFile = fopen(cgpath, "r");
if(procFile) {
char line[MAX_PROC_LINE_CHARS];
int truncated;
while(my_readline(procFile, line, MAX_PROC_LINE_CHARS, &truncated) != EOF) {
if(!truncated) {
// expect lines like 3:devices:<long_path>
int entryNo;
char type[MAX_PROC_LINE_CHARS];
char path[MAX_PROC_LINE_CHARS];
if(sscanf(line, "%d:%[^:]:%[^:]", &entryNo, type, path) == 3) {
if(my_strequal(type, "devices")) {
if(!my_strequal(pod->cgroup_devices, path)) {
if(pod->cgroup_devices)
my_free(pod->cgroup_devices);
pod->cgroup_devices = my_strdup(path);
EVDebug(mod, 1, "pod(%s)->cgroup_devices=%s", pod->hostname, pod->cgroup_devices);
}
}
}
}
}
fclose(procFile);
}
}
}
/*_________________---------------------------__________________
_________________ host counter sample __________________
-----------------___________________________------------------
*/
static void evt_host_cs(EVMod *mod, EVEvent *evt, void *data, size_t dataLen) {
SFL_COUNTERS_SAMPLE_TYPE *cs = *(SFL_COUNTERS_SAMPLE_TYPE **)data;
HSP_mod_K8S *mdata = (HSP_mod_K8S *)mod->data;
HSP *sp = (HSP *)EVROOTDATA(mod);
if(!hasVNodeRole(mod, HSP_VNODE_PRIORITY_POD))
return;
memset(&mdata->vnodeElem, 0, sizeof(mdata->vnodeElem));
mdata->vnodeElem.tag = SFLCOUNTERS_HOST_VRT_NODE;
mdata->vnodeElem.counterBlock.host_vrt_node.mhz = sp->cpu_mhz;
mdata->vnodeElem.counterBlock.host_vrt_node.cpus = sp->cpu_cores;
mdata->vnodeElem.counterBlock.host_vrt_node.num_domains = UTHashN(mdata->podsByHostname);
mdata->vnodeElem.counterBlock.host_vrt_node.memory = sp->mem_total;
mdata->vnodeElem.counterBlock.host_vrt_node.memory_free = sp->mem_free;
SFLADD_ELEMENT(cs, &mdata->vnodeElem);
}
/*_________________---------------------------__________________
_________________ container names __________________
-----------------___________________________------------------
*/
static void setContainerName(EVMod *mod, HSPK8sContainer *container, const char *name) {
char *str = (char *)name;
if(str && str[0] == '/') str++; // consume leading '/'
if(my_strequal(str, container->name) == NO) {
if(container->name)
my_free(container->name);
container->name = my_strdup(str);
}
}
/*_________________---------------------------__________________
_________________ GPUs __________________
-----------------___________________________------------------
*/
static void clearPodGPUs(EVMod *mod, HSPVMState_POD *pod) {
// clear out the list - we are single threaded on the
// poll bus so there is no need for sync
UTArray *arr = pod->vm.gpus;
HSPGpuID *entry;
UTARRAY_WALK(arr, entry)
my_free(entry);
UTArrayReset(arr);
}
static void readPodGPUsFromEnv(EVMod *mod, HSPVMState_POD *pod, cJSON *jenv) {
// look through env vars for evidence of GPUs assigned to this pod
EVDebug(mod, 1, "readPodGPUsFromEnv(%s)", pod->hostname);
pod->gpu_env_tried = YES;
int entries = cJSON_GetArraySize(jenv);
UTArray *arr = pod->vm.gpus;
for(int ii = 0; ii < entries; ii++) {
cJSON *varval = cJSON_GetArrayItem(jenv, ii);
if(varval) {
char *vvstr = varval->valuestring;
int vlen = strlen(HSP_NVIDIA_VIS_DEV_ENV);
if(vvstr
&& my_strnequal(vvstr, HSP_NVIDIA_VIS_DEV_ENV, vlen)
&& vvstr[vlen] == '=') {
EVDebug(mod, 2, "parsing GPU env: %s", vvstr);
char *gpu_uuids = vvstr + vlen + 1;
clearPodGPUs(mod, pod);