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