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