]> arthur.barton.de Git - netdata.git/blob - src/registry.c
registry completed, including impersonate
[netdata.git] / src / registry.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4
5 #include <uuid/uuid.h>
6 #include <inttypes.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <ctype.h>
10 #include <unistd.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <errno.h>
14 #include <fcntl.h>
15
16 #include "log.h"
17 #include "common.h"
18 #include "dictionary.h"
19 #include "appconfig.h"
20
21 #include "web_client.h"
22 #include "rrd.h"
23 #include "rrd2json.h"
24 #include "registry.h"
25
26
27 // ----------------------------------------------------------------------------
28 // TODO
29 //
30 // 1. the default tracking cookie expires in 1 year, but the persons are not
31 //    removed from the db - this means the database only grows - ideally the
32 //    database should be cleaned in registry_save() for both on-disk and
33 //    on-memory entries.
34 //
35 //    Cleanup:
36 //    i. Find all the PERSONs that have expired cookie
37 //    ii. For each of their PERSON_URLs:
38 //     - decrement the linked MACHINE links
39 //     - if the linked MACHINE has no other links, remove the linked MACHINE too
40 //     - remove the PERSON_URL
41 //
42 // 2. add protection to prevent abusing the registry by flooding it with
43 //    requests to fill the memory and crash it.
44 //
45 //    Possible protections:
46 //    - limit the number of URLs per person
47 //    - limit the number of URLs per machine
48 //    - limit the number of persons
49 //    - limit the number of machines
50 //    - [DONE] limit the size of URLs
51 //    - [DONE] limit the size of PERSON_URL names
52 //    - limit the number of requests that add data to the registry,
53 //      per client IP per hour
54
55
56
57 #define REGISTRY_URL_FLAGS_DEFAULT 0x00
58 #define REGISTRY_URL_FLAGS_EXPIRED 0x01
59
60 #define DICTIONARY_FLAGS DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE | DICTIONARY_FLAG_NAME_LINK_DONT_CLONE
61
62 // ----------------------------------------------------------------------------
63 // COMMON structures
64
65 struct registry {
66         int enabled;
67
68         char machine_guid[36 + 1];
69
70         // entries counters / statistics
71         unsigned long long persons_count;
72         unsigned long long machines_count;
73         unsigned long long usages_count;
74         unsigned long long urls_count;
75         unsigned long long persons_urls_count;
76         unsigned long long machines_urls_count;
77         unsigned long long log_count;
78
79         // memory counters / statistics
80         unsigned long long persons_memory;
81         unsigned long long machines_memory;
82         unsigned long long urls_memory;
83         unsigned long long persons_urls_memory;
84         unsigned long long machines_urls_memory;
85
86         // configuration
87         unsigned long long save_registry_every_entries;
88         char *registry_domain;
89         char *hostname;
90         char *registry_to_announce;
91         time_t persons_expiration; // seconds to expire idle persons
92
93         size_t max_url_length;
94         size_t max_name_length;
95
96         // file/path names
97         char *pathname;
98         char *db_filename;
99         char *log_filename;
100         char *machine_guid_filename;
101
102         // open files
103         FILE *log_fp;
104
105         // the database
106         DICTIONARY *persons;    // dictionary of PERSON *, with key the PERSON.guid
107         DICTIONARY *machines;   // dictionary of MACHINE *, with key the MACHINE.guid
108         DICTIONARY *urls;               // dictionary of URL *, with key the URL.url
109
110         // concurrency locking
111         // we keep different locks for different things
112         // so that many tasks can be completed in parallel
113         pthread_mutex_t persons_lock;
114         pthread_mutex_t machines_lock;
115         pthread_mutex_t urls_lock;
116         pthread_mutex_t person_urls_lock;
117         pthread_mutex_t machine_urls_lock;
118         pthread_mutex_t log_lock;
119 } registry;
120
121
122 // ----------------------------------------------------------------------------
123 // URL structures
124 // Save memory by de-duplicating URLs
125 // so instead of storing URLs all over the place
126 // we store them here and we keep pointers elsewhere
127
128 struct url {
129         uint32_t links; // the number of links to this URL - when none is left, we free it
130         uint16_t len;   // the length of the URL in bytes
131         char url[1];    // the URL - dynamically allocated to more size
132 };
133 typedef struct url URL;
134
135
136 // ----------------------------------------------------------------------------
137 // MACHINE structures
138
139 // For each MACHINE-URL pair we keep this
140 struct machine_url {
141         URL *url;                                       // de-duplicated URL
142 //      DICTIONARY *persons;            // dictionary of PERSON *
143
144         uint8_t flags;
145         uint32_t first_t;                       // the first time we saw this
146         uint32_t last_t;                        // the last time we saw this
147         uint32_t usages;                        // how many times this has been accessed
148 };
149 typedef struct machine_url MACHINE_URL;
150
151 // A machine
152 struct machine {
153         char guid[36 + 1];                      // the GUID
154
155         uint32_t links;                         // the number of PERSON_URLs linked to this machine
156
157         DICTIONARY *urls;                       // MACHINE_URL *
158
159         uint32_t first_t;                       // the first time we saw this
160         uint32_t last_t;                        // the last time we saw this
161         uint32_t usages;                        // how many times this has been accessed
162 };
163 typedef struct machine MACHINE;
164
165
166 // ----------------------------------------------------------------------------
167 // PERSON structures
168
169 // for each PERSON-URL pair we keep this
170 struct person_url {
171         URL *url;                                       // de-duplicated URL
172         MACHINE *machine;                       // link the MACHINE of this URL
173
174         uint8_t flags;
175         uint32_t first_t;                       // the first time we saw this
176         uint32_t last_t;                        // the last time we saw this
177         uint32_t usages;                        // how many times this has been accessed
178
179         char name[1];                           // the name of the URL, as known by the user
180                                                                 // dynamically allocated to fit properly
181 };
182 typedef struct person_url PERSON_URL;
183
184 // A person
185 struct person {
186         char guid[36 + 1];                      // the person GUID
187
188         DICTIONARY *urls;                       // dictionary of PERSON_URL *
189
190         uint32_t first_t;                       // the first time we saw this
191         uint32_t last_t;                        // the last time we saw this
192         uint32_t usages;                        // how many times this has been accessed
193 };
194 typedef struct person PERSON;
195
196
197 // ----------------------------------------------------------------------------
198 // REGISTRY concurrency locking
199
200 static inline void registry_persons_lock(void) {
201         pthread_mutex_lock(&registry.persons_lock);
202 }
203
204 static inline void registry_persons_unlock(void) {
205         pthread_mutex_unlock(&registry.persons_lock);
206 }
207
208 static inline void registry_machines_lock(void) {
209         pthread_mutex_lock(&registry.machines_lock);
210 }
211
212 static inline void registry_machines_unlock(void) {
213         pthread_mutex_unlock(&registry.machines_lock);
214 }
215
216 static inline void registry_urls_lock(void) {
217         pthread_mutex_lock(&registry.urls_lock);
218 }
219
220 static inline void registry_urls_unlock(void) {
221         pthread_mutex_unlock(&registry.urls_lock);
222 }
223
224 // ideally, we should not lock the whole registry for
225 // updating a person's urls.
226 // however, to save the memory required for keeping a
227 // mutex (40 bytes) per person, we do...
228 static inline void registry_person_urls_lock(PERSON *p) {
229         (void)p;
230         pthread_mutex_lock(&registry.person_urls_lock);
231 }
232
233 static inline void registry_person_urls_unlock(PERSON *p) {
234         (void)p;
235         pthread_mutex_unlock(&registry.person_urls_lock);
236 }
237
238 // ideally, we should not lock the whole registry for
239 // updating a machine's urls.
240 // however, to save the memory required for keeping a
241 // mutex (40 bytes) per machine, we do...
242 static inline void registry_machine_urls_lock(MACHINE *m) {
243         (void)m;
244         pthread_mutex_lock(&registry.machine_urls_lock);
245 }
246
247 static inline void registry_machine_urls_unlock(MACHINE *m) {
248         (void)m;
249         pthread_mutex_unlock(&registry.machine_urls_lock);
250 }
251
252 static inline void registry_log_lock(void) {
253         pthread_mutex_lock(&registry.log_lock);
254 }
255
256 static inline void registry_log_unlock(void) {
257         pthread_mutex_unlock(&registry.log_lock);
258 }
259
260
261 // ----------------------------------------------------------------------------
262 // common functions
263
264 // parse a GUID and re-generated to be always lower case
265 // this is used as a protection against the variations of GUIDs
266 static inline int registry_regenerate_guid(const char *guid, char *result) {
267         uuid_t uuid;
268         if(unlikely(uuid_parse(guid, uuid) == -1)) {
269                 info("Registry: GUID '%s' is not a valid GUID.", guid);
270                 return -1;
271         }
272         else {
273                 uuid_unparse_lower(uuid, result);
274
275 #ifdef NETDATA_INTERNAL_CHECKS
276                 if(strcmp(guid, result))
277                         info("Registry: source GUID '%s' and re-generated GUID '%s' differ!", guid, result);
278 #endif /* NETDATA_INTERNAL_CHECKS */
279         }
280
281         return 0;
282 }
283
284 // make sure the names of the machines / URLs do not contain any tabs
285 // (which are used as our separator in the database files)
286 // and are properly trimmed (before and after)
287 static inline char *registry_fix_machine_name(char *name, size_t *len) {
288         char *s = name?name:"";
289
290         // skip leading spaces
291         while(*s && isspace(*s)) s++;
292
293         // make sure all spaces are a SPACE
294         char *t = s;
295         while(*t) {
296                 if(unlikely(isspace(*t)))
297                         *t = ' ';
298
299                 t++;
300         }
301
302         // remove trailing spaces
303         while(--t >= s) {
304                 if(*t == ' ')
305                         *t = '\0';
306                 else
307                         break;
308         }
309         t++;
310
311         if(likely(len))
312                 *len = (t - s);
313
314         return s;
315 }
316
317 static inline char *registry_fix_url(char *url, size_t *len) {
318         return registry_fix_machine_name(url, len);
319 }
320
321
322 // ----------------------------------------------------------------------------
323 // forward definition of functions
324
325 extern PERSON *registry_request_access(char *person_guid, char *machine_guid, char *url, char *name, time_t when);
326 extern PERSON *registry_request_delete(char *person_guid, char *machine_guid, char *url, char *delete_url, time_t when);
327
328
329 // ----------------------------------------------------------------------------
330 // URL
331
332 static inline URL *registry_url_allocate_nolock(const char *url, size_t urllen) {
333         // protection from too big URLs
334         if(urllen > registry.max_url_length)
335                 urllen = registry.max_url_length;
336
337         debug(D_REGISTRY, "Registry: registry_url_allocate_nolock('%s'): allocating %zu bytes", url, sizeof(URL) + urllen);
338         URL *u = malloc(sizeof(URL) + urllen);
339         if(!u) fatal("Cannot allocate %zu bytes for URL '%s'", sizeof(URL) + urllen);
340
341         // a simple strcpy() should do the job
342         // but I prefer to be safe, since the caller specified urllen
343         strncpy(u->url, url, urllen);
344         u->url[urllen] = '\0';
345
346         u->len = urllen;
347         u->links = 0;
348
349         registry.urls_memory += sizeof(URL) + urllen;
350
351         debug(D_REGISTRY, "Registry: registry_url_allocate_nolock('%s'): indexing it", url);
352         dictionary_set(registry.urls, u->url, u, sizeof(URL));
353
354         return u;
355 }
356
357 static inline URL *registry_url_get(const char *url, size_t urllen) {
358         debug(D_REGISTRY, "Registry: registry_url_get('%s')", url);
359
360         registry_urls_lock();
361
362         URL *u = dictionary_get(registry.urls, url);
363         if(!u) {
364                 u = registry_url_allocate_nolock(url, urllen);
365                 registry.urls_count++;
366         }
367
368         registry_urls_unlock();
369
370         return u;
371 }
372
373 static inline void registry_url_link_nolock(URL *u) {
374         u->links++;
375         debug(D_REGISTRY, "Registry: registry_url_link_nolock('%s'): URL has now %u links", u->url, u->links);
376 }
377
378 static inline void registry_url_unlink_nolock(URL *u) {
379         u->links--;
380         if(!u->links) {
381                 debug(D_REGISTRY, "Registry: registry_url_unlink_nolock('%s'): No more links for this URL", u->url);
382                 dictionary_del(registry.urls, u->url);
383                 free(u);
384         }
385         else
386                 debug(D_REGISTRY, "Registry: registry_url_unlink_nolock('%s'): URL has %u links left", u->url, u->links);
387 }
388
389
390 // ----------------------------------------------------------------------------
391 // MACHINE
392
393 static inline MACHINE *registry_machine_find(const char *machine_guid) {
394         debug(D_REGISTRY, "Registry: registry_machine_find('%s')", machine_guid);
395         return dictionary_get(registry.machines, machine_guid);
396 }
397
398 static inline MACHINE_URL *registry_machine_url_allocate(MACHINE *m, URL *u, time_t when) {
399         debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s'): allocating %zu bytes", m->guid, u->url, sizeof(MACHINE_URL));
400
401         MACHINE_URL *mu = malloc(sizeof(MACHINE_URL));
402         if(!mu) fatal("registry_machine_link_to_url('%s', '%s'): cannot allocate %zu bytes.", m->guid, u->url, sizeof(MACHINE_URL));
403
404         // mu->persons = dictionary_create(DICTIONARY_FLAGS);
405         // dictionary_set(mu->persons, p->guid, p, sizeof(PERSON));
406
407         mu->first_t = mu->last_t = when;
408         mu->usages = 1;
409         mu->url = u;
410         mu->flags = REGISTRY_URL_FLAGS_DEFAULT;
411
412         registry.machines_urls_memory += sizeof(MACHINE_URL);
413
414         debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s'): indexing URL in machine", m->guid, u->url);
415         dictionary_set(m->urls, u->url, mu, sizeof(MACHINE_URL));
416         registry_url_link_nolock(u);
417
418         return mu;
419 }
420
421 static inline MACHINE *registry_machine_allocate(const char *machine_guid, time_t when) {
422         debug(D_REGISTRY, "Registry: registry_machine_allocate('%s'): creating new machine, sizeof(MACHINE)=%zu", machine_guid, sizeof(MACHINE));
423
424         MACHINE *m = malloc(sizeof(MACHINE));
425         if(!m) fatal("Registry: cannot allocate memory for new machine '%s'", machine_guid);
426
427         strncpy(m->guid, machine_guid, 36);
428         m->guid[36] = '\0';
429
430         debug(D_REGISTRY, "Registry: registry_machine_allocate('%s'): creating dictionary of urls", machine_guid);
431         m->urls = dictionary_create(DICTIONARY_FLAGS);
432
433         m->first_t = m->last_t = when;
434         m->usages = 0;
435
436         registry.machines_memory += sizeof(MACHINE);
437
438         registry.machines_count++;
439         dictionary_set(registry.machines, m->guid, m, sizeof(MACHINE));
440
441         return m;
442 }
443
444 // 1. validate machine GUID
445 // 2. if it is valid, find it or create it and return it
446 // 3. if it is not valid, return NULL
447 static inline MACHINE *registry_machine_get(const char *machine_guid, time_t when) {
448         MACHINE *m = NULL;
449
450         registry_machines_lock();
451
452         if(likely(machine_guid && *machine_guid)) {
453                 // validate it is a GUID
454                 char buf[36 + 1];
455                 if(unlikely(registry_regenerate_guid(machine_guid, buf) == -1))
456                         info("Registry: machine guid '%s' is not a valid guid. Ignoring it.", machine_guid);
457                 else {
458                         machine_guid = buf;
459                         m = registry_machine_find(machine_guid);
460                         if(!m) m = registry_machine_allocate(machine_guid, when);
461                 }
462         }
463
464         registry_machines_unlock();
465
466         return m;
467 }
468
469
470 // ----------------------------------------------------------------------------
471 // PERSON
472
473 static inline PERSON *registry_person_find(const char *person_guid) {
474         debug(D_REGISTRY, "Registry: registry_person_find('%s')", person_guid);
475         return dictionary_get(registry.persons, person_guid);
476 }
477
478 static inline PERSON_URL *registry_person_url_allocate(PERSON *p, MACHINE *m, URL *u, char *name, size_t namelen, time_t when) {
479         // protection from too big names
480         if(namelen > registry.max_name_length)
481                 namelen = registry.max_name_length;
482
483         debug(D_REGISTRY, "registry_person_url_allocate('%s', '%s', '%s'): allocating %zu bytes", p->guid, m->guid, u->url,
484                   sizeof(PERSON_URL) + namelen);
485
486         PERSON_URL *pu = malloc(sizeof(PERSON_URL) + namelen);
487         if(!pu) fatal("registry_person_url_allocate('%s', '%s', '%s'): cannot allocate %zu bytes.", p->guid, m->guid, u->url, sizeof(PERSON_URL) + namelen);
488
489         // a simple strcpy() should do the job
490         // but I prefer to be safe, since the caller specified urllen
491         strncpy(pu->name, name, namelen);
492         pu->name[namelen] = '\0';
493
494         pu->machine = m;
495         pu->first_t = pu->last_t = when;
496         pu->usages = 1;
497         pu->url = u;
498         pu->flags = REGISTRY_URL_FLAGS_DEFAULT;
499         m->links++;
500
501         registry.persons_urls_memory += sizeof(PERSON_URL) + namelen;
502
503         debug(D_REGISTRY, "registry_person_url_allocate('%s', '%s', '%s'): indexing URL in person", p->guid, m->guid, u->url);
504         dictionary_set(p->urls, u->url, pu, sizeof(PERSON_URL));
505         registry_url_link_nolock(u);
506
507         return pu;
508 }
509
510 static inline PERSON_URL *registry_person_url_reallocate(PERSON *p, MACHINE *m, URL *u, char *name, size_t namelen, time_t when, PERSON_URL *pu) {
511         // this function is needed to change the name of a PERSON_URL
512
513         debug(D_REGISTRY, "registry_person_url_reallocate('%s', '%s', '%s'): allocating %zu bytes", p->guid, m->guid, u->url,
514                   sizeof(PERSON_URL) + namelen);
515
516         PERSON_URL *tpu = registry_person_url_allocate(p, m, u, name, namelen, when);
517         tpu->first_t = pu->first_t;
518         tpu->last_t = pu->last_t;
519         tpu->usages = pu->usages;
520
521         // ok, these are a hack - since the registry_person_url_allocate() is
522         // adding these, we have to subtract them
523         tpu->machine->links--;
524         registry.persons_urls_memory -= sizeof(PERSON_URL) + strlen(pu->name);
525         registry_url_unlink_nolock(u);
526
527         free(pu);
528
529         return tpu;
530 }
531
532 static inline PERSON *registry_person_allocate(const char *person_guid, time_t when) {
533         PERSON *p = NULL;
534
535         debug(D_REGISTRY, "Registry: registry_person_allocate('%s'): allocating new person, sizeof(PERSON)=%zu", (person_guid)?person_guid:"", sizeof(PERSON));
536
537         p = malloc(sizeof(PERSON));
538         if(!p) fatal("Registry: cannot allocate memory for new person.");
539
540         if(!person_guid) {
541                 for (; ;) {
542                         uuid_t uuid;
543                         uuid_generate(uuid);
544                         uuid_unparse_lower(uuid, p->guid);
545
546                         debug(D_REGISTRY, "Registry: Checking if the generated person guid '%s' is unique", p->guid);
547                         if (!dictionary_get(registry.persons, p->guid)) {
548                                 debug(D_REGISTRY, "Registry: generated person guid '%s' is unique", p->guid);
549                                 break;
550                         }
551                         else
552                                 info("Registry: generated person guid '%s' found in the registry. Retrying...", p->guid);
553                 }
554         }
555         else {
556                 strncpy(p->guid, person_guid, 36);
557                 p->guid[36] = '\0';
558         }
559
560         debug(D_REGISTRY, "Registry: registry_person_allocate('%s'): creating dictionary of urls", p->guid);
561         p->urls = dictionary_create(DICTIONARY_FLAGS);
562
563         p->first_t = p->last_t = when;
564         p->usages = 0;
565
566         registry.persons_memory += sizeof(PERSON);
567
568         registry.persons_count++;
569         dictionary_set(registry.persons, p->guid, p, sizeof(PERSON));
570
571         return p;
572 }
573
574
575 // 1. validate person GUID
576 // 2. if it is valid, find it
577 // 3. if it is not valid, create a new one
578 // 4. return it
579 static inline PERSON *registry_person_get(const char *person_guid, time_t when) {
580         PERSON *p = NULL;
581
582         registry_persons_lock();
583
584         if(person_guid && *person_guid) {
585                 char buf[36 + 1];
586                 // validate it is a GUID
587                 if(unlikely(registry_regenerate_guid(person_guid, buf) == -1))
588                         info("Registry: person guid '%s' is not a valid guid. Ignoring it.", person_guid);
589                 else {
590                         person_guid = buf;
591                         p = registry_person_find(person_guid);
592                         if(!p) person_guid = NULL;
593                 }
594         }
595
596         if(!p) p = registry_person_allocate(NULL, when);
597
598         registry_persons_unlock();
599
600         return p;
601 }
602
603 // ----------------------------------------------------------------------------
604 // LINKING OF OBJECTS
605
606 static inline PERSON_URL *registry_person_link_to_url(PERSON *p, MACHINE *m, URL *u, char *name, size_t namelen, time_t when) {
607         debug(D_REGISTRY, "registry_person_link_to_url('%s', '%s', '%s'): searching for URL in person", p->guid, m->guid, u->url);
608
609         registry_person_urls_lock(p);
610
611         PERSON_URL *pu = dictionary_get(p->urls, u->url);
612         if(!pu) {
613                 debug(D_REGISTRY, "registry_person_link_to_url('%s', '%s', '%s'): not found", p->guid, m->guid, u->url);
614                 pu = registry_person_url_allocate(p, m, u, name, namelen, when);
615                 registry.persons_urls_count++;
616         }
617         else {
618                 debug(D_REGISTRY, "registry_person_link_to_url('%s', '%s', '%s'): found", p->guid, m->guid, u->url);
619                 pu->usages++;
620
621                 if(pu->machine != m) {
622                         MACHINE_URL *mu = dictionary_get(pu->machine->urls, u->url);
623                         if(mu) {
624                                 info("registry_person_link_to_url('%s', '%s', '%s'): URL switched machines (old was '%s') - expiring it from previous machine.",
625                                          p->guid, m->guid, u->url, pu->machine->guid);
626                                 mu->flags |= REGISTRY_URL_FLAGS_EXPIRED;
627                         }
628                         else {
629                                 info("registry_person_link_to_url('%s', '%s', '%s'): URL switched machines (old was '%s') - but the URL is not linked to the old machine.",
630                                          p->guid, m->guid, u->url, pu->machine->guid);
631                         }
632
633                         pu->machine->links--;
634                         pu->machine = m;
635                 }
636
637                 if(strcmp(pu->name, name)) {
638                         // the name of the PERSON_URL has changed !
639                         pu = registry_person_url_reallocate(p, m, u, name, namelen, when, pu);
640                 }
641         }
642
643         p->usages++;
644         p->last_t = when;
645
646         if(pu->flags & REGISTRY_URL_FLAGS_EXPIRED) {
647                 info("registry_person_link_to_url('%s', '%s', '%s'): accessing an expired URL. Re-enabling URL.", p->guid, m->guid, u->url);
648                 pu->flags &= ~REGISTRY_URL_FLAGS_EXPIRED;
649         }
650
651         registry_person_urls_unlock(p);
652
653         return pu;
654 }
655
656 static inline MACHINE_URL *registry_machine_link_to_url(PERSON *p, MACHINE *m, URL *u, time_t when) {
657         debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): searching for URL in machine", p->guid, m->guid, u->url);
658
659         registry_machine_urls_lock(m);
660
661         MACHINE_URL *mu = dictionary_get(m->urls, u->url);
662         if(!mu) {
663                 debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): not found", p->guid, m->guid, u->url);
664                 mu = registry_machine_url_allocate(m, u, when);
665                 registry.machines_urls_count++;
666         }
667         else {
668                 debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): found", p->guid, m->guid, u->url);
669                 mu->usages++;
670         }
671
672         //debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): indexing person in machine", p->guid, m->guid, u->url);
673         //dictionary_set(mu->persons, p->guid, p, sizeof(PERSON));
674
675         m->usages++;
676         m->last_t = when;
677
678         if(mu->flags & REGISTRY_URL_FLAGS_EXPIRED) {
679                 info("registry_machine_link_to_url('%s', '%s', '%s'): accessing an expired URL.", p->guid, m->guid, u->url);
680                 mu->flags &= ~REGISTRY_URL_FLAGS_EXPIRED;
681         }
682
683         registry_machine_urls_unlock(m);
684
685         return mu;
686 }
687
688 // ----------------------------------------------------------------------------
689 // REGISTRY LOG LOAD/SAVE
690
691 static inline int registry_should_save_db(void) {
692         debug(D_REGISTRY, "log entries %llu, max %llu", registry.log_count, registry.save_registry_every_entries);
693         return registry.log_count > registry.save_registry_every_entries;
694 }
695
696 static inline void registry_log(const char action, PERSON *p, MACHINE *m, URL *u, char *name) {
697         if(likely(registry.log_fp)) {
698                 // we lock only if the file is open
699                 // to allow replaying the log at registry_log_load()
700                 registry_log_lock();
701
702                 if(unlikely(fprintf(registry.log_fp, "%c\t%08x\t%s\t%s\t%s\t%s\n",
703                                 action,
704                                 p->last_t,
705                                 p->guid,
706                                 m->guid,
707                                 name,
708                                 u->url) < 0))
709                         error("Registry: failed to save log. Registry data may be lost in case of abnormal restart.");
710
711                 // we increase the counter even on failures
712                 // so that the registry will be saved periodically
713                 registry.log_count++;
714
715                 registry_log_unlock();
716
717                 // this must be outside the log_lock(), or a deadlock will happen.
718                 // registry_save() checks the same inside the log_lock, so only
719                 // one thread will save the db
720                 if(unlikely(registry_should_save_db()))
721                         registry_save();
722         }
723 }
724
725 static inline int registry_log_open_nolock(void) {
726         if(registry.log_fp)
727                 fclose(registry.log_fp);
728
729         registry.log_fp = fopen(registry.log_filename, "a");
730
731         if(registry.log_fp) {
732                 if (setvbuf(registry.log_fp, NULL, _IOLBF, 0) != 0)
733                         error("Cannot set line buffering on registry log file.");
734                 return 0;
735         }
736
737         error("Cannot open registry log file '%s'. Registry data will be lost in case of netdata or server crash.", registry.log_filename);
738         return -1;
739 }
740
741 static inline void registry_log_close_nolock(void) {
742         if(registry.log_fp) {
743                 fclose(registry.log_fp);
744                 registry.log_fp = NULL;
745         }
746 }
747
748 static inline void registry_log_recreate_nolock(void) {
749         if(registry.log_fp != NULL) {
750                 registry_log_close_nolock();
751
752                 // open it with truncate
753                 registry.log_fp = fopen(registry.log_filename, "w");
754                 if(registry.log_fp) fclose(registry.log_fp);
755                 else error("Cannot truncate registry log '%s'", registry.log_filename);
756
757                 registry.log_fp = NULL;
758
759                 registry_log_open_nolock();
760         }
761 }
762
763 int registry_log_load(void) {
764         char *s, buf[4096 + 1];
765         size_t line = -1;
766
767         // closing the log is required here
768         // otherwise we will append to it the values we read
769         registry_log_close_nolock();
770
771         debug(D_REGISTRY, "Registry: loading active db from: %s", registry.log_filename);
772         FILE *fp = fopen(registry.log_filename, "r");
773         if(!fp)
774                 error("Registry: cannot open registry file: %s", registry.log_filename);
775         else {
776                 line = 0;
777                 size_t len = 0;
778                 while ((s = fgets_trim_len(buf, 4096, fp, &len))) {
779                         line++;
780
781                         switch (s[0]) {
782                                 case 'A': // accesses
783                                 case 'D': // deletes
784
785                                         // verify it is valid
786                                         if (unlikely(len < 85 || s[1] != '\t' || s[10] != '\t' || s[47] != '\t' || s[84] != '\t')) {
787                                                 error("Registry: log line %u is wrong (len = %zu).", line, len);
788                                                 continue;
789                                         }
790                                         s[1] = s[10] = s[47] = s[84] = '\0';
791
792                                         // get the variables
793                                         time_t when = strtoul(&s[2], NULL, 16);
794                                         char *person_guid = &s[11];
795                                         char *machine_guid = &s[48];
796                                         char *name = &s[85];
797
798                                         // skip the name to find the url
799                                         char *url = name;
800                                         while(*url && *url != '\t') url++;
801                                         if(!*url) {
802                                                 error("Registry: log line %u does not have a url.", line);
803                                                 continue;
804                                         }
805                                         *url++ = '\0';
806
807                                         // make sure the person exists
808                                         // without this, a new person guid will be created
809                                         PERSON *p = registry_person_find(person_guid);
810                                         if(!p) p = registry_person_allocate(person_guid, when);
811
812                                         if(s[0] == 'A')
813                                                 registry_request_access(p->guid, machine_guid, url, name, when);
814                                         else
815                                                 registry_request_delete(p->guid, machine_guid, url, name, when);
816
817                                         break;
818
819                                 default:
820                                         error("Registry: ignoring line %zu of filename '%s': %s.", line, registry.log_filename, s);
821                                         break;
822                         }
823                 }
824         }
825
826         // open the log again
827         registry_log_open_nolock();
828
829         return line;
830 }
831
832
833 // ----------------------------------------------------------------------------
834 // REGISTRY REQUESTS
835
836 PERSON *registry_request_access(char *person_guid, char *machine_guid, char *url, char *name, time_t when) {
837         debug(D_REGISTRY, "registry_request_access('%s', '%s', '%s'): NEW REQUEST", (person_guid)?person_guid:"", machine_guid, url);
838
839         MACHINE *m = registry_machine_get(machine_guid, when);
840         if(!m) return NULL;
841
842         // make sure the name is valid
843         size_t namelen;
844         name = registry_fix_machine_name(name, &namelen);
845
846         size_t urllen;
847         url = registry_fix_url(url, &urllen);
848
849         URL *u = registry_url_get(url, urllen);
850         PERSON *p = registry_person_get(person_guid, when);
851
852         registry_person_link_to_url(p, m, u, name, namelen, when);
853         registry_machine_link_to_url(p, m, u, when);
854
855         registry_log('A', p, m, u, name);
856
857         registry.usages_count++;
858         return p;
859 }
860
861 // verify the person, the machine and the URL exist in our DB
862 PERSON_URL *registry_verify_request(char *person_guid, char *machine_guid, char *url, PERSON **pp, MACHINE **mm) {
863         char pbuf[36 + 1], mbuf[36 + 1];
864
865         if(!person_guid || !*person_guid || !machine_guid || !*machine_guid || !url || !*url) {
866                 info("Registry Request Verification: invalid request! person: '%s', machine '%s', url '%s'", person_guid?person_guid:"UNSET", machine_guid?machine_guid:"UNSET", url?url:"UNSET");
867                 return NULL;
868         }
869
870         // normalize the url
871         url = registry_fix_url(url, NULL);
872
873         // make sure the person GUID is valid
874         if(registry_regenerate_guid(person_guid, pbuf) == -1) {
875                 info("Registry Request Verification: invalid person GUID, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
876                 return NULL;
877         }
878         person_guid = pbuf;
879
880         // make sure the machine GUID is valid
881         if(registry_regenerate_guid(machine_guid, mbuf) == -1) {
882                 info("Registry Request Verification: invalid machine GUID, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
883                 return NULL;
884         }
885         machine_guid = mbuf;
886
887         // make sure the machine exists
888         MACHINE *m = registry_machine_find(machine_guid);
889         if(!m) {
890                 info("Registry Request Verification: machine not found, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
891                 return NULL;
892         }
893         if(mm) *mm = m;
894
895         // make sure the person exist
896         PERSON *p = registry_person_find(person_guid);
897         if(!p) {
898                 info("Registry Request Verification: person not found, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
899                 return NULL;
900         }
901         if(pp) *pp = p;
902
903         PERSON_URL *pu = dictionary_get(p->urls, url);
904         if(!pu) {
905                 info("Registry Request Verification: URL not found for person, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
906                 return NULL;
907         }
908         return pu;
909 }
910
911 PERSON *registry_request_delete(char *person_guid, char *machine_guid, char *url, char *delete_url, time_t when) {
912         (void)when;
913
914         PERSON *p = NULL;
915         MACHINE *m = NULL;
916         PERSON_URL *pu = registry_verify_request(person_guid, machine_guid, url, &p, &m);
917         if(!pu || !p || !m) return NULL;
918
919         // normalize the url
920         delete_url = registry_fix_url(delete_url, NULL);
921
922         // make sure the user is not deleting the url it uses
923         if(!strcmp(delete_url, pu->url->url)) {
924                 info("Registry Delete Request: delete URL is the one currently accessed, person: '%s', machine '%s', url '%s', delete url '%s'", p->guid, m->guid, pu->url->url, delete_url);
925                 return NULL;
926         }
927
928         registry_person_urls_lock(p);
929
930         PERSON_URL *dpu = dictionary_get(p->urls, delete_url);
931         if(!dpu) {
932                 info("Registry Delete Request: URL not found for person: '%s', machine '%s', url '%s', delete url '%s'", p->guid, m->guid, pu->url->url, delete_url);
933                 registry_person_urls_unlock(p);
934                 return NULL;
935         }
936
937         registry_log('D', p, m, pu->url, dpu->url->url);
938
939         dictionary_del(p->urls, dpu->url->url);
940         registry_url_unlink_nolock(dpu->url);
941         free(dpu);
942
943         registry_person_urls_unlock(p);
944         return p;
945 }
946
947
948 // a structure to pass to the dictionary_get_all() callback handler
949 struct machine_request_callback_data {
950         MACHINE *find_this_machine;
951         PERSON_URL *result;
952 };
953
954 // the callback function
955 // this will be run for every PERSON_URL of this PERSON
956 int machine_request_callback(void *entry, void *data) {
957         PERSON_URL *mypu = (PERSON_URL *)entry;
958         struct machine_request_callback_data *myrdata = (struct machine_request_callback_data *)data;
959
960         if(mypu->machine == myrdata->find_this_machine) {
961                 myrdata->result = mypu;
962                 return -1; // this will also stop the walk through
963         }
964
965         return 0; // continue
966 }
967
968 MACHINE *registry_request_machine(char *person_guid, char *machine_guid, char *url, char *request_machine, time_t when) {
969         (void)when;
970
971         char mbuf[36 + 1];
972
973         PERSON *p = NULL;
974         MACHINE *m = NULL;
975         PERSON_URL *pu = registry_verify_request(person_guid, machine_guid, url, &p, &m);
976         if(!pu || !p || !m) return NULL;
977
978         // make sure the machine GUID is valid
979         if(registry_regenerate_guid(request_machine, mbuf) == -1) {
980                 info("Registry Machine URLs request: invalid machine GUID, person: '%s', machine '%s', url '%s', request machine '%s'", p->guid, m->guid, pu->url->url, request_machine);
981                 return NULL;
982         }
983         request_machine = mbuf;
984
985         // make sure the machine exists
986         m = registry_machine_find(request_machine);
987         if(!m) {
988                 info("Registry Machine URLs request: machine not found, person: '%s', machine '%s', url '%s', request machine '%s'", p->guid, m->guid, pu->url->url, request_machine);
989                 return NULL;
990         }
991
992         // Verify the user has in the past accessed this machine
993         // We will walk through the PERSON_URLs to find the machine
994         // linking to our machine
995
996         // a structure to pass to the dictionary_get_all() callback handler
997         struct machine_request_callback_data rdata = { m, NULL };
998
999         // request a walk through on the dictionary
1000         // no need for locking here, the underlying dictionary has its own
1001         dictionary_get_all(p->urls, machine_request_callback, &rdata);
1002
1003         if(rdata.result)
1004                 return m;
1005
1006         return NULL;
1007 }
1008
1009
1010 // ----------------------------------------------------------------------------
1011 // REGISTRY JSON generation
1012
1013 #define REGISTRY_STATUS_OK "ok"
1014 #define REGISTRY_STATUS_FAILED "failed"
1015 #define REGISTRY_STATUS_DISABLED "disabled"
1016
1017 static inline void registry_set_person_cookie(struct web_client *w, PERSON *p) {
1018         char edate[100];
1019         time_t et = time(NULL) + registry.persons_expiration;
1020         struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1021         strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1022
1023         if(registry.registry_domain && registry.registry_domain[0])
1024                 snprintf(w->cookie, COOKIE_MAX, NETDATA_REGISTRY_COOKIE_NAME "=%s; Domain=%s; Expires=%s", p->guid, registry.registry_domain, edate);
1025         else
1026                 snprintf(w->cookie, COOKIE_MAX, NETDATA_REGISTRY_COOKIE_NAME "=%s; Expires=%s", p->guid, edate);
1027
1028         w->cookie[COOKIE_MAX] = '\0';
1029 }
1030
1031 static inline void registry_json_header(struct web_client *w, const char *action, const char *status) {
1032         w->response.data->contenttype = CT_APPLICATION_JSON;
1033         buffer_flush(w->response.data);
1034         buffer_sprintf(w->response.data, "{\n\t\"action\": \"%s\",\n\t\"status\": \"%s\",\n\t\"hostname\": \"%s\",\n\t\"machine_guid\": \"%s\"",
1035                                    action, status, registry.hostname, registry.machine_guid);
1036 }
1037
1038 static inline void registry_json_footer(struct web_client *w) {
1039         buffer_strcat(w->response.data, "\n}\n");
1040 }
1041
1042 int registry_request_hello_json(struct web_client *w) {
1043         registry_json_header(w, "hello", REGISTRY_STATUS_OK);
1044
1045         buffer_sprintf(w->response.data, ",\n\t\"registry\": \"%s\"",
1046                                    registry.registry_to_announce);
1047
1048         registry_json_footer(w);
1049         return 200;
1050 }
1051
1052 static inline int registry_json_disabled(struct web_client *w, const char *action) {
1053         registry_json_header(w, action, REGISTRY_STATUS_DISABLED);
1054
1055         buffer_sprintf(w->response.data, ",\n\t\"registry\": \"%s\"",
1056                                    registry.registry_to_announce);
1057
1058         registry_json_footer(w);
1059         return 200;
1060 }
1061
1062 // structure used be the callbacks below
1063 struct registry_json_walk_person_urls_callback {
1064         PERSON *p;
1065         MACHINE *m;
1066         struct web_client *w;
1067         int count;
1068 };
1069
1070 // callback for rendering PERSON_URLs
1071 static inline int registry_json_person_url_callback(void *entry, void *data) {
1072         PERSON_URL *pu = (PERSON_URL *)entry;
1073         struct registry_json_walk_person_urls_callback *c = (struct registry_json_walk_person_urls_callback *)data;
1074         struct web_client *w = c->w;
1075
1076         if(unlikely(c->count++))
1077                 buffer_strcat(w->response.data, ",");
1078
1079         buffer_sprintf(w->response.data, "\n\t\t[ \"%s\", \"%s\", %u000, %u, \"%s\" ]",
1080                                    pu->machine->guid, pu->url->url, pu->last_t, pu->usages, pu->name);
1081
1082         return 1;
1083 }
1084
1085 // callback for rendering MACHINE_URLs
1086 static inline int registry_json_machine_url_callback(void *entry, void *data) {
1087         MACHINE_URL *mu = (MACHINE_URL *)entry;
1088         struct registry_json_walk_person_urls_callback *c = (struct registry_json_walk_person_urls_callback *)data;
1089         struct web_client *w = c->w;
1090         MACHINE *m = c->m;
1091
1092         if(unlikely(c->count++))
1093                 buffer_strcat(w->response.data, ",");
1094
1095         buffer_sprintf(w->response.data, "\n\t\t[ \"%s\", \"%s\", %u000, %u ]",
1096                                    m->guid, mu->url->url, mu->last_t, mu->usages);
1097
1098         return 1;
1099 }
1100
1101
1102 // the main method for registering an access
1103 int registry_request_access_json(struct web_client *w, char *person_guid, char *machine_guid, char *url, char *name, time_t when) {
1104         if(!registry.enabled)
1105                 return registry_json_disabled(w, "access");
1106
1107         PERSON *p = registry_request_access(person_guid, machine_guid, url, name, when);
1108         if(!p) {
1109                 registry_json_header(w, "access", REGISTRY_STATUS_FAILED);
1110                 registry_json_footer(w);
1111                 return 412;
1112         }
1113
1114         // set the cookie
1115         registry_set_person_cookie(w, p);
1116
1117         // generate the response
1118         registry_json_header(w, "access", REGISTRY_STATUS_OK);
1119
1120         buffer_sprintf(w->response.data, ",\n\t\"person_guid\": \"%s\",\n\t\"urls\": [", p->guid);
1121         struct registry_json_walk_person_urls_callback c = { p, NULL, w, 0 };
1122         dictionary_get_all(p->urls, registry_json_person_url_callback, &c);
1123         buffer_strcat(w->response.data, "\n\t]\n");
1124
1125         registry_json_footer(w);
1126         return 200;
1127 }
1128
1129 // the main method for deleting a URL from a person
1130 int registry_request_delete_json(struct web_client *w, char *person_guid, char *machine_guid, char *url, char *delete_url, time_t when) {
1131         if(!registry.enabled)
1132                 return registry_json_disabled(w, "delete");
1133
1134         PERSON *p = registry_request_delete(person_guid, machine_guid, url, delete_url, when);
1135         if(!p) {
1136                 registry_json_header(w, "delete", REGISTRY_STATUS_FAILED);
1137                 registry_json_footer(w);
1138                 return 412;
1139         }
1140
1141         // generate the response
1142         registry_json_header(w, "delete", REGISTRY_STATUS_OK);
1143         registry_json_footer(w);
1144         return 200;
1145 }
1146
1147 // the main method for searching the URLs of a netdata
1148 int registry_request_search_json(struct web_client *w, char *person_guid, char *machine_guid, char *url, char *request_machine, time_t when) {
1149         if(!registry.enabled)
1150                 return registry_json_disabled(w, "search");
1151
1152         MACHINE *m = registry_request_machine(person_guid, machine_guid, url, request_machine, when);
1153         if(!m) {
1154                 registry_json_header(w, "search", REGISTRY_STATUS_FAILED);
1155                 registry_json_footer(w);
1156                 return 404;
1157         }
1158
1159         registry_json_header(w, "search", REGISTRY_STATUS_OK);
1160
1161         buffer_strcat(w->response.data, ",\n\t\"urls\": [");
1162         struct registry_json_walk_person_urls_callback c = { NULL, m, w, 0 };
1163         dictionary_get_all(m->urls, registry_json_machine_url_callback, &c);
1164         buffer_strcat(w->response.data, "\n\t]\n");
1165
1166         registry_json_footer(w);
1167         return 200;
1168 }
1169
1170
1171 int registry_person_url_callback_verify_machine_exists(void *entry, void *machine) {
1172         PERSON_URL *pu = (PERSON_URL *)entry;
1173         MACHINE *m = (MACHINE *)machine;
1174
1175         if(pu->machine == m)
1176                 return 1;
1177         else
1178                 return 0;
1179 }
1180
1181 // the main method for switching user identity
1182 int registry_request_switch_json(struct web_client *w, char *person_guid, char *machine_guid, char *url, char *new_person_guid, time_t when) {
1183         (void)url;
1184         (void)when;
1185
1186         if(!registry.enabled)
1187                 return registry_json_disabled(w, "switch");
1188
1189         PERSON *op = registry_person_find(person_guid);
1190         if(!op) {
1191                 registry_json_header(w, "switch", REGISTRY_STATUS_FAILED);
1192                 registry_json_footer(w);
1193                 return 430;
1194         }
1195
1196         PERSON *np = registry_person_find(new_person_guid);
1197         if(!np) {
1198                 registry_json_header(w, "switch", REGISTRY_STATUS_FAILED);
1199                 registry_json_footer(w);
1200                 return 431;
1201         }
1202
1203         MACHINE *m = registry_machine_find(machine_guid);
1204         if(!m) {
1205                 registry_json_header(w, "switch", REGISTRY_STATUS_FAILED);
1206                 registry_json_footer(w);
1207                 return 432;
1208         }
1209
1210         // verify the old person has access to this machine
1211         int count = dictionary_get_all(op->urls, registry_person_url_callback_verify_machine_exists, m);
1212         if(!count) {
1213                 registry_json_header(w, "switch", REGISTRY_STATUS_FAILED);
1214                 registry_json_footer(w);
1215                 return 433;
1216         }
1217
1218         // verify the new person has access to this machine
1219         count = dictionary_get_all(np->urls, registry_person_url_callback_verify_machine_exists, m);
1220         if(!count) {
1221                 registry_json_header(w, "switch", REGISTRY_STATUS_FAILED);
1222                 registry_json_footer(w);
1223                 return 434;
1224         }
1225
1226         // set the cookie of the new person
1227         // the user just switched identity
1228         registry_set_person_cookie(w, np);
1229
1230         // generate the response
1231         registry_json_header(w, "switch", REGISTRY_STATUS_OK);
1232         buffer_sprintf(w->response.data, ",\n\t\"person_guid\": \"%s\"", np->guid);
1233         registry_json_footer(w);
1234         return 200;
1235 }
1236
1237
1238 // ----------------------------------------------------------------------------
1239 // REGISTRY THIS MACHINE UNIQUE ID
1240
1241 char *registry_get_this_machine_guid(void) {
1242         if(likely(registry.machine_guid[0]))
1243                 return registry.machine_guid;
1244
1245         // read it from disk
1246         int fd = open(registry.machine_guid_filename, O_RDONLY);
1247         if(fd != -1) {
1248                 char buf[36 + 1];
1249                 if(read(fd, buf, 36) != 36)
1250                         error("Failed to read machine GUID from '%s'", registry.machine_guid_filename);
1251                 else {
1252                         buf[36] = '\0';
1253                         if(registry_regenerate_guid(buf, registry.machine_guid) == -1) {
1254                                 error("Failed to validate machine GUID '%s' from '%s'. Ignoring it - this might mean this netdata will appear as duplicate in the registry.",
1255                                           buf, registry.machine_guid_filename);
1256
1257                                 registry.machine_guid[0] = '\0';
1258                         }
1259                 }
1260                 close(fd);
1261         }
1262
1263         // generate a new one?
1264         if(!registry.machine_guid[0]) {
1265                 int count = 10, ret = 0;
1266                 uuid_t uuid;
1267
1268                 // for some reason it reports unsafe generation the first time
1269                 while(count-- && (ret = uuid_generate_time_safe(uuid)) == -1) ;
1270                 uuid_unparse_lower(uuid, registry.machine_guid);
1271                 registry.machine_guid[36] = '\0';
1272
1273                 if(ret == -1)
1274                         info("Warning: generated machine GUID '%s' was not generated using a safe method.", registry.machine_guid);
1275
1276                 // save it
1277                 fd = open(registry.machine_guid_filename, O_WRONLY|O_CREAT|O_TRUNC, 444);
1278                 if(fd == -1)
1279                         fatal("Cannot create unique machine id file '%s'. Please fix this.", registry.machine_guid_filename);
1280
1281                 if(write(fd, registry.machine_guid, 36) != 36)
1282                         fatal("Cannot write the unique machine id file '%s'. Please fix this.", registry.machine_guid_filename);
1283
1284                 close(fd);
1285         }
1286
1287         return registry.machine_guid;
1288 }
1289
1290
1291 // ----------------------------------------------------------------------------
1292 // REGISTRY LOAD/SAVE
1293
1294 int registry_machine_save_url(void *entry, void *file) {
1295         MACHINE_URL *mu = entry;
1296         FILE *fp = file;
1297
1298         debug(D_REGISTRY, "Registry: registry_machine_save_url('%s')", mu->url->url);
1299
1300         int ret = fprintf(fp, "V\t%08x\t%08x\t%08x\t%02x\t%s\n",
1301                         mu->first_t,
1302                         mu->last_t,
1303                         mu->usages,
1304                         mu->flags,
1305                         mu->url->url
1306         );
1307
1308         // error handling is done at registry_save()
1309
1310         return ret;
1311 }
1312
1313 int registry_machine_save(void *entry, void *file) {
1314         MACHINE *m = entry;
1315         FILE *fp = file;
1316
1317         debug(D_REGISTRY, "Registry: registry_machine_save('%s')", m->guid);
1318
1319         int ret = fprintf(fp, "M\t%08x\t%08x\t%08x\t%s\n",
1320                         m->first_t,
1321                         m->last_t,
1322                         m->usages,
1323                         m->guid
1324         );
1325
1326         if(ret >= 0) {
1327                 int ret2 = dictionary_get_all(m->urls, registry_machine_save_url, fp);
1328                 if(ret2 < 0) return ret2;
1329                 ret += ret2;
1330         }
1331
1332         // error handling is done at registry_save()
1333
1334         return ret;
1335 }
1336
1337 static inline int registry_person_save_url(void *entry, void *file) {
1338         PERSON_URL *pu = entry;
1339         FILE *fp = file;
1340
1341         debug(D_REGISTRY, "Registry: registry_person_save_url('%s')", pu->url->url);
1342
1343         int ret = fprintf(fp, "U\t%08x\t%08x\t%08x\t%02x\t%s\t%s\t%s\n",
1344                         pu->first_t,
1345                         pu->last_t,
1346                         pu->usages,
1347                         pu->flags,
1348                         pu->machine->guid,
1349                         pu->name,
1350                         pu->url->url
1351         );
1352
1353         // error handling is done at registry_save()
1354
1355         return ret;
1356 }
1357
1358 static inline int registry_person_save(void *entry, void *file) {
1359         PERSON *p = entry;
1360         FILE *fp = file;
1361
1362         debug(D_REGISTRY, "Registry: registry_person_save('%s')", p->guid);
1363
1364         int ret = fprintf(fp, "P\t%08x\t%08x\t%08x\t%s\n",
1365                         p->first_t,
1366                         p->last_t,
1367                         p->usages,
1368                         p->guid
1369         );
1370
1371         if(ret >= 0) {
1372                 int ret2 = dictionary_get_all(p->urls, registry_person_save_url, fp);
1373                 if (ret2 < 0) return ret2;
1374                 ret += ret2;
1375         }
1376
1377         // error handling is done at registry_save()
1378
1379         return ret;
1380 }
1381
1382 int registry_save(void) {
1383         if(!registry.enabled) return -1;
1384
1385         // make sure the log is not updated
1386         registry_log_lock();
1387
1388         if(unlikely(!registry_should_save_db())) {
1389                 registry_log_unlock();
1390                 return -2;
1391         }
1392
1393         char tmp_filename[FILENAME_MAX + 1];
1394         char old_filename[FILENAME_MAX + 1];
1395
1396         snprintf(old_filename, FILENAME_MAX, "%s.old", registry.db_filename);
1397         snprintf(tmp_filename, FILENAME_MAX, "%s.tmp", registry.db_filename);
1398
1399         debug(D_REGISTRY, "Registry: Creating file '%s'", tmp_filename);
1400         FILE *fp = fopen(tmp_filename, "w");
1401         if(!fp) {
1402                 error("Registry: Cannot create file: %s", tmp_filename);
1403                 registry_log_unlock();
1404                 return -1;
1405         }
1406
1407         // dictionary_get_all() has its own locking, so this is safe to do
1408
1409         debug(D_REGISTRY, "Saving all machines");
1410         int bytes1 = dictionary_get_all(registry.machines, registry_machine_save, fp);
1411         if(bytes1 < 0) {
1412                 error("Registry: Cannot save registry machines - return value %d", bytes1);
1413                 fclose(fp);
1414                 registry_log_unlock();
1415                 return bytes1;
1416         }
1417         debug(D_REGISTRY, "Registry: saving machines took %d bytes", bytes1);
1418
1419         debug(D_REGISTRY, "Saving all persons");
1420         int bytes2 = dictionary_get_all(registry.persons, registry_person_save, fp);
1421         if(bytes2 < 0) {
1422                 error("Registry: Cannot save registry persons - return value %d", bytes2);
1423                 fclose(fp);
1424                 registry_log_unlock();
1425                 return bytes2;
1426         }
1427         debug(D_REGISTRY, "Registry: saving persons took %d bytes", bytes2);
1428
1429         // save the totals
1430         fprintf(fp, "T\t%016llx\t%016llx\t%016llx\t%016llx\t%016llx\t%016llx\n",
1431                         registry.persons_count,
1432                         registry.machines_count,
1433                         registry.usages_count + 1, // this is required - it is lost on db rotation
1434                         registry.urls_count,
1435                         registry.persons_urls_count,
1436                         registry.machines_urls_count
1437         );
1438
1439         fclose(fp);
1440
1441         errno = 0;
1442
1443         // remove the .old db
1444         debug(D_REGISTRY, "Registry: Removing old db '%s'", old_filename);
1445         if(unlink(old_filename) == -1 && errno != ENOENT)
1446                 error("Registry: cannot remove old registry file '%s'", old_filename);
1447
1448         // rename the db to .old
1449         debug(D_REGISTRY, "Registry: Link current db '%s' to .old: '%s'", registry.db_filename, old_filename);
1450         if(link(registry.db_filename, old_filename) == -1 && errno != ENOENT)
1451                 error("Registry: cannot move file '%s' to '%s'. Saving registry DB failed!", tmp_filename, registry.db_filename);
1452
1453         else {
1454                 // remove the database (it is saved in .old)
1455                 debug(D_REGISTRY, "Registry: removing db '%s'", registry.db_filename);
1456                 if (unlink(registry.db_filename) == -1 && errno != ENOENT)
1457                         error("Registry: cannot remove old registry file '%s'", registry.db_filename);
1458
1459                 // move the .tmp to make it active
1460                 debug(D_REGISTRY, "Registry: linking tmp db '%s' to active db '%s'", tmp_filename, registry.db_filename);
1461                 if (link(tmp_filename, registry.db_filename) == -1) {
1462                         error("Registry: cannot move file '%s' to '%s'. Saving registry DB failed!", tmp_filename,
1463                                   registry.db_filename);
1464
1465                         // move the .old back
1466                         debug(D_REGISTRY, "Registry: linking old db '%s' to active db '%s'", old_filename, registry.db_filename);
1467                         if(link(old_filename, registry.db_filename) == -1)
1468                                 error("Registry: cannot move file '%s' to '%s'. Recovering the old registry DB failed!", old_filename, registry.db_filename);
1469                 }
1470                 else {
1471                         debug(D_REGISTRY, "Registry: removing tmp db '%s'", tmp_filename);
1472                         if(unlink(tmp_filename) == -1)
1473                                 error("Registry: cannot remove tmp registry file '%s'", tmp_filename);
1474
1475                         // it has been moved successfully
1476                         // discard the current registry log
1477                         registry_log_recreate_nolock();
1478
1479                         registry.log_count = 0;
1480                 }
1481         }
1482
1483         // continue operations
1484         registry_log_unlock();
1485
1486         return -1;
1487 }
1488
1489 static inline size_t registry_load(void) {
1490         char *s, buf[4096 + 1];
1491         PERSON *p = NULL;
1492         MACHINE *m = NULL;
1493         URL *u = NULL;
1494         size_t line = 0;
1495
1496         debug(D_REGISTRY, "Registry: loading active db from: '%s'", registry.db_filename);
1497         FILE *fp = fopen(registry.db_filename, "r");
1498         if(!fp) {
1499                 error("Registry: cannot open registry file: '%s'", registry.db_filename);
1500                 return 0;
1501         }
1502
1503         size_t len = 0;
1504         buf[4096] = '\0';
1505         while((s = fgets_trim_len(buf, 4096, fp, &len))) {
1506                 line++;
1507
1508                 debug(D_REGISTRY, "Registry: read line %zu to length %zu: %s", line, len, s);
1509                 switch(*s) {
1510                         case 'T': // totals
1511                                 if(unlikely(len != 103 || s[1] != '\t' || s[18] != '\t' || s[35] != '\t' || s[52] != '\t' || s[69] != '\t' || s[86] != '\t' || s[103] != '\0')) {
1512                                         error("Registry totals line %u is wrong (len = %zu).", line, len);
1513                                         continue;
1514                                 }
1515                                 registry.persons_count = strtoull(&s[2], NULL, 16);
1516                                 registry.machines_count = strtoull(&s[19], NULL, 16);
1517                                 registry.usages_count = strtoull(&s[36], NULL, 16);
1518                                 registry.urls_count = strtoull(&s[53], NULL, 16);
1519                                 registry.persons_urls_count = strtoull(&s[70], NULL, 16);
1520                                 registry.machines_urls_count = strtoull(&s[87], NULL, 16);
1521                                 break;
1522
1523                         case 'P': // person
1524                                 m = NULL;
1525                                 // verify it is valid
1526                                 if(unlikely(len != 65 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[65] != '\0')) {
1527                                         error("Registry person line %u is wrong (len = %zu).", line, len);
1528                                         continue;
1529                                 }
1530
1531                                 s[1] = s[10] = s[19] = s[28] = '\0';
1532                                 p = registry_person_allocate(&s[29], strtoul(&s[2], NULL, 16));
1533                                 p->last_t = strtoul(&s[11], NULL, 16);
1534                                 p->usages = strtoul(&s[20], NULL, 16);
1535                                 debug(D_REGISTRY, "Registry loaded person '%s', first: %u, last: %u, usages: %u", p->guid, p->first_t, p->last_t, p->usages);
1536                                 break;
1537
1538                         case 'M': // machine
1539                                 p = NULL;
1540                                 // verify it is valid
1541                                 if(unlikely(len != 65 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[65] != '\0')) {
1542                                         error("Registry person line %u is wrong (len = %zu).", line, len);
1543                                         continue;
1544                                 }
1545
1546                                 s[1] = s[10] = s[19] = s[28] = '\0';
1547                                 m = registry_machine_allocate(&s[29], strtoul(&s[2], NULL, 16));
1548                                 m->last_t = strtoul(&s[11], NULL, 16);
1549                                 m->usages = strtoul(&s[20], NULL, 16);
1550                                 debug(D_REGISTRY, "Registry loaded machine '%s', first: %u, last: %u, usages: %u", m->guid, m->first_t, m->last_t, m->usages);
1551                                 break;
1552
1553                         case 'U': // person URL
1554                                 if(unlikely(!p)) {
1555                                         error("Registry: ignoring line %zu, no person loaded: %s", line, s);
1556                                         continue;
1557                                 }
1558
1559                                 // verify it is valid
1560                                 if(len < 69 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[31] != '\t' || s[68] != '\t') {
1561                                         error("Registry person URL line %u is wrong (len = %zu).", line, len);
1562                                         continue;
1563                                 }
1564
1565                                 s[1] = s[10] = s[19] = s[28] = s[31] = s[68] = '\0';
1566
1567                                 // skip the name to find the url
1568                                 char *url = &s[69];
1569                                 while(*url && *url != '\t') url++;
1570                                 if(!*url) {
1571                                         error("Registry person URL line %u does not have a url.", line);
1572                                         continue;
1573                                 }
1574                                 *url++ = '\0';
1575
1576                                 u = registry_url_allocate_nolock(url, strlen(url));
1577
1578                                 time_t first_t = strtoul(&s[2], NULL, 16);
1579
1580                                 m = registry_machine_find(&s[32]);
1581                                 if(!m) m = registry_machine_allocate(&s[32], first_t);
1582
1583                                 PERSON_URL *pu = registry_person_url_allocate(p, m, u, &s[69], strlen(&s[69]), first_t);
1584                                 pu->last_t = strtoul(&s[11], NULL, 16);
1585                                 pu->usages = strtoul(&s[20], NULL, 16);
1586                                 pu->flags = strtoul(&s[29], NULL, 16);
1587                                 debug(D_REGISTRY, "Registry loaded person URL '%s' with name '%s' of machine '%s', first: %u, last: %u, usages: %u, flags: %02x", u->url, pu->name, m->guid, pu->first_t, pu->last_t, pu->usages, pu->flags);
1588                                 break;
1589
1590                         case 'V': // machine URL
1591                                 if(unlikely(!m)) {
1592                                         error("Registry: ignoring line %zu, no machine loaded: %s", line, s);
1593                                         continue;
1594                                 }
1595
1596                                 // verify it is valid
1597                                 if(len < 32 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[31] != '\t') {
1598                                         error("Registry person URL line %u is wrong (len = %zu).", line, len);
1599                                         continue;
1600                                 }
1601
1602                                 s[1] = s[10] = s[19] = s[28] = s[31] = '\0';
1603                                 u = registry_url_allocate_nolock(&s[32], strlen(&s[32]));
1604
1605                                 MACHINE_URL *mu = registry_machine_url_allocate(m, u, strtoul(&s[2], NULL, 16));
1606                                 mu->last_t = strtoul(&s[11], NULL, 16);
1607                                 mu->usages = strtoul(&s[20], NULL, 16);
1608                                 mu->flags = strtoul(&s[29], NULL, 16);
1609                                 debug(D_REGISTRY, "Registry loaded machine URL '%s', machine '%s', first: %u, last: %u, usages: %u, flags: %02x", u->url, m->guid, mu->first_t, mu->last_t, mu->usages, mu->flags);
1610                                 break;
1611
1612                         default:
1613                                 error("Registry: ignoring line %zu of filename '%s': %s.", line, registry.db_filename, s);
1614                                 break;
1615                 }
1616         }
1617         fclose(fp);
1618
1619         return line;
1620 }
1621
1622 // ----------------------------------------------------------------------------
1623 // REGISTRY
1624
1625 int registry_init(void) {
1626         char filename[FILENAME_MAX + 1];
1627
1628         // registry enabled?
1629         registry.enabled = config_get_boolean("registry", "enabled", 0);
1630
1631         // pathnames
1632         registry.pathname = config_get("registry", "registry db directory", VARLIB_DIR "/registry");
1633         if(mkdir(registry.pathname, 0755) == -1 && errno != EEXIST) {
1634                 error("Cannot create directory '%s'. Registry disabled.", registry.pathname);
1635                 registry.enabled = 0;
1636                 return -1;
1637         }
1638
1639         // filenames
1640         snprintf(filename, FILENAME_MAX, "%s/netdata.public.unique.id", registry.pathname);
1641         registry.machine_guid_filename = config_get("registry", "netdata unique id file", filename);
1642         registry_get_this_machine_guid();
1643
1644         snprintf(filename, FILENAME_MAX, "%s/registry.db", registry.pathname);
1645         registry.db_filename = config_get("registry", "registry db file", filename);
1646
1647         snprintf(filename, FILENAME_MAX, "%s/registry-log.db", registry.pathname);
1648         registry.log_filename = config_get("registry", "registry log file", filename);
1649
1650         // configuration options
1651         registry.save_registry_every_entries = config_get_number("registry", "registry save db every new entries", 1000000);
1652         registry.persons_expiration = config_get_number("registry", "registry expire idle persons days", 365) * 86400;
1653         registry.registry_domain = config_get("registry", "registry domain", "");
1654         registry.registry_to_announce = config_get("registry", "registry to announce", "https://registry.my-netdata.io");
1655         registry.hostname = config_get("registry", "registry hostname", config_get("global", "hostname", hostname));
1656
1657         registry.max_url_length = config_get_number("registry", "max URL length", 1024);
1658         registry.max_name_length = config_get_number("registry", "max URL name length", 50);
1659
1660
1661         // initialize entries counters
1662         registry.persons_count = 0;
1663         registry.machines_count = 0;
1664         registry.usages_count = 0;
1665         registry.urls_count = 0;
1666         registry.persons_urls_count = 0;
1667         registry.machines_urls_count = 0;
1668
1669         // initialize memory counters
1670         registry.persons_memory = 0;
1671         registry.machines_memory = 0;
1672         registry.urls_memory = 0;
1673         registry.persons_urls_memory = 0;
1674         registry.machines_urls_memory = 0;
1675
1676         // initialize locks
1677         pthread_mutex_init(&registry.persons_lock, NULL);
1678         pthread_mutex_init(&registry.machines_lock, NULL);
1679         pthread_mutex_init(&registry.urls_lock, NULL);
1680         pthread_mutex_init(&registry.person_urls_lock, NULL);
1681         pthread_mutex_init(&registry.machine_urls_lock, NULL);
1682
1683         // create dictionaries
1684         registry.persons = dictionary_create(DICTIONARY_FLAGS);
1685         registry.machines = dictionary_create(DICTIONARY_FLAGS);
1686         registry.urls = dictionary_create(DICTIONARY_FLAGS);
1687
1688         // load the registry database
1689         if(registry.enabled) {
1690                 registry_log_open_nolock();
1691                 registry_load();
1692                 registry_log_load();
1693         }
1694
1695         return 0;
1696 }
1697
1698 void registry_free(void) {
1699         if(!registry.enabled) return;
1700
1701         // we need to destroy the dictionaries ourselves
1702         // since the dictionaries use memory we allocated
1703
1704         while(registry.persons->values_index.root) {
1705                 PERSON *p = ((NAME_VALUE *)registry.persons->values_index.root)->value;
1706
1707                 // fprintf(stderr, "\nPERSON: '%s', first: %u, last: %u, usages: %u\n", p->guid, p->first_t, p->last_t, p->usages);
1708
1709                 while(p->urls->values_index.root) {
1710                         PERSON_URL *pu = ((NAME_VALUE *)p->urls->values_index.root)->value;
1711
1712                         // fprintf(stderr, "\tURL: '%s', first: %u, last: %u, usages: %u, flags: 0x%02x\n", pu->url->url, pu->first_t, pu->last_t, pu->usages, pu->flags);
1713
1714                         debug(D_REGISTRY, "Registry: deleting url '%s' from person '%s'", pu->url->url, p->guid);
1715                         dictionary_del(p->urls, pu->url->url);
1716
1717                         debug(D_REGISTRY, "Registry: unlinking url '%s' from person", pu->url->url);
1718                         registry_url_unlink_nolock(pu->url);
1719
1720                         debug(D_REGISTRY, "Registry: freeing person url");
1721                         free(pu);
1722                 }
1723
1724                 debug(D_REGISTRY, "Registry: deleting person '%s' from persons registry", p->guid);
1725                 dictionary_del(registry.persons, p->guid);
1726
1727                 debug(D_REGISTRY, "Registry: destroying URL dictionary of person '%s'", p->guid);
1728                 dictionary_destroy(p->urls);
1729
1730                 debug(D_REGISTRY, "Registry: freeing person '%s'", p->guid);
1731                 free(p);
1732         }
1733
1734         while(registry.machines->values_index.root) {
1735                 MACHINE *m = ((NAME_VALUE *)registry.machines->values_index.root)->value;
1736
1737                 // fprintf(stderr, "\nMACHINE: '%s', first: %u, last: %u, usages: %u\n", m->guid, m->first_t, m->last_t, m->usages);
1738
1739                 while(m->urls->values_index.root) {
1740                         MACHINE_URL *mu = ((NAME_VALUE *)m->urls->values_index.root)->value;
1741
1742                         // fprintf(stderr, "\tURL: '%s', first: %u, last: %u, usages: %u, flags: 0x%02x\n", mu->url->url, mu->first_t, mu->last_t, mu->usages, mu->flags);
1743
1744                         //debug(D_REGISTRY, "Registry: destroying persons dictionary from url '%s'", mu->url->url);
1745                         //dictionary_destroy(mu->persons);
1746
1747                         debug(D_REGISTRY, "Registry: deleting url '%s' from person '%s'", mu->url->url, m->guid);
1748                         dictionary_del(m->urls, mu->url->url);
1749
1750                         debug(D_REGISTRY, "Registry: unlinking url '%s' from machine", mu->url->url);
1751                         registry_url_unlink_nolock(mu->url);
1752
1753                         debug(D_REGISTRY, "Registry: freeing machine url");
1754                         free(mu);
1755                 }
1756
1757                 debug(D_REGISTRY, "Registry: deleting machine '%s' from machines registry", m->guid);
1758                 dictionary_del(registry.machines, m->guid);
1759
1760                 debug(D_REGISTRY, "Registry: destroying URL dictionary of machine '%s'", m->guid);
1761                 dictionary_destroy(m->urls);
1762
1763                 debug(D_REGISTRY, "Registry: freeing machine '%s'", m->guid);
1764                 free(m);
1765         }
1766
1767         // and free the memory of remaining dictionary structures
1768
1769         debug(D_REGISTRY, "Registry: destroying persons dictionary");
1770         dictionary_destroy(registry.persons);
1771
1772         debug(D_REGISTRY, "Registry: destroying machines dictionary");
1773         dictionary_destroy(registry.machines);
1774
1775         debug(D_REGISTRY, "Registry: destroying urls dictionary");
1776         dictionary_destroy(registry.urls);
1777 }
1778
1779 // ----------------------------------------------------------------------------
1780 // STATISTICS
1781
1782 void registry_statistics(void) {
1783         if(!registry.enabled) return;
1784
1785         static RRDSET *sts = NULL, *stc = NULL, *stm = NULL;
1786
1787         if(!sts) sts = rrdset_find("netdata.registry_sessions");
1788         if(!sts) {
1789                 sts = rrdset_create("netdata", "registry_sessions", NULL, "registry", NULL, "NetData Registry Sessions", "session", 131000, rrd_update_every, RRDSET_TYPE_LINE);
1790
1791                 rrddim_add(sts, "sessions",  NULL,  1, 1, RRDDIM_ABSOLUTE);
1792         }
1793         else rrdset_next(sts);
1794
1795         rrddim_set(sts, "sessions", registry.usages_count);
1796         rrdset_done(sts);
1797
1798         // ------------------------------------------------------------------------
1799
1800         if(!stc) stc = rrdset_find("netdata.registry_entries");
1801         if(!stc) {
1802                 stc = rrdset_create("netdata", "registry_entries", NULL, "registry", NULL, "NetData Registry Entries", "entries", 131100, rrd_update_every, RRDSET_TYPE_LINE);
1803
1804                 rrddim_add(stc, "persons",        NULL,  1, 1, RRDDIM_ABSOLUTE);
1805                 rrddim_add(stc, "machines",       NULL,  1, 1, RRDDIM_ABSOLUTE);
1806                 rrddim_add(stc, "urls",           NULL,  1, 1, RRDDIM_ABSOLUTE);
1807                 rrddim_add(stc, "persons_urls",   NULL,  1, 1, RRDDIM_ABSOLUTE);
1808                 rrddim_add(stc, "machines_urls",  NULL,  1, 1, RRDDIM_ABSOLUTE);
1809         }
1810         else rrdset_next(stc);
1811
1812         rrddim_set(stc, "persons",       registry.persons_count);
1813         rrddim_set(stc, "machines",      registry.machines_count);
1814         rrddim_set(stc, "urls",          registry.urls_count);
1815         rrddim_set(stc, "persons_urls",  registry.persons_urls_count);
1816         rrddim_set(stc, "machines_urls", registry.machines_urls_count);
1817         rrdset_done(stc);
1818
1819         // ------------------------------------------------------------------------
1820
1821         if(!stm) stm = rrdset_find("netdata.registry_mem");
1822         if(!stm) {
1823                 stm = rrdset_create("netdata", "registry_mem", NULL, "registry", NULL, "NetData Registry Memory", "KB", 131300, rrd_update_every, RRDSET_TYPE_STACKED);
1824
1825                 rrddim_add(stm, "persons",        NULL,  1, 1024, RRDDIM_ABSOLUTE);
1826                 rrddim_add(stm, "machines",       NULL,  1, 1024, RRDDIM_ABSOLUTE);
1827                 rrddim_add(stm, "urls",           NULL,  1, 1024, RRDDIM_ABSOLUTE);
1828                 rrddim_add(stm, "persons_urls",   NULL,  1, 1024, RRDDIM_ABSOLUTE);
1829                 rrddim_add(stm, "machines_urls",  NULL,  1, 1024, RRDDIM_ABSOLUTE);
1830         }
1831         else rrdset_next(stm);
1832
1833         rrddim_set(stm, "persons",       registry.persons_memory + registry.persons_count * sizeof(NAME_VALUE) + sizeof(DICTIONARY));
1834         rrddim_set(stm, "machines",      registry.machines_memory + registry.machines_count * sizeof(NAME_VALUE) + sizeof(DICTIONARY));
1835         rrddim_set(stm, "urls",          registry.urls_memory + registry.urls_count * sizeof(NAME_VALUE) + sizeof(DICTIONARY));
1836         rrddim_set(stm, "persons_urls",  registry.persons_urls_memory + registry.persons_count * sizeof(DICTIONARY) + registry.persons_urls_count * sizeof(NAME_VALUE));
1837         rrddim_set(stm, "machines_urls", registry.machines_urls_memory + registry.machines_count * sizeof(DICTIONARY) + registry.machines_urls_count * sizeof(NAME_VALUE));
1838         rrdset_done(stm);
1839 }
1840
1841
1842 #ifdef REGISTRY_STANDALONE_TESTS
1843
1844 // ----------------------------------------------------------------------------
1845 // TESTS
1846
1847 int test1(int argc, char **argv) {
1848
1849         void print_stats(uint32_t requests, unsigned long long start, unsigned long long end) {
1850                 fprintf(stderr, " > SPEED: %u requests served in %0.2f seconds ( >>> %llu per second <<< )\n",
1851                                 requests, (end-start) / 1000000.0, (unsigned long long)requests * 1000000ULL / (end-start));
1852
1853                 fprintf(stderr, " > DB   : persons %llu, machines %llu, unique URLs %llu, accesses %llu, URLs: for persons %llu, for machines %llu\n",
1854                                 registry.persons_count, registry.machines_count, registry.urls_count, registry.usages_count,
1855                                 registry.persons_urls_count, registry.machines_urls_count);
1856         }
1857
1858         (void) argc;
1859         (void) argv;
1860
1861         uint32_t u, users = 1000000;
1862         uint32_t m, machines = 200000;
1863         uint32_t machines2 = machines * 2;
1864
1865         char **users_guids = malloc(users * sizeof(char *));
1866         char **machines_guids = malloc(machines2 * sizeof(char *));
1867         char **machines_urls = malloc(machines2 * sizeof(char *));
1868         unsigned long long start;
1869
1870         registry_init();
1871
1872         fprintf(stderr, "Generating %u machine guids\n", machines2);
1873         for(m = 0; m < machines2 ;m++) {
1874                 uuid_t uuid;
1875                 machines_guids[m] = malloc(36+1);
1876                 uuid_generate(uuid);
1877                 uuid_unparse(uuid, machines_guids[m]);
1878
1879                 char buf[FILENAME_MAX + 1];
1880                 snprintf(buf, FILENAME_MAX, "http://%u.netdata.rocks/", m+1);
1881                 machines_urls[m] = strdup(buf);
1882
1883                 // fprintf(stderr, "\tmachine %u: '%s', url: '%s'\n", m + 1, machines_guids[m], machines_urls[m]);
1884         }
1885
1886         start = timems();
1887         fprintf(stderr, "\nGenerating %u users accessing %u machines\n", users, machines);
1888         m = 0;
1889         time_t now = time(NULL);
1890         for(u = 0; u < users ; u++) {
1891                 if(++m == machines) m = 0;
1892
1893                 PERSON *p = registry_request_access(NULL, machines_guids[m], machines_urls[m], "test", now);
1894                 users_guids[u] = p->guid;
1895         }
1896         print_stats(u, start, timems());
1897
1898         start = timems();
1899         fprintf(stderr, "\nAll %u users accessing again the same %u servers\n", users, machines);
1900         m = 0;
1901         now = time(NULL);
1902         for(u = 0; u < users ; u++) {
1903                 if(++m == machines) m = 0;
1904
1905                 PERSON *p = registry_request_access(users_guids[u], machines_guids[m], machines_urls[m], "test", now);
1906
1907                 if(p->guid != users_guids[u])
1908                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[u], p->guid);
1909         }
1910         print_stats(u, start, timems());
1911
1912         start = timems();
1913         fprintf(stderr, "\nAll %u users accessing a new server, out of the %u servers\n", users, machines);
1914         m = 1;
1915         now = time(NULL);
1916         for(u = 0; u < users ; u++) {
1917                 if(++m == machines) m = 0;
1918
1919                 PERSON *p = registry_request_access(users_guids[u], machines_guids[m], machines_urls[m], "test", now);
1920
1921                 if(p->guid != users_guids[u])
1922                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[u], p->guid);
1923         }
1924         print_stats(u, start, timems());
1925
1926         start = timems();
1927         fprintf(stderr, "\n%u random users accessing a random server, out of the %u servers\n", users, machines);
1928         now = time(NULL);
1929         for(u = 0; u < users ; u++) {
1930                 uint32_t tu = random() * users / RAND_MAX;
1931                 uint32_t tm = random() * machines / RAND_MAX;
1932
1933                 PERSON *p = registry_request_access(users_guids[tu], machines_guids[tm], machines_urls[tm], "test", now);
1934
1935                 if(p->guid != users_guids[tu])
1936                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[tu], p->guid);
1937         }
1938         print_stats(u, start, timems());
1939
1940         start = timems();
1941         fprintf(stderr, "\n%u random users accessing a random server, out of %u servers\n", users, machines2);
1942         now = time(NULL);
1943         for(u = 0; u < users ; u++) {
1944                 uint32_t tu = random() * users / RAND_MAX;
1945                 uint32_t tm = random() * machines2 / RAND_MAX;
1946
1947                 PERSON *p = registry_request_access(users_guids[tu], machines_guids[tm], machines_urls[tm], "test", now);
1948
1949                 if(p->guid != users_guids[tu])
1950                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[tu], p->guid);
1951         }
1952         print_stats(u, start, timems());
1953
1954         for(m = 0; m < 10; m++) {
1955                 start = timems();
1956                 fprintf(stderr,
1957                                 "\n%u random user accesses to a random server, out of %u servers,\n > using 1/10000 with a random url, 1/1000 with a mismatched url\n",
1958                                 users * 2, machines2);
1959                 now = time(NULL);
1960                 for (u = 0; u < users * 2; u++) {
1961                         uint32_t tu = random() * users / RAND_MAX;
1962                         uint32_t tm = random() * machines2 / RAND_MAX;
1963
1964                         char *url = machines_urls[tm];
1965                         char buf[FILENAME_MAX + 1];
1966                         if (random() % 10000 == 1234) {
1967                                 snprintf(buf, FILENAME_MAX, "http://random.%ld.netdata.rocks/", random());
1968                                 url = buf;
1969                         }
1970                         else if (random() % 1000 == 123)
1971                                 url = machines_urls[random() * machines2 / RAND_MAX];
1972
1973                         PERSON *p = registry_request_access(users_guids[tu], machines_guids[tm], url, "test", now);
1974
1975                         if (p->guid != users_guids[tu])
1976                                 fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[tu], p->guid);
1977                 }
1978                 print_stats(u, start, timems());
1979         }
1980
1981         fprintf(stderr, "\n\nSAVE\n");
1982         start = timems();
1983         registry_save();
1984         print_stats(registry.persons_count, start, timems());
1985
1986         fprintf(stderr, "\n\nCLEANUP\n");
1987         start = timems();
1988         registry_free();
1989         print_stats(registry.persons_count, start, timems());
1990         return 0;
1991 }
1992
1993 // ----------------------------------------------------------------------------
1994 // TESTING
1995
1996 int main(int argc, char **argv) {
1997         // debug_flags = 0xFFFFFFFF;
1998         // test1(argc, argv);
1999         // exit(0);
2000
2001         (void)argc;
2002         (void)argv;
2003
2004
2005         PERSON *p1, *p2;
2006
2007         fprintf(stderr, "\n\nINITIALIZATION\n");
2008
2009         registry_init();
2010
2011         int i = 2;
2012
2013         fprintf(stderr, "\n\nADDING ENTRY\n");
2014         p1 = registry_request_access("2c95abd0-1542-11e6-8c66-00508db7e9c9", "7c173980-145c-11e6-b86f-00508db7e9c1", "http://localhost:19999/", "test", time(NULL));
2015
2016         if(0)
2017         while(i--) {
2018 #ifdef REGISTRY_STDOUT_DUMP
2019                 fprintf(stderr, "\n\nADDING ENTRY\n");
2020 #endif /* REGISTRY_STDOUT_DUMP */
2021                 p1 = registry_request_access(NULL, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://localhost:19999/", "test", time(NULL));
2022
2023 #ifdef REGISTRY_STDOUT_DUMP
2024                 fprintf(stderr, "\n\nADDING ANOTHER URL\n");
2025 #endif /* REGISTRY_STDOUT_DUMP */
2026                 p1 = registry_request_access(p1->guid, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://127.0.0.1:19999/", "test", time(NULL));
2027
2028 #ifdef REGISTRY_STDOUT_DUMP
2029                 fprintf(stderr, "\n\nADDING ANOTHER URL\n");
2030 #endif /* REGISTRY_STDOUT_DUMP */
2031                 p1 = registry_request_access(p1->guid, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://my.server:19999/", "test", time(NULL));
2032
2033 #ifdef REGISTRY_STDOUT_DUMP
2034                 fprintf(stderr, "\n\nADDING ANOTHER MACHINE\n");
2035 #endif /* REGISTRY_STDOUT_DUMP */
2036                 p1 = registry_request_access(p1->guid, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://my.server:19999/", "test", time(NULL));
2037
2038 #ifdef REGISTRY_STDOUT_DUMP
2039                 fprintf(stderr, "\n\nADDING ANOTHER PERSON\n");
2040 #endif /* REGISTRY_STDOUT_DUMP */
2041                 p2 = registry_request_access(NULL, "7c173980-145c-11e6-b86f-00508db7e9c3", "http://localhost:19999/", "test", time(NULL));
2042
2043 #ifdef REGISTRY_STDOUT_DUMP
2044                 fprintf(stderr, "\n\nADDING ANOTHER MACHINE\n");
2045 #endif /* REGISTRY_STDOUT_DUMP */
2046                 p2 = registry_request_access(p2->guid, "7c173980-145c-11e6-b86f-00508db7e9c3", "http://localhost:19999/", "test", time(NULL));
2047         }
2048
2049         fprintf(stderr, "\n\nSAVE\n");
2050         registry_save();
2051
2052         fprintf(stderr, "\n\nCLEANUP\n");
2053         registry_free();
2054         return 0;
2055 }
2056
2057 #endif /* REGISTRY_STANDALONE_TESTS */