]> arthur.barton.de Git - netdata.git/blob - src/registry.c
fixed typo
[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
429         debug(D_REGISTRY, "Registry: registry_machine_allocate('%s'): creating dictionary of urls", machine_guid);
430         m->urls = dictionary_create(DICTIONARY_FLAGS);
431
432         m->first_t = m->last_t = when;
433         m->usages = 0;
434
435         registry.machines_memory += sizeof(MACHINE);
436
437         dictionary_set(registry.machines, m->guid, m, sizeof(MACHINE));
438
439         return m;
440 }
441
442 // 1. validate machine GUID
443 // 2. if it is valid, find it or create it and return it
444 // 3. if it is not valid, return NULL
445 static inline MACHINE *registry_machine_get(const char *machine_guid, time_t when) {
446         MACHINE *m = NULL;
447
448         registry_machines_lock();
449
450         if(likely(machine_guid && *machine_guid)) {
451                 // validate it is a GUID
452                 char buf[36 + 1];
453                 if(unlikely(registry_regenerate_guid(machine_guid, buf) == -1))
454                         info("Registry: machine guid '%s' is not a valid guid. Ignoring it.", machine_guid);
455                 else {
456                         machine_guid = buf;
457                         m = registry_machine_find(machine_guid);
458                         if(!m) {
459                                 m = registry_machine_allocate(machine_guid, when);
460                                 registry.machines_count++;
461                         }
462                 }
463         }
464
465         registry_machines_unlock();
466
467         return m;
468 }
469
470
471 // ----------------------------------------------------------------------------
472 // PERSON
473
474 static inline PERSON *registry_person_find(const char *person_guid) {
475         debug(D_REGISTRY, "Registry: registry_person_find('%s')", person_guid);
476         return dictionary_get(registry.persons, person_guid);
477 }
478
479 static inline PERSON_URL *registry_person_url_allocate(PERSON *p, MACHINE *m, URL *u, char *name, size_t namelen, time_t when) {
480         // protection from too big names
481         if(namelen > registry.max_name_length)
482                 namelen = registry.max_name_length;
483
484         debug(D_REGISTRY, "registry_person_url_allocate('%s', '%s', '%s'): allocating %zu bytes", p->guid, m->guid, u->url,
485                   sizeof(PERSON_URL) + namelen);
486
487         PERSON_URL *pu = malloc(sizeof(PERSON_URL) + namelen);
488         if(!pu) fatal("registry_person_url_allocate('%s', '%s', '%s'): cannot allocate %zu bytes.", p->guid, m->guid, u->url, sizeof(PERSON_URL) + namelen);
489
490         // a simple strcpy() should do the job
491         // but I prefer to be safe, since the caller specified urllen
492         strncpy(pu->name, name, namelen);
493         pu->name[namelen] = '\0';
494
495         pu->machine = m;
496         pu->first_t = pu->last_t = when;
497         pu->usages = 1;
498         pu->url = u;
499         pu->flags = REGISTRY_URL_FLAGS_DEFAULT;
500         m->links++;
501
502         registry.persons_urls_memory += sizeof(PERSON_URL) + namelen;
503
504         debug(D_REGISTRY, "registry_person_url_allocate('%s', '%s', '%s'): indexing URL in person", p->guid, m->guid, u->url);
505         dictionary_set(p->urls, u->url, pu, sizeof(PERSON_URL));
506         registry_url_link_nolock(u);
507
508         return pu;
509 }
510
511 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) {
512         // this function is needed to change the name of a PERSON_URL
513
514         debug(D_REGISTRY, "registry_person_url_reallocate('%s', '%s', '%s'): allocating %zu bytes", p->guid, m->guid, u->url,
515                   sizeof(PERSON_URL) + namelen);
516
517         PERSON_URL *tpu = registry_person_url_allocate(p, m, u, name, namelen, when);
518         tpu->first_t = pu->first_t;
519         tpu->last_t = pu->last_t;
520         tpu->usages = pu->usages;
521
522         // ok, these are a hack - since the registry_person_url_allocate() is
523         // adding these, we have to subtract them
524         tpu->machine->links--;
525         registry.persons_urls_memory -= sizeof(PERSON_URL) + strlen(pu->name);
526         registry_url_unlink_nolock(u);
527
528         free(pu);
529
530         return tpu;
531 }
532
533 static inline PERSON *registry_person_allocate(const char *person_guid, time_t when) {
534         PERSON *p = NULL;
535
536         debug(D_REGISTRY, "Registry: registry_person_allocate('%s'): allocating new person, sizeof(PERSON)=%zu", (person_guid)?person_guid:"", sizeof(PERSON));
537
538         p = malloc(sizeof(PERSON));
539         if(!p) fatal("Registry: cannot allocate memory for new person.");
540
541         if(!person_guid) {
542                 for (; ;) {
543                         uuid_t uuid;
544                         if (uuid_generate_time_safe(uuid) == -1)
545                                 info("Registry: uuid_generate_time_safe() reports UUID generation is not safe for uniqueness.");
546
547                         uuid_unparse_lower(uuid, p->guid);
548
549                         debug(D_REGISTRY, "Registry: Checking if the generated person guid '%s' is unique", p->guid);
550                         if (!dictionary_get(registry.persons, p->guid)) {
551                                 debug(D_REGISTRY, "Registry: generated person guid '%s' is unique", p->guid);
552                                 break;
553                         }
554                         else
555                                 info("Registry: generated person guid '%s' found in the registry. Retrying...", p->guid);
556                 }
557         }
558         else {
559                 strncpy(p->guid, person_guid, 36);
560                 p->guid[36] = '\0';
561         }
562
563         debug(D_REGISTRY, "Registry: registry_person_allocate('%s'): creating dictionary of urls", p->guid);
564         p->urls = dictionary_create(DICTIONARY_FLAGS);
565
566         p->first_t = p->last_t = when;
567         p->usages = 0;
568
569         registry.persons_memory += sizeof(PERSON);
570
571         dictionary_set(registry.persons, p->guid, p, sizeof(PERSON));
572         return p;
573 }
574
575
576 // 1. validate person GUID
577 // 2. if it is valid, find it
578 // 3. if it is not valid, create a new one
579 // 4. return it
580 static inline PERSON *registry_person_get(const char *person_guid, time_t when) {
581         PERSON *p = NULL;
582
583         registry_persons_lock();
584
585         if(person_guid && *person_guid) {
586                 char buf[36 + 1];
587                 // validate it is a GUID
588                 if(unlikely(registry_regenerate_guid(person_guid, buf) == -1))
589                         info("Registry: person guid '%s' is not a valid guid. Ignoring it.", person_guid);
590                 else {
591                         person_guid = buf;
592                         p = registry_person_find(person_guid);
593                         if(!p) person_guid = NULL;
594                 }
595         }
596
597         if(!p) {
598                 p = registry_person_allocate(NULL, when);
599                 registry.persons_count++;
600         }
601
602         registry_persons_unlock();
603
604         return p;
605 }
606
607 // ----------------------------------------------------------------------------
608 // LINKING OF OBJECTS
609
610 static inline PERSON_URL *registry_person_link_to_url(PERSON *p, MACHINE *m, URL *u, char *name, size_t namelen, time_t when) {
611         debug(D_REGISTRY, "registry_person_link_to_url('%s', '%s', '%s'): searching for URL in person", p->guid, m->guid, u->url);
612
613         registry_person_urls_lock(p);
614
615         PERSON_URL *pu = dictionary_get(p->urls, u->url);
616         if(!pu) {
617                 debug(D_REGISTRY, "registry_person_link_to_url('%s', '%s', '%s'): not found", p->guid, m->guid, u->url);
618                 pu = registry_person_url_allocate(p, m, u, name, namelen, when);
619                 registry.persons_urls_count++;
620         }
621         else {
622                 debug(D_REGISTRY, "registry_person_link_to_url('%s', '%s', '%s'): found", p->guid, m->guid, u->url);
623                 pu->usages++;
624
625                 if(pu->machine != m) {
626                         MACHINE_URL *mu = dictionary_get(pu->machine->urls, u->url);
627                         if(mu) {
628                                 info("registry_person_link_to_url('%s', '%s', '%s'): URL switched machines (old was '%s') - expiring it from previous machine.",
629                                          p->guid, m->guid, u->url, pu->machine->guid);
630                                 mu->flags |= REGISTRY_URL_FLAGS_EXPIRED;
631                         }
632                         else {
633                                 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.",
634                                          p->guid, m->guid, u->url, pu->machine->guid);
635                         }
636
637                         pu->machine->links--;
638                         pu->machine = m;
639                 }
640
641                 if(strcmp(pu->name, name)) {
642                         // the name of the PERSON_URL has changed !
643                         pu = registry_person_url_reallocate(p, m, u, name, namelen, when, pu);
644                 }
645         }
646
647         p->usages++;
648         p->last_t = when;
649
650         if(pu->flags & REGISTRY_URL_FLAGS_EXPIRED) {
651                 info("registry_person_link_to_url('%s', '%s', '%s'): accessing an expired URL. Re-enabling URL.", p->guid, m->guid, u->url);
652                 pu->flags &= ~REGISTRY_URL_FLAGS_EXPIRED;
653         }
654
655         registry_person_urls_unlock(p);
656
657         return pu;
658 }
659
660 static inline MACHINE_URL *registry_machine_link_to_url(PERSON *p, MACHINE *m, URL *u, time_t when) {
661         debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): searching for URL in machine", p->guid, m->guid, u->url);
662
663         registry_machine_urls_lock(m);
664
665         MACHINE_URL *mu = dictionary_get(m->urls, u->url);
666         if(!mu) {
667                 debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): not found", p->guid, m->guid, u->url);
668                 mu = registry_machine_url_allocate(m, u, when);
669                 registry.machines_urls_count++;
670         }
671         else {
672                 debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): found", p->guid, m->guid, u->url);
673                 mu->usages++;
674         }
675
676         //debug(D_REGISTRY, "registry_machine_link_to_url('%s', '%s', '%s'): indexing person in machine", p->guid, m->guid, u->url);
677         //dictionary_set(mu->persons, p->guid, p, sizeof(PERSON));
678
679         m->usages++;
680         m->last_t = when;
681
682         if(mu->flags & REGISTRY_URL_FLAGS_EXPIRED) {
683                 info("registry_machine_link_to_url('%s', '%s', '%s'): accessing an expired URL.", p->guid, m->guid, u->url);
684                 mu->flags &= ~REGISTRY_URL_FLAGS_EXPIRED;
685         }
686
687         registry_machine_urls_unlock(m);
688
689         return mu;
690 }
691
692 // ----------------------------------------------------------------------------
693 // REGISTRY LOG LOAD/SAVE
694
695 static inline int registry_should_save_db(void) {
696         debug(D_REGISTRY, "log entries %llu, max %llu", registry.log_count, registry.save_registry_every_entries);
697         return registry.log_count > registry.save_registry_every_entries;
698 }
699
700 static inline void registry_log(const char action, PERSON *p, MACHINE *m, URL *u, char *name) {
701         if(likely(registry.log_fp)) {
702                 // we lock only if the file is open
703                 // to allow replaying the log at registry_log_load()
704                 registry_log_lock();
705
706                 if(unlikely(fprintf(registry.log_fp, "%c\t%08x\t%s\t%s\t%s\t%s\n",
707                                 action,
708                                 p->last_t,
709                                 p->guid,
710                                 m->guid,
711                                 name,
712                                 u->url) < 0))
713                         error("Registry: failed to save log. Registry data may be lost in case of abnormal restart.");
714
715                 // we increase the counter even on failures
716                 // so that the registry will be saved periodically
717                 registry.log_count++;
718
719                 registry_log_unlock();
720
721                 // this must be outside the log_lock(), or a deadlock will happen.
722                 // registry_save() checks the same inside the log_lock, so only
723                 // one thread will save the db
724                 if(unlikely(registry_should_save_db()))
725                         registry_save();
726         }
727 }
728
729 static inline int registry_log_open_nolock(void) {
730         if(registry.log_fp)
731                 fclose(registry.log_fp);
732
733         registry.log_fp = fopen(registry.log_filename, "a");
734
735         if(registry.log_fp) {
736                 if (setvbuf(registry.log_fp, NULL, _IOLBF, 0) != 0)
737                         error("Cannot set line buffering on registry log file.");
738                 return 0;
739         }
740
741         error("Cannot open registry log file '%s'. Registry data will be lost in case of netdata or server crash.", registry.log_filename);
742         return -1;
743 }
744
745 static inline void registry_log_close_nolock(void) {
746         if(registry.log_fp) {
747                 fclose(registry.log_fp);
748                 registry.log_fp = NULL;
749         }
750 }
751
752 static inline void registry_log_recreate_nolock(void) {
753         if(registry.log_fp != NULL) {
754                 registry_log_close_nolock();
755
756                 // open it with truncate
757                 registry.log_fp = fopen(registry.log_filename, "w");
758                 if(registry.log_fp) fclose(registry.log_fp);
759                 else error("Cannot truncate registry log '%s'", registry.log_filename);
760
761                 registry.log_fp = NULL;
762
763                 registry_log_open_nolock();
764         }
765 }
766
767 int registry_log_load(void) {
768         char *s, buf[4096 + 1];
769         size_t line = -1;
770
771         // closing the log is required here
772         // otherwise we will append to it the values we read
773         registry_log_close_nolock();
774
775         debug(D_REGISTRY, "Registry: loading active db from: %s", registry.log_filename);
776         FILE *fp = fopen(registry.log_filename, "r");
777         if(!fp)
778                 error("Registry: cannot open registry file: %s", registry.log_filename);
779         else {
780                 line = 0;
781                 size_t len = 0;
782                 while ((s = fgets_trim_len(buf, 4096, fp, &len))) {
783                         line++;
784
785                         switch (s[0]) {
786                                 case 'A': // accesses
787                                 case 'D': // deletes
788
789                                         // verify it is valid
790                                         if (unlikely(len < 85 || s[1] != '\t' || s[10] != '\t' || s[47] != '\t' || s[84] != '\t')) {
791                                                 error("Registry: log line %u is wrong (len = %zu).", line, len);
792                                                 continue;
793                                         }
794                                         s[1] = s[10] = s[47] = s[84] = '\0';
795
796                                         // get the variables
797                                         time_t when = strtoul(&s[2], NULL, 16);
798                                         char *person_guid = &s[11];
799                                         char *machine_guid = &s[48];
800                                         char *name = &s[85];
801
802                                         // skip the name to find the url
803                                         char *url = name;
804                                         while(*url && *url != '\t') url++;
805                                         if(!*url) {
806                                                 error("Registry: log line %u does not have a url.", line);
807                                                 continue;
808                                         }
809                                         *url++ = '\0';
810
811                                         // make sure the person exists
812                                         // without this, a new person guid will be created
813                                         PERSON *p = registry_person_find(person_guid);
814                                         if(!p) p = registry_person_allocate(person_guid, when);
815
816                                         if(s[0] == 'A')
817                                                 registry_request_access(p->guid, machine_guid, url, name, when);
818                                         else
819                                                 registry_request_delete(p->guid, machine_guid, url, name, when);
820
821                                         break;
822
823                                 default:
824                                         error("Registry: ignoring line %zu of filename '%s': %s.", line, registry.log_filename, s);
825                                         break;
826                         }
827                 }
828         }
829
830         // open the log again
831         registry_log_open_nolock();
832
833         return line;
834 }
835
836
837 // ----------------------------------------------------------------------------
838 // REGISTRY REQUESTS
839
840 PERSON *registry_request_access(char *person_guid, char *machine_guid, char *url, char *name, time_t when) {
841         debug(D_REGISTRY, "registry_request_access('%s', '%s', '%s'): NEW REQUEST", (person_guid)?person_guid:"", machine_guid, url);
842
843         MACHINE *m = registry_machine_get(machine_guid, when);
844         if(!m) return NULL;
845
846         // make sure the name is valid
847         size_t namelen;
848         name = registry_fix_machine_name(name, &namelen);
849
850         size_t urllen;
851         url = registry_fix_url(url, &urllen);
852
853         URL *u = registry_url_get(url, urllen);
854         PERSON *p = registry_person_get(person_guid, when);
855
856         registry_person_link_to_url(p, m, u, name, namelen, when);
857         registry_machine_link_to_url(p, m, u, when);
858
859         registry_log('A', p, m, u, name);
860
861         registry.usages_count++;
862         return p;
863 }
864
865 // verify the person, the machine and the URL exist in our DB
866 PERSON_URL *registry_verify_request(char *person_guid, char *machine_guid, char *url, PERSON **pp, MACHINE **mm) {
867         char pbuf[36 + 1], mbuf[36 + 1];
868
869         if(!person_guid || !*person_guid || !machine_guid || !*machine_guid || !url || !*url) {
870                 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");
871                 return NULL;
872         }
873
874         // normalize the url
875         url = registry_fix_url(url, NULL);
876
877         // make sure the person GUID is valid
878         if(registry_regenerate_guid(person_guid, pbuf) == -1) {
879                 info("Registry Request Verification: invalid person GUID, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
880                 return NULL;
881         }
882         person_guid = pbuf;
883
884         // make sure the machine GUID is valid
885         if(registry_regenerate_guid(machine_guid, mbuf) == -1) {
886                 info("Registry Request Verification: invalid machine GUID, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
887                 return NULL;
888         }
889         machine_guid = mbuf;
890
891         // make sure the machine exists
892         MACHINE *m = registry_machine_find(machine_guid);
893         if(!m) {
894                 info("Registry Request Verification: machine not found, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
895                 return NULL;
896         }
897         if(mm) *mm = m;
898
899         // make sure the person exist
900         PERSON *p = registry_person_find(person_guid);
901         if(!p) {
902                 info("Registry Request Verification: person not found, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
903                 return NULL;
904         }
905         if(pp) *pp = p;
906
907         PERSON_URL *pu = dictionary_get(p->urls, url);
908         if(!pu) {
909                 info("Registry Request Verification: URL not found for person, person: '%s', machine '%s', url '%s'", person_guid, machine_guid, url);
910                 return NULL;
911         }
912         return pu;
913 }
914
915 PERSON *registry_request_delete(char *person_guid, char *machine_guid, char *url, char *delete_url, time_t when) {
916         (void)when;
917
918         PERSON *p = NULL;
919         MACHINE *m = NULL;
920         PERSON_URL *pu = registry_verify_request(person_guid, machine_guid, url, &p, &m);
921         if(!pu || !p || !m) return NULL;
922
923         // normalize the url
924         delete_url = registry_fix_url(delete_url, NULL);
925
926         // make sure the user is not deleting the url it uses
927         if(!strcmp(delete_url, pu->url->url)) {
928                 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);
929                 return NULL;
930         }
931
932         registry_person_urls_lock(p);
933
934         PERSON_URL *dpu = dictionary_get(p->urls, delete_url);
935         if(!dpu) {
936                 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);
937                 registry_person_urls_unlock(p);
938                 return NULL;
939         }
940
941         registry_log('D', p, m, pu->url, dpu->url->url);
942
943         dictionary_del(p->urls, dpu->url->url);
944         registry_url_unlink_nolock(dpu->url);
945         free(dpu);
946
947         registry_person_urls_unlock(p);
948         return p;
949 }
950
951
952 // a structure to pass to the dictionary_get_all() callback handler
953 struct machine_request_callback_data {
954         MACHINE *find_this_machine;
955         PERSON_URL *result;
956 };
957
958 // the callback function
959 // this will be run for every PERSON_URL of this PERSON
960 int machine_request_callback(void *entry, void *data) {
961         PERSON_URL *mypu = (PERSON_URL *)entry;
962         struct machine_request_callback_data *myrdata = (struct machine_request_callback_data *)data;
963
964         if(mypu->machine == myrdata->find_this_machine) {
965                 myrdata->result = mypu;
966                 return -1; // this will also stop the walk through
967         }
968
969         return 0; // continue
970 }
971
972 MACHINE *registry_request_machine(char *person_guid, char *machine_guid, char *url, char *request_machine, time_t when) {
973         (void)when;
974
975         char mbuf[36 + 1];
976
977         PERSON *p = NULL;
978         MACHINE *m = NULL;
979         PERSON_URL *pu = registry_verify_request(person_guid, machine_guid, url, &p, &m);
980         if(!pu || !p || !m) return NULL;
981
982         // make sure the machine GUID is valid
983         if(registry_regenerate_guid(request_machine, mbuf) == -1) {
984                 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);
985                 return NULL;
986         }
987         request_machine = mbuf;
988
989         // make sure the machine exists
990         m = registry_machine_find(request_machine);
991         if(!m) {
992                 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);
993                 return NULL;
994         }
995
996         // Verify the user has in the past accessed this machine
997         // We will walk through the PERSON_URLs to find the machine
998         // linking to our machine
999
1000         // a structure to pass to the dictionary_get_all() callback handler
1001         struct machine_request_callback_data rdata = { m, NULL };
1002
1003         // request a walk through on the dictionary
1004         // no need for locking here, the underlying dictionary has its own
1005         dictionary_get_all(p->urls, machine_request_callback, &rdata);
1006
1007         if(rdata.result)
1008                 return m;
1009
1010         return NULL;
1011 }
1012
1013
1014 // ----------------------------------------------------------------------------
1015 // REGISTRY JSON generation
1016
1017 #ifndef REGISTRY_STANDALONE_TESTS
1018
1019 static inline void registry_set_person_cookie(struct web_client *w, PERSON *p) {
1020         char edate[100];
1021         time_t et = time(NULL) + registry.persons_expiration;
1022         struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1023         strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1024
1025         if(registry.registry_domain && registry.registry_domain[0])
1026                 snprintf(w->cookie, COOKIE_MAX, NETDATA_REGISTRY_COOKIE_NAME "=%s; Domain=%s; Expires=%s", p->guid, registry.registry_domain, edate);
1027         else
1028                 snprintf(w->cookie, COOKIE_MAX, NETDATA_REGISTRY_COOKIE_NAME "=%s; Expires=%s", p->guid, edate);
1029
1030         w->cookie[COOKIE_MAX] = '\0';
1031 }
1032
1033
1034 static inline void registry_json_header(struct web_client *w, int status) {
1035         w->response.data->contenttype = CT_APPLICATION_JSON;
1036         buffer_flush(w->response.data);
1037         buffer_sprintf(w->response.data, "{\n\t\"success\": %s,\n\t\"hostname\": \"%s\",\n\t\"machine_guid\": \"%s\"",
1038                                    status?"true":"false", registry.hostname, registry.machine_guid);
1039 }
1040
1041 static inline void registry_json_footer(struct web_client *w) {
1042         buffer_strcat(w->response.data, "\n}\n");
1043 }
1044
1045 int registry_json_redirect(struct web_client *w) {
1046         registry_json_header(w, 0);
1047
1048         buffer_sprintf(w->response.data, ",\n\t\"registry\": \"%s\"",
1049                                    registry.registry_to_announce);
1050
1051         registry_json_footer(w);
1052         return 200;
1053 }
1054
1055 // structure used be the callbacks below
1056 struct registry_json_walk_person_urls_callback {
1057         PERSON *p;
1058         MACHINE *m;
1059         struct web_client *w;
1060         int count;
1061 };
1062
1063 // callback for rendering PERSON_URLs
1064 static inline int registry_json_person_url_callback(void *entry, void *data) {
1065         PERSON_URL *pu = (PERSON_URL *)entry;
1066         struct registry_json_walk_person_urls_callback *c = (struct registry_json_walk_person_urls_callback *)data;
1067         struct web_client *w = c->w;
1068
1069         if(unlikely(c->count++))
1070                 buffer_strcat(w->response.data, ",");
1071
1072         buffer_sprintf(w->response.data, "\n\t\t[ \"%s\", \"%s\", %u000, %u, \"%s\" ]",
1073                                    pu->machine->guid, pu->url->url, pu->last_t, pu->usages, pu->name);
1074
1075         return 1;
1076 }
1077
1078 // callback for rendering MACHINE_URLs
1079 static inline int registry_json_machine_url_callback(void *entry, void *data) {
1080         MACHINE_URL *mu = (MACHINE_URL *)entry;
1081         struct registry_json_walk_person_urls_callback *c = (struct registry_json_walk_person_urls_callback *)data;
1082         struct web_client *w = c->w;
1083         MACHINE *m = c->m;
1084
1085         if(unlikely(c->count++))
1086                 buffer_strcat(w->response.data, ",");
1087
1088         buffer_sprintf(w->response.data, "\n\t\t[ \"%s\", \"%s\", %u000, %u ]",
1089                                    m->guid, mu->url->url, mu->last_t, mu->usages);
1090
1091         return 1;
1092 }
1093
1094
1095 // the main method for registering an access
1096 int registry_request_access_json(struct web_client *w, char *person_guid, char *machine_guid, char *url, char *name, time_t when) {
1097         if(!registry.enabled)
1098                 return registry_json_redirect(w);
1099
1100         PERSON *p = registry_request_access(person_guid, machine_guid, url, name, when);
1101         if(!p) {
1102                 registry_json_header(w, 0);
1103                 registry_json_footer(w);
1104                 return 400;
1105         }
1106
1107         // set the cookie
1108         registry_set_person_cookie(w, p);
1109
1110         // generate the response
1111         registry_json_header(w, 1);
1112
1113         buffer_strcat(w->response.data, ",\n\t\"urls\": [");
1114         struct registry_json_walk_person_urls_callback c = { p, NULL, w, 0 };
1115         dictionary_get_all(p->urls, registry_json_person_url_callback, &c);
1116         buffer_strcat(w->response.data, "\n\t]\n");
1117
1118         registry_json_footer(w);
1119         return 200;
1120 }
1121
1122 // the main method for deleting a URL from a person
1123 int registry_request_delete_json(struct web_client *w, char *person_guid, char *machine_guid, char *url, char *delete_url, time_t when) {
1124         if(!registry.enabled)
1125                 return registry_json_redirect(w);
1126
1127         PERSON *p = registry_request_delete(person_guid, machine_guid, url, delete_url, when);
1128         if(!p) {
1129                 registry_json_header(w, 0);
1130                 registry_json_footer(w);
1131                 return 400;
1132         }
1133
1134         // generate the response
1135         registry_json_header(w, 1);
1136         registry_json_footer(w);
1137         return 200;
1138 }
1139
1140 // the main method for searching the URLs of a netdata
1141 int registry_request_search_json(struct web_client *w, char *person_guid, char *machine_guid, char *url, char *request_machine, time_t when) {
1142         if(!registry.enabled)
1143                 return registry_json_redirect(w);
1144
1145         MACHINE *m = registry_request_machine(person_guid, machine_guid, url, request_machine, when);
1146         if(!m) {
1147                 registry_json_header(w, 0);
1148                 registry_json_footer(w);
1149                 return 400;
1150         }
1151
1152         registry_json_header(w, 1);
1153
1154         buffer_strcat(w->response.data, ",\n\t\"urls\": [");
1155         struct registry_json_walk_person_urls_callback c = { NULL, m, w, 0 };
1156         dictionary_get_all(m->urls, registry_json_machine_url_callback, &c);
1157         buffer_strcat(w->response.data, "\n\t]\n");
1158
1159         registry_json_footer(w);
1160         return 200;
1161 }
1162
1163 #endif /* ! REGISTRY_STANDALONE_TESTS */
1164
1165
1166 // ----------------------------------------------------------------------------
1167 // REGISTRY THIS MACHINE UNIQUE ID
1168
1169 char *registry_get_this_machine_guid(void) {
1170         if(likely(registry.machine_guid[0]))
1171                 return registry.machine_guid;
1172
1173         // read it from disk
1174         int fd = open(registry.machine_guid_filename, O_RDONLY);
1175         if(fd != -1) {
1176                 char buf[36 + 1];
1177                 if(read(fd, buf, 36) != 36)
1178                         error("Failed to read machine GUID from '%s'", registry.machine_guid_filename);
1179                 else {
1180                         buf[36] = '\0';
1181                         if(registry_regenerate_guid(buf, registry.machine_guid) == -1) {
1182                                 error("Failed to validate machine GUID '%s' from '%s'. Ignoring it - this might mean this netdata will appear as duplicate in the registry.",
1183                                           buf, registry.machine_guid_filename);
1184
1185                                 registry.machine_guid[0] = '\0';
1186                         }
1187                 }
1188                 close(fd);
1189         }
1190
1191         // generate a new one?
1192         if(!registry.machine_guid[0]) {
1193                 int count = 10, ret = 0;
1194                 uuid_t uuid;
1195
1196                 // for some reason it reports unsafe generation the first time
1197                 while(count-- && (ret = uuid_generate_time_safe(uuid)) == -1) ;
1198                 uuid_unparse_lower(uuid, registry.machine_guid);
1199                 registry.machine_guid[36] = '\0';
1200
1201                 if(ret == -1)
1202                         info("Warning: generated machine GUID '%s' was not generated using a safe method.", registry.machine_guid);
1203
1204                 // save it
1205                 fd = open(registry.machine_guid_filename, O_WRONLY|O_CREAT|O_TRUNC, 444);
1206                 if(fd == -1)
1207                         fatal("Cannot create unique machine id file '%s'. Please fix this.", registry.machine_guid_filename);
1208
1209                 if(write(fd, registry.machine_guid, 36) != 36)
1210                         fatal("Cannot write the unique machine id file '%s'. Please fix this.", registry.machine_guid_filename);
1211
1212                 close(fd);
1213         }
1214
1215         return registry.machine_guid;
1216 }
1217
1218
1219 // ----------------------------------------------------------------------------
1220 // REGISTRY LOAD/SAVE
1221
1222 int registry_machine_save_url(void *entry, void *file) {
1223         MACHINE_URL *mu = entry;
1224         FILE *fp = file;
1225
1226         debug(D_REGISTRY, "Registry: registry_machine_save_url('%s')", mu->url->url);
1227
1228         int ret = fprintf(fp, "V\t%08x\t%08x\t%08x\t%02x\t%s\n",
1229                         mu->first_t,
1230                         mu->last_t,
1231                         mu->usages,
1232                         mu->flags,
1233                         mu->url->url
1234         );
1235
1236         // error handling is done at registry_save()
1237
1238         return ret;
1239 }
1240
1241 int registry_machine_save(void *entry, void *file) {
1242         MACHINE *m = entry;
1243         FILE *fp = file;
1244
1245         debug(D_REGISTRY, "Registry: registry_machine_save('%s')", m->guid);
1246
1247         int ret = fprintf(fp, "M\t%08x\t%08x\t%08x\t%s\n",
1248                         m->first_t,
1249                         m->last_t,
1250                         m->usages,
1251                         m->guid
1252         );
1253
1254         if(ret >= 0) {
1255                 int ret2 = dictionary_get_all(m->urls, registry_machine_save_url, fp);
1256                 if(ret2 < 0) return ret2;
1257                 ret += ret2;
1258         }
1259
1260         // error handling is done at registry_save()
1261
1262         return ret;
1263 }
1264
1265 static inline int registry_person_save_url(void *entry, void *file) {
1266         PERSON_URL *pu = entry;
1267         FILE *fp = file;
1268
1269         debug(D_REGISTRY, "Registry: registry_person_save_url('%s')", pu->url->url);
1270
1271         int ret = fprintf(fp, "U\t%08x\t%08x\t%08x\t%02x\t%s\t%s\t%s\n",
1272                         pu->first_t,
1273                         pu->last_t,
1274                         pu->usages,
1275                         pu->flags,
1276                         pu->machine->guid,
1277                         pu->name,
1278                         pu->url->url
1279         );
1280
1281         // error handling is done at registry_save()
1282
1283         return ret;
1284 }
1285
1286 static inline int registry_person_save(void *entry, void *file) {
1287         PERSON *p = entry;
1288         FILE *fp = file;
1289
1290         debug(D_REGISTRY, "Registry: registry_person_save('%s')", p->guid);
1291
1292         int ret = fprintf(fp, "P\t%08x\t%08x\t%08x\t%s\n",
1293                         p->first_t,
1294                         p->last_t,
1295                         p->usages,
1296                         p->guid
1297         );
1298
1299         if(ret >= 0) {
1300                 int ret2 = dictionary_get_all(p->urls, registry_person_save_url, fp);
1301                 if (ret2 < 0) return ret2;
1302                 ret += ret2;
1303         }
1304
1305         // error handling is done at registry_save()
1306
1307         return ret;
1308 }
1309
1310 int registry_save(void) {
1311         if(!registry.enabled) return -1;
1312
1313         // make sure the log is not updated
1314         registry_log_lock();
1315
1316         if(unlikely(!registry_should_save_db())) {
1317                 registry_log_unlock();
1318                 return -2;
1319         }
1320
1321         char tmp_filename[FILENAME_MAX + 1];
1322         char old_filename[FILENAME_MAX + 1];
1323
1324         snprintf(old_filename, FILENAME_MAX, "%s.old", registry.db_filename);
1325         snprintf(tmp_filename, FILENAME_MAX, "%s.tmp", registry.db_filename);
1326
1327         debug(D_REGISTRY, "Registry: Creating file '%s'", tmp_filename);
1328         FILE *fp = fopen(tmp_filename, "w");
1329         if(!fp) {
1330                 error("Registry: Cannot create file: %s", tmp_filename);
1331                 registry_log_unlock();
1332                 return -1;
1333         }
1334
1335         // dictionary_get_all() has its own locking, so this is safe to do
1336
1337         debug(D_REGISTRY, "Saving all machines");
1338         int bytes1 = dictionary_get_all(registry.machines, registry_machine_save, fp);
1339         if(bytes1 < 0) {
1340                 error("Registry: Cannot save registry machines - return value %d", bytes1);
1341                 fclose(fp);
1342                 registry_log_unlock();
1343                 return bytes1;
1344         }
1345         debug(D_REGISTRY, "Registry: saving machines took %d bytes", bytes1);
1346
1347         debug(D_REGISTRY, "Saving all persons");
1348         int bytes2 = dictionary_get_all(registry.persons, registry_person_save, fp);
1349         if(bytes2 < 0) {
1350                 error("Registry: Cannot save registry persons - return value %d", bytes2);
1351                 fclose(fp);
1352                 registry_log_unlock();
1353                 return bytes2;
1354         }
1355         debug(D_REGISTRY, "Registry: saving persons took %d bytes", bytes2);
1356
1357         // save the totals
1358         fprintf(fp, "T\t%016llx\t%016llx\t%016llx\t%016llx\t%016llx\t%016llx\n",
1359                         registry.persons_count,
1360                         registry.machines_count,
1361                         registry.usages_count + 1, // this is required - it is lost on db rotation
1362                         registry.urls_count,
1363                         registry.persons_urls_count,
1364                         registry.machines_urls_count
1365         );
1366
1367         fclose(fp);
1368
1369         errno = 0;
1370
1371         // remove the .old db
1372         debug(D_REGISTRY, "Registry: Removing old db '%s'", old_filename);
1373         if(unlink(old_filename) == -1 && errno != ENOENT)
1374                 error("Registry: cannot remove old registry file '%s'", old_filename);
1375
1376         // rename the db to .old
1377         debug(D_REGISTRY, "Registry: Link current db '%s' to .old: '%s'", registry.db_filename, old_filename);
1378         if(link(registry.db_filename, old_filename) == -1 && errno != ENOENT)
1379                 error("Registry: cannot move file '%s' to '%s'. Saving registry DB failed!", tmp_filename, registry.db_filename);
1380
1381         else {
1382                 // remove the database (it is saved in .old)
1383                 debug(D_REGISTRY, "Registry: removing db '%s'", registry.db_filename);
1384                 if (unlink(registry.db_filename) == -1 && errno != ENOENT)
1385                         error("Registry: cannot remove old registry file '%s'", registry.db_filename);
1386
1387                 // move the .tmp to make it active
1388                 debug(D_REGISTRY, "Registry: linking tmp db '%s' to active db '%s'", tmp_filename, registry.db_filename);
1389                 if (link(tmp_filename, registry.db_filename) == -1) {
1390                         error("Registry: cannot move file '%s' to '%s'. Saving registry DB failed!", tmp_filename,
1391                                   registry.db_filename);
1392
1393                         // move the .old back
1394                         debug(D_REGISTRY, "Registry: linking old db '%s' to active db '%s'", old_filename, registry.db_filename);
1395                         if(link(old_filename, registry.db_filename) == -1)
1396                                 error("Registry: cannot move file '%s' to '%s'. Recovering the old registry DB failed!", old_filename, registry.db_filename);
1397                 }
1398                 else {
1399                         debug(D_REGISTRY, "Registry: removing tmp db '%s'", tmp_filename);
1400                         if(unlink(tmp_filename) == -1)
1401                                 error("Registry: cannot remove tmp registry file '%s'", tmp_filename);
1402
1403                         // it has been moved successfully
1404                         // discard the current registry log
1405                         registry_log_recreate_nolock();
1406
1407                         registry.log_count = 0;
1408                 }
1409         }
1410
1411         // continue operations
1412         registry_log_unlock();
1413
1414         return -1;
1415 }
1416
1417 static inline size_t registry_load(void) {
1418         char *s, buf[4096 + 1];
1419         PERSON *p = NULL;
1420         MACHINE *m = NULL;
1421         URL *u = NULL;
1422         size_t line = 0;
1423
1424         debug(D_REGISTRY, "Registry: loading active db from: '%s'", registry.db_filename);
1425         FILE *fp = fopen(registry.db_filename, "r");
1426         if(!fp) {
1427                 error("Registry: cannot open registry file: '%s'", registry.db_filename);
1428                 return 0;
1429         }
1430
1431         size_t len = 0;
1432         while((s = fgets_trim_len(buf, 4096, fp, &len))) {
1433                 line++;
1434
1435                 debug(D_REGISTRY, "Registry: read line %zu to length %zu: %s", line, len, s);
1436                 switch(*s) {
1437                         case 'T': // totals
1438                                 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')) {
1439                                         error("Registry totals line %u is wrong (len = %zu).", line, len);
1440                                         continue;
1441                                 }
1442                                 registry.persons_count = strtoull(&s[2], NULL, 16);
1443                                 registry.machines_count = strtoull(&s[19], NULL, 16);
1444                                 registry.usages_count = strtoull(&s[36], NULL, 16);
1445                                 registry.urls_count = strtoull(&s[53], NULL, 16);
1446                                 registry.persons_urls_count = strtoull(&s[70], NULL, 16);
1447                                 registry.machines_urls_count = strtoull(&s[87], NULL, 16);
1448                                 break;
1449
1450                         case 'P': // person
1451                                 m = NULL;
1452                                 // verify it is valid
1453                                 if(unlikely(len != 65 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[65] != '\0')) {
1454                                         error("Registry person line %u is wrong (len = %zu).", line, len);
1455                                         continue;
1456                                 }
1457
1458                                 s[1] = s[10] = s[19] = s[28] = '\0';
1459                                 p = registry_person_allocate(&s[29], strtoul(&s[2], NULL, 16));
1460                                 p->last_t = strtoul(&s[11], NULL, 16);
1461                                 p->usages = strtoul(&s[20], NULL, 16);
1462                                 debug(D_REGISTRY, "Registry loaded person '%s', first: %u, last: %u, usages: %u", p->guid, p->first_t, p->last_t, p->usages);
1463                                 break;
1464
1465                         case 'M': // machine
1466                                 p = NULL;
1467                                 // verify it is valid
1468                                 if(unlikely(len != 65 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[65] != '\0')) {
1469                                         error("Registry person line %u is wrong (len = %zu).", line, len);
1470                                         continue;
1471                                 }
1472
1473                                 s[1] = s[10] = s[19] = s[28] = '\0';
1474                                 m = registry_machine_allocate(&s[29], strtoul(&s[2], NULL, 16));
1475                                 m->last_t = strtoul(&s[11], NULL, 16);
1476                                 m->usages = strtoul(&s[20], NULL, 16);
1477                                 debug(D_REGISTRY, "Registry loaded machine '%s', first: %u, last: %u, usages: %u", m->guid, m->first_t, m->last_t, m->usages);
1478                                 break;
1479
1480                         case 'U': // person URL
1481                                 if(unlikely(!p)) {
1482                                         error("Registry: ignoring line %zu, no person loaded: %s", line, s);
1483                                         continue;
1484                                 }
1485
1486                                 // verify it is valid
1487                                 if(len < 69 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[31] != '\t' || s[68] != '\t') {
1488                                         error("Registry person URL line %u is wrong (len = %zu).", line, len);
1489                                         continue;
1490                                 }
1491
1492                                 s[1] = s[10] = s[19] = s[28] = s[31] = s[68] = '\0';
1493
1494                                 // skip the name to find the url
1495                                 char *url = &s[69];
1496                                 while(*url && *url != '\t') url++;
1497                                 if(!*url) {
1498                                         error("Registry person URL line %u does not have a url.", line);
1499                                         continue;
1500                                 }
1501                                 *url++ = '\0';
1502
1503                                 u = registry_url_allocate_nolock(url, strlen(url));
1504
1505                                 time_t first_t = strtoul(&s[2], NULL, 16);
1506
1507                                 m = registry_machine_find(&s[32]);
1508                                 if(!m) m = registry_machine_allocate(&s[32], first_t);
1509
1510                                 PERSON_URL *pu = registry_person_url_allocate(p, m, u, &s[69], strlen(&s[69]), first_t);
1511                                 pu->last_t = strtoul(&s[11], NULL, 16);
1512                                 pu->usages = strtoul(&s[20], NULL, 16);
1513                                 pu->flags = strtoul(&s[29], NULL, 16);
1514                                 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);
1515                                 break;
1516
1517                         case 'V': // machine URL
1518                                 if(unlikely(!m)) {
1519                                         error("Registry: ignoring line %zu, no machine loaded: %s", line, s);
1520                                         continue;
1521                                 }
1522
1523                                 // verify it is valid
1524                                 if(len < 32 || s[1] != '\t' || s[10] != '\t' || s[19] != '\t' || s[28] != '\t' || s[31] != '\t') {
1525                                         error("Registry person URL line %u is wrong (len = %zu).", line, len);
1526                                         continue;
1527                                 }
1528
1529                                 s[1] = s[10] = s[19] = s[28] = s[31] = '\0';
1530                                 u = registry_url_allocate_nolock(&s[32], strlen(&s[32]));
1531
1532                                 MACHINE_URL *mu = registry_machine_url_allocate(m, u, strtoul(&s[2], NULL, 16));
1533                                 mu->last_t = strtoul(&s[11], NULL, 16);
1534                                 mu->usages = strtoul(&s[20], NULL, 16);
1535                                 mu->flags = strtoul(&s[29], NULL, 16);
1536                                 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);
1537                                 break;
1538
1539                         default:
1540                                 error("Registry: ignoring line %zu of filename '%s': %s.", line, registry.db_filename, s);
1541                                 break;
1542                 }
1543         }
1544         fclose(fp);
1545
1546         return line;
1547 }
1548
1549 // ----------------------------------------------------------------------------
1550 // REGISTRY
1551
1552 int registry_init(void) {
1553         char filename[FILENAME_MAX + 1];
1554
1555         // registry enabled?
1556         registry.enabled = config_get_boolean("registry", "enabled", 0);
1557
1558         // pathnames
1559         registry.pathname = config_get("registry", "registry db directory", VARLIB_DIR "/registry");
1560         if(mkdir(registry.pathname, 0755) == -1 && errno != EEXIST) {
1561                 error("Cannot create directory '%s'. Registry disabled.", registry.pathname);
1562                 registry.enabled = 0;
1563                 return -1;
1564         }
1565
1566         // filenames
1567         snprintf(filename, FILENAME_MAX, "%s/netdata.public.unique.id", registry.pathname);
1568         registry.machine_guid_filename = config_get("registry", "netdata unique id file", filename);
1569         registry_get_this_machine_guid();
1570
1571         snprintf(filename, FILENAME_MAX, "%s/registry.db", registry.pathname);
1572         registry.db_filename = config_get("registry", "registry db file", filename);
1573
1574         snprintf(filename, FILENAME_MAX, "%s/registry-log.db", registry.pathname);
1575         registry.log_filename = config_get("registry", "registry log file", filename);
1576
1577         // configuration options
1578         registry.save_registry_every_entries = config_get_number("registry", "registry save db every new entries", 1000000);
1579         registry.persons_expiration = config_get_number("registry", "registry expire idle persons days", 365) * 86400;
1580         registry.registry_domain = config_get("registry", "registry domain", "");
1581         registry.registry_to_announce = config_get("registry", "registry to announce", "https://registry.netdata.online");
1582         registry.hostname = config_get("registry", "registry hostname", config_get("global", "hostname", hostname));
1583
1584         registry.max_url_length = config_get_number("registry", "max URL length", 1024);
1585         registry.max_name_length = config_get_number("registry", "max URL name length", 50);
1586
1587
1588         // initialize entries counters
1589         registry.persons_count = 0;
1590         registry.machines_count = 0;
1591         registry.usages_count = 0;
1592         registry.urls_count = 0;
1593         registry.persons_urls_count = 0;
1594         registry.machines_urls_count = 0;
1595
1596         // initialize memory counters
1597         registry.persons_memory = 0;
1598         registry.machines_memory = 0;
1599         registry.urls_memory = 0;
1600         registry.persons_urls_memory = 0;
1601         registry.machines_urls_memory = 0;
1602
1603         // initialize locks
1604         pthread_mutex_init(&registry.persons_lock, NULL);
1605         pthread_mutex_init(&registry.machines_lock, NULL);
1606         pthread_mutex_init(&registry.urls_lock, NULL);
1607         pthread_mutex_init(&registry.person_urls_lock, NULL);
1608         pthread_mutex_init(&registry.machine_urls_lock, NULL);
1609
1610         // create dictionaries
1611         registry.persons = dictionary_create(DICTIONARY_FLAGS);
1612         registry.machines = dictionary_create(DICTIONARY_FLAGS);
1613         registry.urls = dictionary_create(DICTIONARY_FLAGS);
1614
1615         // load the registry database
1616         if(registry.enabled) {
1617                 registry_log_open_nolock();
1618                 registry_load();
1619                 registry_log_load();
1620         }
1621
1622         return 0;
1623 }
1624
1625 void registry_free(void) {
1626         if(!registry.enabled) return;
1627
1628         // we need to destroy the dictionaries ourselves
1629         // since the dictionaries use memory we allocated
1630
1631         while(registry.persons->values_index.root) {
1632                 PERSON *p = ((NAME_VALUE *)registry.persons->values_index.root)->value;
1633
1634                 // fprintf(stderr, "\nPERSON: '%s', first: %u, last: %u, usages: %u\n", p->guid, p->first_t, p->last_t, p->usages);
1635
1636                 while(p->urls->values_index.root) {
1637                         PERSON_URL *pu = ((NAME_VALUE *)p->urls->values_index.root)->value;
1638
1639                         // 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);
1640
1641                         debug(D_REGISTRY, "Registry: deleting url '%s' from person '%s'", pu->url->url, p->guid);
1642                         dictionary_del(p->urls, pu->url->url);
1643
1644                         debug(D_REGISTRY, "Registry: unlinking url '%s' from person", pu->url->url);
1645                         registry_url_unlink_nolock(pu->url);
1646
1647                         debug(D_REGISTRY, "Registry: freeing person url");
1648                         free(pu);
1649                 }
1650
1651                 debug(D_REGISTRY, "Registry: deleting person '%s' from persons registry", p->guid);
1652                 dictionary_del(registry.persons, p->guid);
1653
1654                 debug(D_REGISTRY, "Registry: destroying URL dictionary of person '%s'", p->guid);
1655                 dictionary_destroy(p->urls);
1656
1657                 debug(D_REGISTRY, "Registry: freeing person '%s'", p->guid);
1658                 free(p);
1659         }
1660
1661         while(registry.machines->values_index.root) {
1662                 MACHINE *m = ((NAME_VALUE *)registry.machines->values_index.root)->value;
1663
1664                 // fprintf(stderr, "\nMACHINE: '%s', first: %u, last: %u, usages: %u\n", m->guid, m->first_t, m->last_t, m->usages);
1665
1666                 while(m->urls->values_index.root) {
1667                         MACHINE_URL *mu = ((NAME_VALUE *)m->urls->values_index.root)->value;
1668
1669                         // 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);
1670
1671                         //debug(D_REGISTRY, "Registry: destroying persons dictionary from url '%s'", mu->url->url);
1672                         //dictionary_destroy(mu->persons);
1673
1674                         debug(D_REGISTRY, "Registry: deleting url '%s' from person '%s'", mu->url->url, m->guid);
1675                         dictionary_del(m->urls, mu->url->url);
1676
1677                         debug(D_REGISTRY, "Registry: unlinking url '%s' from machine", mu->url->url);
1678                         registry_url_unlink_nolock(mu->url);
1679
1680                         debug(D_REGISTRY, "Registry: freeing machine url");
1681                         free(mu);
1682                 }
1683
1684                 debug(D_REGISTRY, "Registry: deleting machine '%s' from machines registry", m->guid);
1685                 dictionary_del(registry.machines, m->guid);
1686
1687                 debug(D_REGISTRY, "Registry: destroying URL dictionary of machine '%s'", m->guid);
1688                 dictionary_destroy(m->urls);
1689
1690                 debug(D_REGISTRY, "Registry: freeing machine '%s'", m->guid);
1691                 free(m);
1692         }
1693
1694         // and free the memory of remaining dictionary structures
1695
1696         debug(D_REGISTRY, "Registry: destroying persons dictionary");
1697         dictionary_destroy(registry.persons);
1698
1699         debug(D_REGISTRY, "Registry: destroying machines dictionary");
1700         dictionary_destroy(registry.machines);
1701
1702         debug(D_REGISTRY, "Registry: destroying urls dictionary");
1703         dictionary_destroy(registry.urls);
1704 }
1705
1706 // ----------------------------------------------------------------------------
1707 // STATISTICS
1708
1709 void registry_statistics(void) {
1710         if(!registry.enabled) return;
1711
1712         static RRDSET *sts = NULL, *stc = NULL, *stm = NULL;
1713
1714         if(!sts) sts = rrdset_find("netdata.registry_sessions");
1715         if(!sts) {
1716                 sts = rrdset_create("netdata", "registry_sessions", NULL, "registry", NULL, "NetData Registry Sessions", "session", 131000, rrd_update_every, RRDSET_TYPE_LINE);
1717
1718                 rrddim_add(sts, "sessions",  NULL,  1, 1, RRDDIM_ABSOLUTE);
1719         }
1720         else rrdset_next(sts);
1721
1722         rrddim_set(sts, "sessions", registry.usages_count);
1723         rrdset_done(sts);
1724
1725         // ------------------------------------------------------------------------
1726
1727         if(!stc) stc = rrdset_find("netdata.registry_entries");
1728         if(!stc) {
1729                 stc = rrdset_create("netdata", "registry_entries", NULL, "registry", NULL, "NetData Registry Entries", "entries", 131100, rrd_update_every, RRDSET_TYPE_LINE);
1730
1731                 rrddim_add(stc, "persons",        NULL,  1, 1, RRDDIM_ABSOLUTE);
1732                 rrddim_add(stc, "machines",       NULL,  1, 1, RRDDIM_ABSOLUTE);
1733                 rrddim_add(stc, "urls",           NULL,  1, 1, RRDDIM_ABSOLUTE);
1734                 rrddim_add(stc, "persons_urls",   NULL,  1, 1, RRDDIM_ABSOLUTE);
1735                 rrddim_add(stc, "machines_urls",  NULL,  1, 1, RRDDIM_ABSOLUTE);
1736         }
1737         else rrdset_next(stc);
1738
1739         rrddim_set(stc, "persons",       registry.persons_count);
1740         rrddim_set(stc, "machines",      registry.machines_count);
1741         rrddim_set(stc, "urls",          registry.urls_count);
1742         rrddim_set(stc, "persons_urls",  registry.persons_urls_count);
1743         rrddim_set(stc, "machines_urls", registry.machines_urls_count);
1744         rrdset_done(stc);
1745
1746         // ------------------------------------------------------------------------
1747
1748         if(!stm) stm = rrdset_find("netdata.registry_mem");
1749         if(!stm) {
1750                 stm = rrdset_create("netdata", "registry_mem", NULL, "registry", NULL, "NetData Registry Memory", "KB", 131300, rrd_update_every, RRDSET_TYPE_STACKED);
1751
1752                 rrddim_add(stm, "persons",        NULL,  1, 1024, RRDDIM_ABSOLUTE);
1753                 rrddim_add(stm, "machines",       NULL,  1, 1024, RRDDIM_ABSOLUTE);
1754                 rrddim_add(stm, "urls",           NULL,  1, 1024, RRDDIM_ABSOLUTE);
1755                 rrddim_add(stm, "persons_urls",   NULL,  1, 1024, RRDDIM_ABSOLUTE);
1756                 rrddim_add(stm, "machines_urls",  NULL,  1, 1024, RRDDIM_ABSOLUTE);
1757         }
1758         else rrdset_next(stm);
1759
1760         rrddim_set(stm, "persons",       registry.persons_memory + registry.persons_count * sizeof(NAME_VALUE) + sizeof(DICTIONARY));
1761         rrddim_set(stm, "machines",      registry.machines_memory + registry.machines_count * sizeof(NAME_VALUE) + sizeof(DICTIONARY));
1762         rrddim_set(stm, "urls",          registry.urls_memory + registry.urls_count * sizeof(NAME_VALUE) + sizeof(DICTIONARY));
1763         rrddim_set(stm, "persons_urls",  registry.persons_urls_memory + registry.persons_count * sizeof(DICTIONARY) + registry.persons_urls_count * sizeof(NAME_VALUE));
1764         rrddim_set(stm, "machines_urls", registry.machines_urls_memory + registry.machines_count * sizeof(DICTIONARY) + registry.machines_urls_count * sizeof(NAME_VALUE));
1765         rrdset_done(stm);
1766 }
1767
1768
1769 #ifdef REGISTRY_STANDALONE_TESTS
1770
1771 // ----------------------------------------------------------------------------
1772 // TESTS
1773
1774 int test1(int argc, char **argv) {
1775
1776         void print_stats(uint32_t requests, unsigned long long start, unsigned long long end) {
1777                 fprintf(stderr, " > SPEED: %u requests served in %0.2f seconds ( >>> %llu per second <<< )\n",
1778                                 requests, (end-start) / 1000000.0, (unsigned long long)requests * 1000000ULL / (end-start));
1779
1780                 fprintf(stderr, " > DB   : persons %llu, machines %llu, unique URLs %llu, accesses %llu, URLs: for persons %llu, for machines %llu\n",
1781                                 registry.persons_count, registry.machines_count, registry.urls_count, registry.usages_count,
1782                                 registry.persons_urls_count, registry.machines_urls_count);
1783         }
1784
1785         (void) argc;
1786         (void) argv;
1787
1788         uint32_t u, users = 1000000;
1789         uint32_t m, machines = 200000;
1790         uint32_t machines2 = machines * 2;
1791
1792         char **users_guids = malloc(users * sizeof(char *));
1793         char **machines_guids = malloc(machines2 * sizeof(char *));
1794         char **machines_urls = malloc(machines2 * sizeof(char *));
1795         unsigned long long start;
1796
1797         registry_init();
1798
1799         fprintf(stderr, "Generating %u machine guids\n", machines2);
1800         for(m = 0; m < machines2 ;m++) {
1801                 uuid_t uuid;
1802                 machines_guids[m] = malloc(36+1);
1803                 uuid_generate(uuid);
1804                 uuid_unparse(uuid, machines_guids[m]);
1805
1806                 char buf[FILENAME_MAX + 1];
1807                 snprintf(buf, FILENAME_MAX, "http://%u.netdata.rocks/", m+1);
1808                 machines_urls[m] = strdup(buf);
1809
1810                 // fprintf(stderr, "\tmachine %u: '%s', url: '%s'\n", m + 1, machines_guids[m], machines_urls[m]);
1811         }
1812
1813         start = timems();
1814         fprintf(stderr, "\nGenerating %u users accessing %u machines\n", users, machines);
1815         m = 0;
1816         time_t now = time(NULL);
1817         for(u = 0; u < users ; u++) {
1818                 if(++m == machines) m = 0;
1819
1820                 PERSON *p = registry_request_access(NULL, machines_guids[m], machines_urls[m], "test", now);
1821                 users_guids[u] = p->guid;
1822         }
1823         print_stats(u, start, timems());
1824
1825         start = timems();
1826         fprintf(stderr, "\nAll %u users accessing again the same %u servers\n", users, machines);
1827         m = 0;
1828         now = time(NULL);
1829         for(u = 0; u < users ; u++) {
1830                 if(++m == machines) m = 0;
1831
1832                 PERSON *p = registry_request_access(users_guids[u], machines_guids[m], machines_urls[m], "test", now);
1833
1834                 if(p->guid != users_guids[u])
1835                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[u], p->guid);
1836         }
1837         print_stats(u, start, timems());
1838
1839         start = timems();
1840         fprintf(stderr, "\nAll %u users accessing a new server, out of the %u servers\n", users, machines);
1841         m = 1;
1842         now = time(NULL);
1843         for(u = 0; u < users ; u++) {
1844                 if(++m == machines) m = 0;
1845
1846                 PERSON *p = registry_request_access(users_guids[u], machines_guids[m], machines_urls[m], "test", now);
1847
1848                 if(p->guid != users_guids[u])
1849                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[u], p->guid);
1850         }
1851         print_stats(u, start, timems());
1852
1853         start = timems();
1854         fprintf(stderr, "\n%u random users accessing a random server, out of the %u servers\n", users, machines);
1855         now = time(NULL);
1856         for(u = 0; u < users ; u++) {
1857                 uint32_t tu = random() * users / RAND_MAX;
1858                 uint32_t tm = random() * machines / RAND_MAX;
1859
1860                 PERSON *p = registry_request_access(users_guids[tu], machines_guids[tm], machines_urls[tm], "test", now);
1861
1862                 if(p->guid != users_guids[tu])
1863                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[tu], p->guid);
1864         }
1865         print_stats(u, start, timems());
1866
1867         start = timems();
1868         fprintf(stderr, "\n%u random users accessing a random server, out of %u servers\n", users, machines2);
1869         now = time(NULL);
1870         for(u = 0; u < users ; u++) {
1871                 uint32_t tu = random() * users / RAND_MAX;
1872                 uint32_t tm = random() * machines2 / RAND_MAX;
1873
1874                 PERSON *p = registry_request_access(users_guids[tu], machines_guids[tm], machines_urls[tm], "test", now);
1875
1876                 if(p->guid != users_guids[tu])
1877                         fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[tu], p->guid);
1878         }
1879         print_stats(u, start, timems());
1880
1881         for(m = 0; m < 10; m++) {
1882                 start = timems();
1883                 fprintf(stderr,
1884                                 "\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",
1885                                 users * 2, machines2);
1886                 now = time(NULL);
1887                 for (u = 0; u < users * 2; u++) {
1888                         uint32_t tu = random() * users / RAND_MAX;
1889                         uint32_t tm = random() * machines2 / RAND_MAX;
1890
1891                         char *url = machines_urls[tm];
1892                         char buf[FILENAME_MAX + 1];
1893                         if (random() % 10000 == 1234) {
1894                                 snprintf(buf, FILENAME_MAX, "http://random.%ld.netdata.rocks/", random());
1895                                 url = buf;
1896                         }
1897                         else if (random() % 1000 == 123)
1898                                 url = machines_urls[random() * machines2 / RAND_MAX];
1899
1900                         PERSON *p = registry_request_access(users_guids[tu], machines_guids[tm], url, "test", now);
1901
1902                         if (p->guid != users_guids[tu])
1903                                 fprintf(stderr, "ERROR: expected to get user guid '%s' but git '%s'", users_guids[tu], p->guid);
1904                 }
1905                 print_stats(u, start, timems());
1906         }
1907
1908         fprintf(stderr, "\n\nSAVE\n");
1909         start = timems();
1910         registry_save();
1911         print_stats(registry.persons_count, start, timems());
1912
1913         fprintf(stderr, "\n\nCLEANUP\n");
1914         start = timems();
1915         registry_free();
1916         print_stats(registry.persons_count, start, timems());
1917         return 0;
1918 }
1919
1920 // ----------------------------------------------------------------------------
1921 // TESTING
1922
1923 int main(int argc, char **argv) {
1924         // debug_flags = 0xFFFFFFFF;
1925         // test1(argc, argv);
1926         // exit(0);
1927
1928         (void)argc;
1929         (void)argv;
1930
1931
1932         PERSON *p1, *p2;
1933
1934         fprintf(stderr, "\n\nINITIALIZATION\n");
1935
1936         registry_init();
1937
1938         int i = 2;
1939
1940         fprintf(stderr, "\n\nADDING ENTRY\n");
1941         p1 = registry_request_access("2c95abd0-1542-11e6-8c66-00508db7e9c9", "7c173980-145c-11e6-b86f-00508db7e9c1", "http://localhost:19999/", "test", time(NULL));
1942
1943         if(0)
1944         while(i--) {
1945 #ifdef REGISTRY_STDOUT_DUMP
1946                 fprintf(stderr, "\n\nADDING ENTRY\n");
1947 #endif /* REGISTRY_STDOUT_DUMP */
1948                 p1 = registry_request_access(NULL, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://localhost:19999/", "test", time(NULL));
1949
1950 #ifdef REGISTRY_STDOUT_DUMP
1951                 fprintf(stderr, "\n\nADDING ANOTHER URL\n");
1952 #endif /* REGISTRY_STDOUT_DUMP */
1953                 p1 = registry_request_access(p1->guid, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://127.0.0.1:19999/", "test", time(NULL));
1954
1955 #ifdef REGISTRY_STDOUT_DUMP
1956                 fprintf(stderr, "\n\nADDING ANOTHER URL\n");
1957 #endif /* REGISTRY_STDOUT_DUMP */
1958                 p1 = registry_request_access(p1->guid, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://my.server:19999/", "test", time(NULL));
1959
1960 #ifdef REGISTRY_STDOUT_DUMP
1961                 fprintf(stderr, "\n\nADDING ANOTHER MACHINE\n");
1962 #endif /* REGISTRY_STDOUT_DUMP */
1963                 p1 = registry_request_access(p1->guid, "7c173980-145c-11e6-b86f-00508db7e9c1", "http://my.server:19999/", "test", time(NULL));
1964
1965 #ifdef REGISTRY_STDOUT_DUMP
1966                 fprintf(stderr, "\n\nADDING ANOTHER PERSON\n");
1967 #endif /* REGISTRY_STDOUT_DUMP */
1968                 p2 = registry_request_access(NULL, "7c173980-145c-11e6-b86f-00508db7e9c3", "http://localhost:19999/", "test", time(NULL));
1969
1970 #ifdef REGISTRY_STDOUT_DUMP
1971                 fprintf(stderr, "\n\nADDING ANOTHER MACHINE\n");
1972 #endif /* REGISTRY_STDOUT_DUMP */
1973                 p2 = registry_request_access(p2->guid, "7c173980-145c-11e6-b86f-00508db7e9c3", "http://localhost:19999/", "test", time(NULL));
1974         }
1975
1976         fprintf(stderr, "\n\nSAVE\n");
1977         registry_save();
1978
1979         fprintf(stderr, "\n\nCLEANUP\n");
1980         registry_free();
1981         return 0;
1982 }
1983
1984 #endif /* REGISTRY_STANDALONE_TESTS */