/
hsflowd.c
2285 lines (2020 loc) · 81.3 KB
/
hsflowd.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 "hsflowd.h"
#include "cpu_utils.h"
#include "cJSON.h"
#if (__GLIBC__ >= 2 && __GLIBC_MINOR__ >= 13)
#include "malloc.h" // for malloc_info()
#endif
// globals - easier for signal handler
HSP HSPSamplingProbe;
int exitStatus = EXIT_SUCCESS;
FILE *f_crash = NULL;
static void openCollectorSockets(HSP *sp, HSPSFlowSettings *settings);
static bool installSFlowSettings(HSP *sp, HSPSFlowSettings *settings);
static bool updatePollingInterval(HSP *sp);
static void openLogFile(HSP *sp);
/*_________________---------------------------__________________
_________________ agent callbacks __________________
-----------------___________________________------------------
*/
static void *agentCB_alloc(void *magic, SFLAgent *agent, size_t bytes)
{
return my_calloc(bytes);
}
static int agentCB_free(void *magic, SFLAgent *agent, void *obj)
{
my_free(obj);
return 0;
}
static void agentCB_error(void *magic, SFLAgent *agent, char *msg)
{
myLog(LOG_ERR, "sflow agent error: %s", msg);
}
static void agentCB_sendPkt(void *magic, SFLAgent *agent, SFLReceiver *receiver, u_char *pkt, uint32_t pktLen)
{
HSP *sp = (HSP *)magic;
// note that we are relying on any new settings being installed atomically from the DNS-SD
// thread (it's just a pointer move, so it should be atomic). Otherwise we would want to
// grab sp->sync whenever we call sfl_sampler_writeFlowSample(), because that can
// bring us here where we read the list of collectors.
if(sp->suppress_sendPkt_agentAddress
|| sp->suppress_sendPkt_waitConfig)
return;
if(sp->sFlowSettings == NULL)
return;
sp->telemetry[HSP_TELEMETRY_DATAGRAMS]++;
if(debug(2)) {
myDebug(2, "mS=%u agentCB_sendPkt() sending datagram: %u",
EVBusRunningTime_mS(EVCurrentBus()),
sp->telemetry[HSP_TELEMETRY_DATAGRAMS]);
}
for(HSPCollector *coll = sp->sFlowSettings->collectors; coll; coll=coll->nxt) {
if(coll->socklen && coll->socket > 0) {
int result = sendto(coll->socket,
pkt,
pktLen,
0,
(struct sockaddr *)&coll->sendSocketAddr,
coll->socklen);
if(result == -1 && errno != EINTR) {
EVLog(60, LOG_ERR, "socket sendto error: %s", strerror(errno));
// We have the agent semaphore lock here, so it's safe
// to close and clear the socket, then set a countdown
// to try opening it again.
close(coll->socket);
coll->socket = 0;
sp->reopenCollectorSocketCountdown = HSP_RETRY_COLLECTOR_SOCKET;
}
else if(result == 0) {
EVLog(60, LOG_ERR, "socket sendto returned 0: %s", strerror(errno));
}
}
}
}
/*_________________---------------------------__________________
_________________ adaptor utils __________________
-----------------___________________________------------------
*/
SFLAdaptor *nioAdaptorNew(char *dev, u_char *macBytes, uint32_t ifIndex) {
SFLAdaptor *adaptor = adaptorNew(dev, macBytes, sizeof(HSPAdaptorNIO), ifIndex);
HSPAdaptorNIO *nio = ADAPTOR_NIO(adaptor);
// set defaults
nio->vlan = HSP_VLAN_ALL;
nio->ethtool_GDRVINFO = YES;
nio->ethtool_GLINKSETTINGS = YES;
nio->ethtool_GSET = YES;
nio->ethtool_GSTATS = YES;
nio->procNetDev = YES;
return adaptor;
}
void adaptorAddOrReplace(UTHash *ht, SFLAdaptor *ad, char *htname) {
SFLAdaptor *replaced = UTHashAdd(ht, ad);
if(replaced && replaced != ad) {
char buf1[256], buf2[256];
myDebug(1, "adaptorAddOrReplace: %s: replacing adaptor [%s] with [%s]",
htname,
adaptorStr(replaced, buf1, 256),
adaptorStr(ad, buf2, 256));
// This can happen quite commonly when two interfaces share the
// same MAC addresses and the adaptorsByMAC hash table detects
// the clash, so don't free the one that was replaced. It's
// probably still referenced in adaptorsByIndex and adaptorsByName.
}
}
SFLAdaptor *adaptorByName(HSP *sp, char *dev) {
SFLAdaptor ad = { .deviceName = dev };
return UTHashGet(sp->adaptorsByName, &ad);
}
SFLAdaptor *adaptorByMac(HSP *sp, SFLMacAddress *mac) {
SFLAdaptor ad = { .macs[0] = (*mac) };
return UTHashGet(sp->adaptorsByMac, &ad);
}
SFLAdaptor *adaptorByIndex(HSP *sp, uint32_t ifIndex) {
SFLAdaptor ad = { .ifIndex = ifIndex };
return UTHashGet(sp->adaptorsByIndex, &ad);
}
SFLAdaptor *adaptorByPeerIndex(HSP *sp, uint32_t ifIndex) {
SFLAdaptor ad = { .peer_ifIndex = ifIndex };
return UTHashGet(sp->adaptorsByPeerIndex, &ad);
}
SFLAdaptor *adaptorByIP(HSP *sp, SFLAddress *ip) {
SFLAdaptor *adaptor;
UTHASH_WALK(sp->adaptorsByName, adaptor) {
HSPAdaptorNIO *adaptorNIO = ADAPTOR_NIO(adaptor);
if(SFLAddress_equal(ip, &adaptorNIO->ipAddr))
return adaptor;
}
return NULL;
}
SFLAdaptor *adaptorByAlias(HSP *sp, char *alias) {
SFLAdaptor *adaptor;
UTHASH_WALK(sp->adaptorsByName, adaptor) {
HSPAdaptorNIO *adaptorNIO = ADAPTOR_NIO(adaptor);
if(my_strequal(alias, adaptorNIO->deviceAlias))
return adaptor;
}
return NULL;
}
static void deleteAdaptorFromHT(UTHash *ht, SFLAdaptor *ad, char *htname) {
char buf[256];
if(UTHashDel(ht, ad) != ad) {
myDebug(1, "WARNING: adaptor not deleted from %s : %s", htname, adaptorStr(ad, buf, 256));
if(debug(1))
adaptorHTPrint(ht, htname);
}
}
void deleteAdaptor(HSP *sp, SFLAdaptor *ad, int freeFlag) {
if(sp->allowDeleteAdaptor == NO)
return;
deleteAdaptorFromHT(sp->adaptorsByName, ad, "byName");
deleteAdaptorFromHT(sp->adaptorsByIndex, ad, "byIndex");
deleteAdaptorFromHT(sp->adaptorsByMac, ad, "byMac");
if(ad->peer_ifIndex)
deleteAdaptorFromHT(sp->adaptorsByPeerIndex, ad, "byPeerIndex");
if(freeFlag) {
HSPAdaptorNIO *nio = ADAPTOR_NIO(ad);
if(nio->sampler)
myDebug(1, "deleteAdaptor: adaptor %s has sFlow sampler", ad->deviceName);
if(nio->poller)
myDebug(1, "deleteAdaptor: adaptor %s has sFlow poller", ad->deviceName);
if(nio->deviceAlias)
myDebug(1, "deleteAdaptor: adaptor %s has deviceAlias", ad->deviceName);
adaptorFree(ad);
}
}
int deleteMarkedAdaptors(HSP *sp, UTHash *adaptorHT, int freeFlag) {
int found = 0;
SFLAdaptor *ad;
UTHASH_WALK(adaptorHT, ad) if(ad->marked) {
deleteAdaptor(sp, ad, freeFlag);
found++;
}
return found;
}
int deleteMarkedAdaptors_adaptorList(HSP *sp, SFLAdaptorList *adList) {
int found = 0;
SFLAdaptor *ad;
ADAPTORLIST_WALK(adList, ad) if(ad->marked) {
deleteAdaptor(sp, ad, NO);
found++;
}
return found;
}
char *adaptorStr(SFLAdaptor *ad, char *buf, int bufLen) {
u_char macstr[13];
macstr[0] = '\0';
if(ad->num_macs) printHex(ad->macs[0].mac, 6, macstr, 13, NO);
snprintf(buf, bufLen, "ifindex: %u peer: %u nmacs: %u mac0: %s name: %s",
ad->ifIndex,
ad->peer_ifIndex,
ad->num_macs,
macstr,
ad->deviceName);
return buf;
}
void adaptorHTPrint(UTHash *ht, char *prefix) {
char buf[256];
SFLAdaptor *ad;
UTHASH_WALK(ht, ad)
myLog(LOG_INFO, "%s: %s", prefix, adaptorStr(ad, buf, 256));
}
static SFLAdaptorList *host_adaptors(HSP *sp, SFLAdaptorList *myAdaptors, int capacity)
{
// build the list of adaptors that are up and have non-empty MACs,
// and are not veth connectors to peers inside containers,
// and have not been claimed as switchPorts or VM or Container ports,
// but stop if we hit the capacity
SFLAdaptor *adaptor;
UTHASH_WALK(sp->adaptorsByName, adaptor) {
if(adaptor->peer_ifIndex == 0) {
HSPAdaptorNIO *niostate = ADAPTOR_NIO(adaptor);
if(niostate->up
&& (niostate->switchPort == NO)
&& (niostate->vm_or_container == NO)
&& adaptor->num_macs
&& !isZeroMAC(&adaptor->macs[0])) {
if(myAdaptors->num_adaptors >= capacity) break;
myAdaptors->adaptors[myAdaptors->num_adaptors++] = adaptor;
}
}
}
return myAdaptors;
}
bool setAdaptorSpeed(HSP *sp, SFLAdaptor *adaptor, uint64_t speed, char *method)
{
bool changed = (speed != adaptor->ifSpeed);
adaptor->ifSpeed = speed;
HSPAdaptorNIO *nio = ADAPTOR_NIO(adaptor);
nio->changed_speed = changed;
myDebug(1, "setAdaptorSpeed(%s): %s ifSpeed == %"PRIu64" (changed=%s)",
method,
adaptor->deviceName,
speed,
changed ? "YES":"NO");
if(changed
&& sp->rootModule) {
EVEventTxAll(sp->rootModule, HSPEVENT_INTF_SPEED, &adaptor, sizeof(adaptor));
}
return changed;
}
bool setAdaptorAlias(HSP *sp, SFLAdaptor *adaptor, char *alias, char *method)
{
HSPAdaptorNIO *nio = ADAPTOR_NIO(adaptor);
bool changed = !my_strequal(nio->deviceAlias, alias);
myDebug(1, "setAdaptorAlias(%s): %s alias == %s (changed=%s)",
method,
nio->deviceAlias ?: "NULL",
alias ?: "NULL",
changed ? "YES":"NO");
if(changed)
setStr(&nio->deviceAlias, alias);
return changed;
}
bool setAdaptorSelectionPriority(HSP *sp, SFLAdaptor *adaptor, uint32_t priority, char *method)
{
HSPAdaptorNIO *nio = ADAPTOR_NIO(adaptor);
bool changed = nio->selectionPriority != priority;
myDebug(1, "setAdaptorSelectionPriority(%s): %s %u -> %u (changed=%s)",
method,
adaptor->deviceName,
nio->selectionPriority,
priority,
changed ? "YES":"NO");
nio->selectionPriority = priority;
return changed;
}
/*_________________---------------------------__________________
_________________ local IPs __________________
-----------------___________________________------------------
*/
static __thread int th_n_localIPs = 0;
HSPLocalIP *localIPNew(SFLAddress *ipAddr, char *dev) {
HSPLocalIP *lip = my_calloc(sizeof(HSPLocalIP));
lip->ipAddr = *ipAddr;
lip->dev = my_strdup(dev);
th_n_localIPs++;
return lip;
}
void localIPFree(HSPLocalIP *lip) {
my_free(lip->dev);
my_free(lip);
th_n_localIPs--;
}
int localIPInstances(void) {
return th_n_localIPs;
}
/*_________________---------------------------__________________
_________________ agentCB_getCounters __________________
-----------------___________________________------------------
*/
static void agentCB_getCounters(void *magic, SFLPoller *poller, SFL_COUNTERS_SAMPLE_TYPE *cs)
{
assert(poller->magic);
HSP *sp = (HSP *)poller->magic;
// host ID
SFLCounters_sample_element hidElem = { 0 };
hidElem.tag = SFLCOUNTERS_HOST_HID;
if(readHidCounters(sp,
&hidElem.counterBlock.host_hid,
sp->hostname,
SFL_MAX_HOSTNAME_CHARS,
sp->os_release,
SFL_MAX_OSRELEASE_CHARS)) {
SFLADD_ELEMENT(cs, &hidElem);
}
// host Net I/O
SFLCounters_sample_element nioElem = { 0 };
nioElem.tag = SFLCOUNTERS_HOST_NIO;
if(readNioCounters(sp, &nioElem.counterBlock.host_nio, NULL, NULL)) {
SFLADD_ELEMENT(cs, &nioElem);
}
// host cpu counters
SFLCounters_sample_element cpuElem = { 0 };
cpuElem.tag = SFLCOUNTERS_HOST_CPU;
if(readCpuCounters(&cpuElem.counterBlock.host_cpu)) {
// remember speed and nprocs for other purposes
sp->cpu_cores = cpuElem.counterBlock.host_cpu.cpu_num;
sp->cpu_mhz = cpuElem.counterBlock.host_cpu.cpu_speed;
SFLADD_ELEMENT(cs, &cpuElem);
}
// host memory counters
SFLCounters_sample_element memElem = { 0 };
memElem.tag = SFLCOUNTERS_HOST_MEM;
if(readMemoryCounters(&memElem.counterBlock.host_mem)) {
// remember mem_total and mem_free for other purposes
sp->mem_total = memElem.counterBlock.host_mem.mem_total;
sp->mem_free = memElem.counterBlock.host_mem.mem_free;
SFLADD_ELEMENT(cs, &memElem);
}
// host I/O counters
SFLCounters_sample_element dskElem = { 0 };
dskElem.tag = SFLCOUNTERS_HOST_DSK;
if(readDiskCounters(sp, &dskElem.counterBlock.host_dsk)) {
SFLADD_ELEMENT(cs, &dskElem);
}
// don't send L4 stats from switches. Save the space for other things.
// TODO: review this. Possibly generalize with a request-to-omit flag.
// host TCP/IP counters
SFLCounters_sample_element ipElem = { 0 }, icmpElem = { 0 }, tcpElem = { 0 }, udpElem = { 0 };
if(!sp->cumulus.cumulus
&& !sp->opx.opx
&& !sp->dent.dent) {
ipElem.tag = SFLCOUNTERS_HOST_IP;
icmpElem.tag = SFLCOUNTERS_HOST_ICMP;
tcpElem.tag = SFLCOUNTERS_HOST_TCP;
udpElem.tag = SFLCOUNTERS_HOST_UDP;
if(readTcpipCounters(sp,
&ipElem.counterBlock.host_ip,
&icmpElem.counterBlock.host_icmp,
&tcpElem.counterBlock.host_tcp,
&udpElem.counterBlock.host_udp)) {
SFLADD_ELEMENT(cs, &ipElem);
SFLADD_ELEMENT(cs, &icmpElem);
SFLADD_ELEMENT(cs, &tcpElem);
SFLADD_ELEMENT(cs, &udpElem);
}
}
SFLCounters_sample_element adaptorsElem = { 0 };
adaptorsElem.tag = SFLCOUNTERS_ADAPTORS;
// collect list of host adaptors that are up, and have non-zero MACs, and
// have not been claimed by xen, kvm or docker.
SFLAdaptorList myAdaptors;
SFLAdaptor *adaptors[HSP_MAX_PHYSICAL_ADAPTORS];
myAdaptors.adaptors = adaptors;
myAdaptors.capacity = HSP_MAX_PHYSICAL_ADAPTORS;
myAdaptors.num_adaptors = 0;
adaptorsElem.counterBlock.adaptors = host_adaptors(sp, &myAdaptors, HSP_MAX_PHYSICAL_ADAPTORS);
SFLADD_ELEMENT(cs, &adaptorsElem);
// send the cs out to be annotated by other modules such as docker, xen, vrt and NVML
EVEvent *evt_host_cs = EVGetEvent(sp->pollBus, HSPEVENT_HOST_COUNTER_SAMPLE);
// TODO: use HSPPendingSample, and remove the extra later of & indirection here
// because it is not necessary.
EVEventTx(sp->rootModule, evt_host_cs, &cs, sizeof(cs));
SEMLOCK_DO(sp->sync_agent) {
sfl_poller_writeCountersSample(poller, cs);
sp->counterSampleQueued = YES;
sp->telemetry[HSP_TELEMETRY_COUNTER_SAMPLES]++;
}
}
static void agentCB_getCounters_request(void *magic, SFLPoller *poller, SFL_COUNTERS_SAMPLE_TYPE *cs)
{
HSP *sp = (HSP *)poller->magic;
UTArrayAdd(sp->pollActions, poller);
UTArrayAdd(sp->pollActions, agentCB_getCounters);
// Note readPackets.c uses this mechanism too (for switch port
// pollers), but other mods use their own array.
}
/*_________________---------------------------__________________
_________________ persistent dsIndex __________________
-----------------___________________________------------------
*/
static uint32_t assignVM_dsIndex(HSP *sp, HSPVMState *state) {
// make sure we are never called from a different thread
assert(EVCurrentBus() == sp->pollBus);
uint32_t first = HSP_DEFAULT_LOGICAL_DSINDEX_START;
uint32_t last = HSP_DEFAULT_APP_DSINDEX_START - 1;
uint32_t range = last - first + 1;
if(UTHashN(sp->vmsByDsIndex) >= range) {
// table is full
state->dsIndex = 0;
return NO;
}
uint32_t hash = hashUUID(state->uuid);
uint32_t preferred = first + (hash % range);
state->dsIndex = preferred;
for(;;) {
HSPVMState *probe = UTHashGet(sp->vmsByDsIndex, state);
if(probe == NULL) {
// claim this one
UTHashAdd(sp->vmsByDsIndex, state);
break;
}
if(probe == state) {
// why did we assign again?
break;
}
// collision - keep searching
state->dsIndex++;
if(state->dsIndex > last)
state->dsIndex = first;
if(state->dsIndex == preferred) {
// full wrap - shouldn't happen if the table
// is not full, but detect it anyway just in
// case we change something later.
state->dsIndex = 0;
return NO;
}
}
return YES;
}
/*_________________---------------------------__________________
_________________ VM/Container state __________________
-----------------___________________________------------------
*/
HSPVMState *getVM(EVMod *mod, char *uuid, bool create, size_t objSize, EnumVMType vmType, getCountersFn_t getCountersFn) {
HSP *sp = (HSP *)EVROOTDATA(mod);
// make sure we are never called from a different thread
assert(EVCurrentBus() == sp->pollBus);
assert(objSize >= sizeof(HSPVMState));
HSPVMState search;
memcpy(search.uuid, uuid, 16);
HSPVMState *state = UTHashGet(sp->vmsByUUID, &search);
if(state == NULL
&& create) {
state = (HSPVMState *)my_calloc(objSize);
memcpy(state->uuid, uuid, 16);
UTHashAdd(sp->vmsByUUID, state);
if(assignVM_dsIndex(sp,state) == NO) {
my_free(state);
state = NULL;
}
else {
state->created = YES;
state->vmType = vmType;
state->volumes = strArrayNew();
state->disks = strArrayNew();
state->interfaces = adaptorListNew();
state->gpus = UTArrayNew(UTARRAY_DFLT);
sp->refreshAdaptorList = YES;
SFLDataSource_instance dsi;
// ds_class = <virtualEntity>, ds_index = offset + <assigned>, ds_instance = 0
SFL_DS_SET(dsi, SFL_DSCLASS_LOGICAL_ENTITY, state->dsIndex, 0);
SEMLOCK_DO(sp->sync_agent) {
state->poller = sfl_agent_addPoller(sp->agent, &dsi, mod, getCountersFn);
state->poller->userData = state;
sfl_poller_set_sFlowCpInterval(state->poller, sp->actualPollingInterval);
sfl_poller_set_sFlowCpReceiver(state->poller, HSP_SFLOW_RECEIVER_INDEX);
}
}
}
return state;
}
void removeAndFreeVM(EVMod *mod, HSPVMState *state) {
HSP *sp = (HSP *)EVROOTDATA(mod);
// make sure we are never called from a different thread
assert(EVCurrentBus() == sp->pollBus);
UTHashDel(sp->vmsByDsIndex, state);
UTHashDel(sp->vmsByUUID, state);
if(state->disks) strArrayFree(state->disks);
if(state->volumes) strArrayFree(state->volumes);
if(state->interfaces) {
adaptorListMarkAll(state->interfaces);
// delete any hash-table references to these adaptors
deleteMarkedAdaptors_adaptorList(sp, state->interfaces);
// then free them along with the adaptorList itself
adaptorListFree(state->interfaces);
}
if(state->poller) {
state->poller->userData = NULL;
SEMLOCK_DO(sp->sync_agent) {
sfl_agent_removePoller(sp->agent, &state->poller->dsi);
}
}
my_free(state);
sp->refreshAdaptorList = YES;
}
/*_________________---------------------------__________________
_________________ syncOutputFile __________________
-----------------___________________________------------------
*/
static void syncOutputFile(HSP *sp) {
// The current settings will usually be found in sp->sFlowSettings, but there
// is a case where those have not been determined yet and we start with the
// file settings:
HSPSFlowSettings *settings = sp->sFlowSettings ?: sp->sFlowSettings_file;
myDebug(1, "syncOutputFile");
rewind(sp->f_out);
fprintf(sp->f_out, "# WARNING: Do not edit this file. It is generated automatically by hsflowd.\n");
// revision appears both at the beginning and at the end
fprintf(sp->f_out, "rev_start=%u\n", sp->revisionNo);
// don't write out the settings if we are suppressing output at the moment
if(sp->sFlowSettings_str
&& sp->suppress_sendPkt_waitConfig == NO
&& sp->suppress_sendPkt_agentAddress == NO) {
fputs(sp->sFlowSettings_str, sp->f_out);
// If agentIP or agentDevice was overridden then we just wrote that out with the sFlowSettings_str,
// but otherwise add the election-chosen ones here, so others can know what selection was made:
if(!settings->agentIP.type) {
char ipbuf[51];
fprintf(sp->f_out, "agentIP=%s\n", SFLAddress_print(&sp->agentIP, ipbuf, 50));
}
if(!settings->agentDevice
&& sp->agentDevice)
fprintf(sp->f_out, "agent=%s\n", sp->agentDevice);
// jsonPort always comes from local config file, but include it here so that
// others know where to send their JSON application/rtmetric/rtflow messages
if(sp->json.port)
fprintf(sp->f_out, "jsonPort=%u\n", sp->json.port);
// Others may need to know our ds_index too
fprintf(sp->f_out, "ds_index=%u\n", HSP_DEFAULT_PHYSICAL_DSINDEX);
}
// repeat the revision number. The reader knows that if the revison number
// has not changed under his feet then he has a consistent config.
fprintf(sp->f_out, "rev_end=%u\n", sp->revisionNo);
fflush(sp->f_out);
// chop off anything that may be lingering from before
UTTruncateOpenFile(sp->f_out);
}
/*_________________---------------------------------__________________
_________________ refreshAdaptorsAndAgentAddress __________________
-----------------_________________________________------------------
*/
static void refreshAdaptorsAndAgentAddress(HSP *sp) {
bool suppress = NO;
uint32_t ad_added=0, ad_removed=0, ad_cameup=0, ad_wentdown=0, ad_changed=0;
if(readInterfaces(sp, YES, &ad_added, &ad_removed, &ad_cameup, &ad_wentdown, &ad_changed) == 0) {
myLog(LOG_ERR, "failed to re-read interfaces\n");
}
else {
myDebug(1, "interfaces added: %u removed: %u cameup: %u wentdown: %u changed: %u",
ad_added, ad_removed, ad_cameup, ad_wentdown, ad_changed);
}
bool agentAddressChanged=NO;
bool agentDeviceMismatch=NO;
if(selectAgentAddress(sp, &agentAddressChanged, &agentDeviceMismatch) == NO) {
myLog(LOG_ERR, "failed to re-select agent address - suppress output");
// make sure we don't send anything with an invalid agent address (such
// as one that was just removed under our feet). Hopefully a new address
// will be added and we can recover in due course.
suppress = YES;
}
if(agentDeviceMismatch
&& sp->agentDeviceStrict) {
myDebug(1, "agent device mismatch and agentDeviceStrict is set - suppress output");
// this can happen if the interface referred to has not come up yet, or if the config
// is using an alias name for it and the alias has not be learned yet (e.g. mod_sonic).
// If the agentDeviceStrict flag is set then we treat this as a showstopper.
suppress = YES;
}
if(suppress
&& sp->suppress_sendPkt_agentAddress == NO) {
// impose the restriction on sending with a bad agent-address right away
myDebug(1, "imposing suppress_sendPkt_agentAddress");
sp->suppress_sendPkt_agentAddress = YES;
}
myDebug(1, "agentAddressChanged=%s", agentAddressChanged ? "YES" : "NO");
if(agentAddressChanged) {
SEMLOCK_DO(sp->sync_agent) {
sfl_agent_set_address(sp->agent, &sp->agentIP);
}
// this incs the revision No so it causes the
// output file to be rewritten below too.
installSFlowSettings(sp, sp->sFlowSettings);
}
myDebug(1, "instances: adaptors=%d, localIP=%d",
adaptorInstances(),
localIPInstances());
if(ad_added || ad_removed || ad_cameup || ad_wentdown || ad_changed) {
// test for switch ports
configSwitchPorts(sp); // in readPackets.c
// announce (e.g. to adjust sampling rates if ifSpeeds changed)
EVEventTxAll(sp->rootModule, HSPEVENT_INTFS_CHANGED, NULL, 0);
}
if(suppress == NO
&& sp->suppress_sendPkt_agentAddress) {
myDebug(1, "lifting suppress_sendPkt_agentAddress");
// on the other hand, if we are lifting the restriction then defer it to here.
sp->suppress_sendPkt_agentAddress = NO;
}
}
/*_________________---------------------------__________________
_________________ tick __________________
-----------------___________________________------------------
*/
static void evt_poll_tick(EVMod *mod, EVEvent *evt, void *data, size_t dataLen) {
HSP *sp = (HSP *)EVROOTDATA(mod);
if(sp->suppress_sendPkt_waitConfig) {
myDebug(1, "hsflowd: evt_poll_tick() waitConfig");
return;
}
time_t clk = evt->bus->now.tv_sec;
// reset the pollActions
UTArrayReset(sp->pollActions);
// send a tick to the sFlow agent. This will be passed on
// to the samplers, pollers and receiver. If the poller is
// ready to poll counters it will pull it's callback, but
// we are using that just to populate the poll actions list.
// That way we can relinquish the sync semaphore quickly.
// It is up to the poller's getCounters Fn to grab it again
// if and when it is required. Same goes for the
// sync_receiver lock, which is needed when the final
// counter sample is submitted for XDR serialization.
SEMLOCK_DO(sp->sync_agent) {
// update agent 'now' (also updated by packet samples):
sfl_agent_set_now(sp->agent, clk, evt->bus->now.tv_nsec);
// only run the poller_tick()s here, not the full agent_tick()
// we'll call receiver_flush at the end of this tick/tock cycle,
// and skip the sampler_tick() altogether.
// sfl_agent_tick(sp->agent, clk);
for(SFLPoller *pl = sp->agent->pollers; pl; pl = pl->nxt)
sfl_poller_tick(pl, clk);
for(SFLNotifier *nf = sp->agent->notifiers; nf; nf = nf->nxt)
sfl_notifier_tick(nf, clk);
// If a collector socket failed, we will attempt to reopen it
// here after a suitable cooling off period. One scenario for
// this is if the interface VRF is changed under our feet. That
// results in the sentto() failing with "No Such Device".
// Reopening here while we have the agent semaphore means that
// another thread will not try to send something while the
// socket is half opened. For consistency we could choose to
// hold the same semaphore in the more common "installSFlowSettings"
// path, but there the collector sockets are deliberately opened
// before the settings "go live" so it is not necessary.
if(sp->reopenCollectorSocketCountdown) {
if(--sp->reopenCollectorSocketCountdown == 0) {
myDebug(1, "Reopening collector socket(s) after error");
openCollectorSockets(sp, sp->sFlowSettings);
}
}
}
// We can only get away with this scheme because the poller
// objects are only ever removed and free by this thread.
// So we don't need to worry about them being freed under
// our feet below.
// now we can execute them without holding on to the semaphore
for(uint32_t ii = 0; ii < UTArrayN(sp->pollActions); ii += 2) {
SFLPoller *poller = (SFLPoller *)UTArrayAt(sp->pollActions, ii);
getCountersFn_t cb = (getCountersFn_t)UTArrayAt(sp->pollActions, ii+1);
SFL_COUNTERS_SAMPLE_TYPE cs;
memset(&cs, 0, sizeof(cs));
(cb)((void *)sp, poller, &cs);
}
// possibly poll the nio counters to avoid 32-bit rollover
if(sp->nio_polling_secs &&
clk >= sp->next_nio_poll) {
updateNioCounters(sp, NULL);
sp->next_nio_poll = clk + sp->nio_polling_secs;
}
// check for interface changes (relatively frequently)
// and request a full refresh if we find anything
if(clk >= sp->next_checkAdaptorList) {
sp->next_checkAdaptorList = clk + sp->checkAdaptorListSecs;
if(detectInterfaceChange(sp))
sp->refreshAdaptorList = YES;
}
// refresh the interface list periodically or on request
if(sp->refreshAdaptorList
|| clk >= sp->next_refreshAdaptorList) {
sp->refreshAdaptorList = NO;
sp->next_refreshAdaptorList = clk + sp->refreshAdaptorListSecs;
refreshAdaptorsAndAgentAddress(sp);
}
// rewrite the output if the config has changed
if(sp->outputRevisionNo != sp->revisionNo) {
syncOutputFile(sp);
sp->outputRevisionNo = sp->revisionNo;
}
}
/*_________________---------------------------__________________
_________________ flushCounters __________________
-----------------___________________________------------------
Use this to ensure that any sFlow datagram with a counter-sample
is flushed immediately. While not required by the sFlow standard
this does help to ensure that counters arrive at the collector
promptly, rather than waiting for up to a second. This reduces
the time-dither effect and makes successive counter deltas more
stable. It is particularly helpful when the polling interval is
short.
*/
void flushCounters(EVMod *mod) {
HSP *sp = (HSP *)EVROOTDATA(mod);
if(sp->counterSampleQueued) {
SEMLOCK_DO(sp->sync_agent) {
if(sp->counterSampleQueued) {
sfl_receiver_flush(sp->agent->receivers);
sp->counterSampleQueued = NO;
}
}
}
}
/*_________________---------------------------__________________
_________________ tock __________________
-----------------___________________________------------------
*/
static void evt_poll_tock(EVMod *mod, EVEvent *evt, void *data, size_t dataLen) {
HSP *sp = (HSP *)EVROOTDATA(mod);
// we registered for this event after the other modules were loaded, so
// unless they delay their registration for some reason we can assume
// that this is the last tock() action. (Could add another event to the
// cycle in evbus.c if we really need to be sure). Delaying the flush to
// here makes it more likely that counters will be flushed out promptly
// when they are freshly read.
SEMLOCK_DO(sp->sync_agent) {
// note - this used to happen inside sfl_agent_tick(), but we
// disaggregated that call so the pollers get their ticks first
// and the receiver flush happens at the end.
sfl_receiver_flush(sp->agent->receivers);
sp->counterSampleQueued = NO;
}
}
/*_________________---------------------------__________________
_________________ tock - all buses __________________
-----------------___________________________------------------
this fn called on tock by all buses (all threads) so be careful!
*/
static void evt_all_tock(EVMod *mod, EVEvent *evt, void *data, size_t dataLen) {
#ifdef UTHEAP
// check for heap cleanup
UTHeapGC();
#endif
// TODO: this would be a good place to test the memory footprint and
// bail out if it looks like we are leaking memory(?)
}
/*_________________---------------------------__________________
_________________ initAgent __________________
-----------------___________________________------------------
*/
static void initAgent(HSP *sp)
{
myDebug(1,"creating sfl agent");
// Used to open collector sockets here, but now that each
// collector object has his own socket we delay that until
// the point where the settings are about to go into effect
// (installSFlowSettings()).
SEMLOCK_DO(sp->sync_agent) {
struct timespec ts;
EVClockMono(&ts);
time_t mono_now = ts.tv_sec;
sp->agent = (SFLAgent *)my_calloc(sizeof(SFLAgent));
sfl_agent_init(sp->agent,
&sp->agentIP,
sp->subAgentId,
mono_now,
mono_now,
sp,
agentCB_alloc,
agentCB_free,
agentCB_error,
agentCB_sendPkt);
// just one receiver - we are serious about making this lightweight for now
SFLReceiver *receiver = sfl_agent_addReceiver(sp->agent);
// max datagram size might have been tweaked in the config file
if(sp->sFlowSettings_file->datagramBytes) {
sfl_receiver_set_sFlowRcvrMaximumDatagramSize(receiver, sp->sFlowSettings_file->datagramBytes);
}
// claim the receiver slot
sfl_receiver_set_sFlowRcvrOwner(receiver, "Virtual Switch sFlow Probe");
// set the timeout to infinity
sfl_receiver_set_sFlowRcvrTimeout(receiver, 0xFFFFFFFF);
}
}
/*_________________---------------------------__________________
_________________ setDefaults __________________
-----------------___________________________------------------
*/
static void setDefaults(HSP *sp)
{
sp->configFile = HSP_DEFAULT_CONFIGFILE;
sp->outputFile = HSP_DEFAULT_OUTPUTFILE;
sp->pidFile = HSP_DEFAULT_PIDFILE;
sp->crashFile = NULL;
sp->dropPriv = YES;
sp->refreshAdaptorListSecs = HSP_REFRESH_ADAPTORS;
sp->checkAdaptorListSecs = HSP_CHECK_ADAPTORS;
sp->refreshVMListSecs = HSP_REFRESH_VMS;
sp->forgetVMSecs = HSP_FORGET_VMS;
sp->modulesPath = STRINGIFY_DEF(HSP_MOD_DIR);
sp->logBytes = HSP_DEFAULT_LOGBYTES;
}
/*_________________---------------------------__________________
_________________ instructions __________________
-----------------___________________________------------------
*/
static void instructions(char *command)
{
fprintf(stderr,"Usage: %s [-dvP] [-p PIDFile] [-u UUID] [-m machine_id] [-f CONFIGFile] [-l MODULESDir] [-D LOGFile] [-L LOGBytes]\n", command);
fprintf(stderr,"\n\
-d: do not daemonize, and log to stdout/LOGFile (repeat for more debug details)\n\
-D LOGFile: debug logging goes to this file\n\
-L LOGBytes: max bytes in LOGFile (default is " HSP_DEFAULT_LOGBYTES ")\n\
-v: print version number and exit\n\
-P: do not drop privileges (run as root)\n\
-p PIDFile: specify PID file (default is " HSP_DEFAULT_PIDFILE ")\n\
-u UUID: specify UUID as unique ID for this host\n\
-f CONFIGFile: specify config file (default is " HSP_DEFAULT_CONFIGFILE ")\n\
-l MODULESDir: specify modules directory (default is " STRINGIFY_DEF(HSP_MOD_DIR) ")\n \
-c CRASHFile: specify file to write crash info to (default is stderr)\n");
fprintf(stderr, "=============== More Information ============================================\n");
fprintf(stderr, "| sFlow standard - http://www.sflow.org |\n");
fprintf(stderr, "| sFlowTrend (FREE) - http://www.inmon.com/products/sFlowTrend.php |\n");
fprintf(stderr, "=============================================================================\n");
exit(EXIT_FAILURE);
}
/*_________________---------------------------__________________
_________________ processCommandLine __________________
-----------------___________________________------------------
*/
static void processCommandLine(HSP *sp, int argc, char *argv[])
{
int in;
while ((in = getopt(argc, argv, "dvPp:f:l:o:u:m:?hc:D:L:")) != -1) {
switch(in) {
case 'v':
printf("%s version %s\n", argv[0], STRINGIFY_DEF(HSP_VERSION));
exit(EXIT_SUCCESS);
break;
case 'd':
// first 'd' just turns off daemonize, second increments debug
if(!getDaemon())
setDebug(getDebug() + 1);
setDaemon(NO);
break;
case 'P': sp->dropPriv = NO; break;
case 'p': sp->pidFile = optarg; break;
case 'f': sp->configFile = optarg; break;
case 'l': sp->modulesPath = my_strlen(optarg) ? optarg : NULL; break;
case 'o': sp->outputFile = optarg; break;
case 'c': sp->crashFile = optarg; break;
case 'D': sp->logFile = optarg; break;
case 'L': sp->logBytes = optarg; break;
case 'u':
if(parseUUID(optarg, sp->uuid) == NO) {
fprintf(stderr, "bad UUID format: %s\n", optarg);
instructions(*argv);
}
break;
case 'm':
if(parseUUID(optarg, sp->machine_id) == NO) {
fprintf(stderr, "bad UUID (machine-id) format: %s\n", optarg);
instructions(*argv);
}
break;
case '?':
case 'h':
default: instructions(*argv);
}
}
}
/*_________________---------------------------__________________
_________________ log_backtrace __________________
-----------------___________________________------------------
*/
void log_backtrace(int sig, siginfo_t *info, FILE *out) {
#ifdef HAVE_BACKTRACE
#define HSP_NUM_BACKTRACE_PTRS 50
static void *backtracePtrs[HSP_NUM_BACKTRACE_PTRS];
// ask for the backtrace pointers
size_t siz = backtrace(backtracePtrs, HSP_NUM_BACKTRACE_PTRS);
FILE *outFile = out ?: stderr;
// do this first in case everything else is compromised
backtrace_symbols_fd(backtracePtrs, siz, fileno(outFile));