forked from openstreetmap/mod_tile
/
daemon.c
1224 lines (1081 loc) · 41.4 KB
/
daemon.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <poll.h>
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <syslog.h>
#include <getopt.h>
#include "render_config.h"
#include "daemon.h"
#include "gen_tile.h"
#include "protocol.h"
#define PIDFILE "/var/run/renderd/renderd.pid"
// extern "C" {
#include "iniparser3.0b/src/iniparser.h"
// }
static pthread_t *render_threads;
static pthread_t *slave_threads;
static struct sigaction sigPipeAction;
static struct item reqHead, reqPrioHead, reqBulkHead, dirtyHead, renderHead;
static struct item_idx * item_hashidx;
static int reqNum, reqPrioNum, reqBulkNum, dirtyNum;
static pthread_mutex_t qLock;
static pthread_cond_t qCond;
static int exit_pipe_fd;
static stats_struct stats;
static pthread_t stats_thread;
static renderd_config config;
int noSlaveRenders;
int hashidxSize;
void statsRenderFinish(int z, long time) {
pthread_mutex_lock(&qLock);
if ((z >= 0) && (z <= MAX_ZOOM)) {
stats.noZoomRender[z]++;
stats.timeZoomRender[z] += time;
}
pthread_mutex_unlock(&qLock);
}
struct item *fetch_request(void)
{
struct item *item = NULL;
pthread_mutex_lock(&qLock);
while ((reqNum == 0) && (dirtyNum == 0) && (reqPrioNum == 0) && (reqBulkNum == 0)) {
pthread_cond_wait(&qCond, &qLock);
}
if (reqPrioNum) {
item = reqPrioHead.next;
reqPrioNum--;
stats.noReqPrioRender++;
} else if (reqNum) {
item = reqHead.next;
reqNum--;
stats.noReqRender++;
} else if (dirtyNum) {
item = dirtyHead.next;
dirtyNum--;
stats.noDirtyRender++;
} else if (reqBulkNum) {
item = reqBulkHead.next;
reqBulkNum--;
stats.noReqBulkRender++;
}
if (item) {
item->next->prev = item->prev;
item->prev->next = item->next;
item->prev = &renderHead;
item->next = renderHead.next;
renderHead.next->prev = item;
renderHead.next = item;
item->inQueue = queueRender;
}
pthread_mutex_unlock(&qLock);
return item;
}
void clear_requests(int fd)
{
struct item *item, *dupes, *queueHead;
/**Only need to look up on the shorter request and render queue
* so using the linear list shouldn't be a problem
*/
pthread_mutex_lock(&qLock);
for (int i = 0; i < 4; i++) {
switch (i) {
case 0: { queueHead = &reqHead; break;}
case 1: { queueHead = &renderHead; break;}
case 2: { queueHead = &reqPrioHead; break;}
case 3: { queueHead = &reqBulkHead; break;}
}
item = queueHead->next;
while (item != queueHead) {
if (item->fd == fd)
item->fd = FD_INVALID;
dupes = item->duplicates;
while (dupes) {
if (dupes->fd == fd)
dupes->fd = FD_INVALID;
dupes = dupes->duplicates;
}
item = item->next;
}
}
pthread_mutex_unlock(&qLock);
}
static int calcHashKey(struct item *item) {
uint64_t xmlnameHash = 0;
uint64_t key;
for (int i = 0; item->req.xmlname[i] != 0; i++) {
xmlnameHash += item->req.xmlname[i];
}
key = ((uint64_t)(xmlnameHash & 0x1FF) << 52) + ((uint64_t)(item->req.z) << 48) + ((uint64_t)(item->mx & 0xFFFFFF) << 24) + (item->my & 0xFFFFFF);
return key % hashidxSize;
}
void insert_item_idx(struct item *item) {
struct item_idx * nextItem;
struct item_idx * prevItem;
int key = calcHashKey(item);
if (item_hashidx[key].item == NULL) {
item_hashidx[key].item = item;
} else {
prevItem = &(item_hashidx[key]);
nextItem = item_hashidx[key].next;
while(nextItem) {
prevItem = nextItem;
nextItem = nextItem->next;
}
nextItem = (struct item_idx *)malloc(sizeof(struct item_idx));
nextItem->item = item;
nextItem->next = NULL;
prevItem->next = nextItem;
}
}
void remove_item_idx(struct item * item) {
int key = calcHashKey(item);
struct item_idx * nextItem;
struct item_idx * prevItem;
struct item * test;
if (item_hashidx[key].item == NULL) {
//item not in index;
return;
}
prevItem = &(item_hashidx[key]);
nextItem = &(item_hashidx[key]);
while (nextItem != NULL) {
test = nextItem->item;
if ((item->mx == test->mx) && (item->my == test->my) && (item->req.z
== test->req.z) && (!strcmp(item->req.xmlname,
test->req.xmlname))) {
/*
* Found item, removing it from list
*/
nextItem->item = NULL;
if (nextItem->next != NULL) {
if (nextItem == &(item_hashidx[key])) {
prevItem = nextItem->next;
memcpy(&(item_hashidx[key]), nextItem->next,
sizeof(struct item_idx));
free(prevItem);
} else {
prevItem->next = nextItem->next;
}
} else {
prevItem->next = NULL;
}
if (nextItem != &(item_hashidx[key])) {
free(nextItem);
}
return;
} else {
prevItem = nextItem;
nextItem = nextItem->next;
}
}
}
struct item * lookup_item_idx(struct item * item) {
struct item_idx * nextItem;
struct item * test;
int key = calcHashKey(item);
if (item_hashidx[key].item == NULL) {
return NULL;
} else {
nextItem = &(item_hashidx[key]);
while (nextItem != NULL) {
test = nextItem->item;
if ((item->mx == test->mx) && (item->my == test->my)
&& (item->req.z == test->req.z) && (!strcmp(
item->req.xmlname, test->req.xmlname))) {
return test;
} else {
nextItem = nextItem->next;
}
}
}
return NULL;
}
static const char *cmdStr(enum protoCmd c)
{
switch (c) {
case cmdIgnore: return "Ignore";
case cmdRender: return "Render";
case cmdRenderPrio: return "RenderPrio";
case cmdRenderBulk: return "RenderBulk";
case cmdDirty: return "Dirty";
case cmdDone: return "Done";
case cmdNotDone: return "NotDone";
default: return "unknown";
}
}
void send_response(struct item *item, enum protoCmd rsp)
{
struct protocol *req = &item->req;
int ret;
pthread_mutex_lock(&qLock);
item->next->prev = item->prev;
item->prev->next = item->next;
remove_item_idx(item);
pthread_mutex_unlock(&qLock);
while (item) {
struct item *prev = item;
req = &item->req;
if ((item->fd != FD_INVALID) && ((req->cmd == cmdRender) || (req->cmd == cmdRenderPrio) || (req->cmd == cmdRenderBulk))) {
req->cmd = rsp;
//fprintf(stderr, "Sending message %s to %d\n", cmdStr(rsp), item->fd);
ret = send(item->fd, req, sizeof(*req), 0);
if (ret != sizeof(*req))
perror("send error during send_done");
}
item = item->duplicates;
free(prev);
}
}
enum protoCmd pending(struct item *test)
{
// check all queues and render list to see if this request already queued
// If so, add this new request as a duplicate
// call with qLock held
struct item *item;
item = lookup_item_idx(test);
if (item != NULL) {
if ((item->inQueue == queueRender) || (item->inQueue == queueRequest) || (item->inQueue == queueRequestPrio)) {
test->duplicates = item->duplicates;
item->duplicates = test;
test->inQueue = queueDuplicate;
return cmdIgnore;
} else if ((item->inQueue == queueDirty) || (item->inQueue == queueRequestBulk)){
return cmdNotDone;
}
}
return cmdRender;
}
void item_load(struct item *item, const struct protocol *req) {
char path[PATH_MAX];
struct stat buf;
xyz_to_meta(path, sizeof(path), HASH_PATH, req->xmlname, req->x, req->y, req->z);
if(!stat(path, &buf)) {
// save time of old tile
item->old_mtime=buf.st_mtime;
}
else {
// no tile
item->old_mtime=0;
}
}
enum protoCmd rx_request(const struct protocol *req, int fd)
{
struct protocol *reqnew;
struct item *list = NULL, *item;
enum protoCmd pend;
// Upgrade version 1 to version 2
if (req->ver == 1) {
reqnew = (struct protocol *)malloc(sizeof(struct protocol));
memcpy(reqnew, req, sizeof(struct protocol_v1));
reqnew->xmlname[0] = 0;
req = reqnew;
}
else if (req->ver != 2) {
syslog(LOG_ERR, "Bad protocol version %d", req->ver);
return cmdIgnore;
}
syslog(LOG_DEBUG, "DEBUG: Got command %s fd(%d) xml(%s), z(%d), x(%d), y(%d)",
cmdStr(req->cmd), fd, req->xmlname, req->z, req->x, req->y);
if ((req->cmd != cmdRender) && (req->cmd != cmdRenderPrio) && (req->cmd != cmdDirty) && (req->cmd != cmdRenderBulk))
return cmdIgnore;
item = (struct item *)malloc(sizeof(*item));
if (!item) {
syslog(LOG_ERR, "malloc failed");
return cmdNotDone;
}
item->req = *req;
item->duplicates = NULL;
item->fd = (req->cmd == cmdDirty) ? FD_INVALID : fd;
item_load(item, req);
#ifdef METATILE
/* Round down request co-ordinates to the neareast N (should be a power of 2)
* Note: request path is no longer consistent but this will be recalculated
* when the metatile is being rendered.
*/
item->mx = item->req.x & ~(METATILE-1);
item->my = item->req.y & ~(METATILE-1);
#else
item->mx = item->req.x;
item->my = item->req.y;
#endif
pthread_mutex_lock(&qLock);
// Check for a matching request in the current rendering or dirty queues
pend = pending(item);
if (pend == cmdNotDone) {
// We found a match in the dirty queue, can not wait for it
pthread_mutex_unlock(&qLock);
free(item);
return cmdNotDone;
}
if (pend == cmdIgnore) {
// Found a match in render queue, item added as duplicate
pthread_mutex_unlock(&qLock);
return cmdIgnore;
}
// New request, add it to render or dirty queue
if ((req->cmd == cmdRender) && (reqNum < REQ_LIMIT)) {
list = &reqHead;
item->inQueue = queueRequest;
reqNum++;
} else if ((req->cmd == cmdRenderPrio) && (reqPrioNum < REQ_LIMIT)) {
list = &reqPrioHead;
item->inQueue = queueRequestPrio;
reqPrioNum++;
} else if ((req->cmd == cmdRenderBulk) && (reqBulkNum < REQ_LIMIT)) {
list = &reqBulkHead;
item->inQueue = queueRequestBulk;
reqBulkNum++;
} else if (dirtyNum < DIRTY_LIMIT) {
list = &dirtyHead;
item->inQueue = queueDirty;
dirtyNum++;
item->fd = FD_INVALID; // No response after render
} else {
// The queue is severely backlogged. Drop request
stats.noReqDroped++;
pthread_mutex_unlock(&qLock);
free(item);
return cmdNotDone;
}
if (list) {
item->next = list;
item->prev = list->prev;
item->prev->next = item;
list->prev = item;
/* In addition to the linked list, add item to a hash table index
* for faster lookup of pending requests.
*/
insert_item_idx(item);
pthread_cond_signal(&qCond);
} else
free(item);
pthread_mutex_unlock(&qLock);
return (list == &reqHead)?cmdIgnore:cmdNotDone;
}
void request_exit(void)
{
// Any write to the exit pipe will trigger a graceful exit
char c=0;
if (write(exit_pipe_fd, &c, sizeof(c)) < 0) {
fprintf(stderr, "Failed to write to the exit pipe: %s\n", strerror(errno));
}
}
void process_loop(int listen_fd)
{
int num_connections = 0;
int connections[MAX_CONNECTIONS];
int pipefds[2];
int exit_pipe_read;
bzero(connections, sizeof(connections));
// A pipe is used to allow the render threads to request an exit by the main process
if (pipe(pipefds)) {
fprintf(stderr, "Failed to create pipe\n");
return;
}
exit_pipe_fd = pipefds[1];
exit_pipe_read = pipefds[0];
while (1) {
struct sockaddr_un in_addr;
socklen_t in_addrlen = sizeof(in_addr);
fd_set rd;
int incoming, num, nfds, i;
FD_ZERO(&rd);
FD_SET(listen_fd, &rd);
nfds = listen_fd+1;
for (i=0; i<num_connections; i++) {
FD_SET(connections[i], &rd);
nfds = MAX(nfds, connections[i]+1);
}
FD_SET(exit_pipe_read, &rd);
nfds = MAX(nfds, exit_pipe_read+1);
num = select(nfds, &rd, NULL, NULL, NULL);
if (num == -1)
perror("select()");
else if (num) {
if (FD_ISSET(exit_pipe_read, &rd)) {
// A render thread wants us to exit
break;
}
//printf("Data is available now on %d fds\n", num);
if (FD_ISSET(listen_fd, &rd)) {
num--;
incoming = accept(listen_fd, (struct sockaddr *) &in_addr, &in_addrlen);
if (incoming < 0) {
perror("accept()");
} else {
if (num_connections == MAX_CONNECTIONS) {
syslog(LOG_WARNING, "Connection limit(%d) reached. Dropping connection\n", MAX_CONNECTIONS);
close(incoming);
} else {
connections[num_connections++] = incoming;
syslog(LOG_DEBUG, "DEBUG: Got incoming connection, fd %d, number %d\n", incoming, num_connections);
}
}
}
for (i=0; num && (i<num_connections); i++) {
int fd = connections[i];
if (FD_ISSET(fd, &rd)) {
struct protocol cmd;
int ret;
// TODO: to get highest performance we should loop here until we get EAGAIN
ret = recv(fd, &cmd, sizeof(cmd), MSG_DONTWAIT);
if (ret == sizeof(cmd)) {
enum protoCmd rsp = rx_request(&cmd, fd);
if ((cmd.cmd == cmdRender) && (rsp == cmdNotDone)) {
cmd.cmd = rsp;
syslog(LOG_DEBUG, "DEBUG: Sending NotDone response(%d)\n", rsp);
ret = send(fd, &cmd, sizeof(cmd), 0);
if (ret != sizeof(cmd))
perror("response send error");
}
} else if (!ret) {
int j;
num_connections--;
syslog(LOG_DEBUG, "DEBUG: Connection %d, fd %d closed, now %d left\n", i, fd, num_connections);
for (j=i; j < num_connections; j++)
connections[j] = connections[j+1];
clear_requests(fd);
close(fd);
} else {
syslog(LOG_ERR, "Recv Error on fd %d", fd);
break;
}
}
}
} else {
syslog(LOG_ERR, "Select timeout");
}
}
}
/**
* Periodically write out current stats to a stats file. This information
* can then be used to monitor performance of renderd e.g. with a munin plugin
*/
void *stats_writeout_thread(void * arg) {
stats_struct lStats;
int dirtQueueLength;
int reqQueueLength;
int reqPrioQueueLength;
int reqBulkQueueLength;
int i;
int noFailedAttempts = 0;
char tmpName[PATH_MAX];
snprintf(tmpName, sizeof(tmpName), "%s.tmp", config.stats_filename);
syslog(LOG_DEBUG, "Starting stats thread");
while (1) {
pthread_mutex_lock(&qLock);
memcpy(&lStats, &stats, sizeof(stats_struct));
dirtQueueLength = dirtyNum;
reqQueueLength = reqNum;
reqPrioQueueLength = reqPrioNum;
reqBulkQueueLength = reqBulkNum;
pthread_mutex_unlock(&qLock);
FILE * statfile = fopen(tmpName, "w");
if (statfile == NULL) {
syslog(LOG_WARNING, "Failed to open stats file: %i", errno);
noFailedAttempts++;
if (noFailedAttempts > 3) {
syslog(LOG_ERR, "ERROR: Failed repeatedly to write stats, giving up");
break;
}
continue;
} else {
noFailedAttempts = 0;
fprintf(statfile, "ReqQueueLength: %i\n", reqQueueLength);
fprintf(statfile, "ReqPrioQueueLength: %i\n", reqPrioQueueLength);
fprintf(statfile, "ReqBulkQueueLength: %i\n", reqBulkQueueLength);
fprintf(statfile, "DirtQueueLength: %i\n", dirtQueueLength);
fprintf(statfile, "DropedRequest: %li\n", lStats.noReqDroped);
fprintf(statfile, "ReqRendered: %li\n", lStats.noReqRender);
fprintf(statfile, "ReqPrioRendered: %li\n", lStats.noReqPrioRender);
fprintf(statfile, "ReqBulkRendered: %li\n", lStats.noReqBulkRender);
fprintf(statfile, "DirtyRendered: %li\n", lStats.noDirtyRender);
for (i = 0; i <= MAX_ZOOM; i++) {
fprintf(statfile,"ZoomRendered%02i: %li\n", i, lStats.noZoomRender[i]);
}
for (i = 0; i <= MAX_ZOOM; i++) {
fprintf(statfile,"TimeRenderedZoom%02i: %li\n", i, lStats.timeZoomRender[i]);
}
fclose(statfile);
if (rename(tmpName, config.stats_filename)) {
syslog(LOG_WARNING, "Failed to overwrite stats file: %i", errno);
noFailedAttempts++;
if (noFailedAttempts > 3) {
syslog(LOG_ERR, "ERROR: Failed repeatedly to overwrite stats, giving up");
break;
}
continue;
}
}
sleep(10);
}
return NULL;
}
int client_socket_init(renderd_config * sConfig) {
int fd, s;
struct sockaddr_un * addrU;
struct addrinfo hints;
struct addrinfo *result, *rp;
char portnum[16];
char ipstring[INET6_ADDRSTRLEN];
if (sConfig->ipport > 0) {
syslog(LOG_INFO, "Initialising TCP/IP client socket to %s:%i", sConfig->iphostname, sConfig->ipport);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
sprintf(portnum,"%i", sConfig->ipport);
s = getaddrinfo(sConfig->iphostname, portnum, &hints, &result);
if (s != 0) {
syslog(LOG_INFO, "failed to resolve hostname of rendering slave");
return FD_INVALID;
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
inet_ntop(rp->ai_family, rp->ai_family == AF_INET ? &(((struct sockaddr_in *)rp->ai_addr)->sin_addr) :
&(((struct sockaddr_in6 *)rp->ai_addr)->sin6_addr) , ipstring, rp->ai_addrlen);
syslog(LOG_DEBUG, "Connecting TCP socket to rendering daemon at %s", ipstring);
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (fd < 0)
continue;
if (connect(fd, rp->ai_addr, rp->ai_addrlen) != 0) {
syslog(LOG_INFO, "failed to connect to rendering daemon (%s), trying next ip", ipstring);
close(fd);
fd = -1;
continue;
} else {
break;
}
}
freeaddrinfo(result);
if (fd < 0) {
syslog(LOG_WARNING, "failed to connect to %s:%i", sConfig->iphostname, sConfig->ipport);
return FD_INVALID;
}
syslog(LOG_INFO, "socket %s:%i initialised to fd %i", sConfig->iphostname, sConfig->ipport, fd);
} else {
syslog(LOG_INFO, "Initialising unix client socket on %s",
sConfig->socketname);
addrU = (struct sockaddr_un *)malloc(sizeof(struct sockaddr_un));
fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
syslog(LOG_WARNING, "Could not obtain socket: %i", fd);
free(addrU);
return FD_INVALID;
}
bzero(addrU, sizeof(struct sockaddr_un));
addrU->sun_family = AF_UNIX;
strncpy(addrU->sun_path, sConfig->socketname, sizeof(addrU->sun_path) - 1);
if (connect(fd, (struct sockaddr *) addrU, sizeof(struct sockaddr_un)) < 0) {
syslog(LOG_WARNING, "socket connect failed for: %s",
sConfig->socketname);
close(fd);
free(addrU);
return FD_INVALID;
}
free(addrU);
syslog(LOG_INFO, "socket %s initialised to fd %i", sConfig->socketname,
fd);
}
return fd;
}
int server_socket_init(renderd_config *sConfig) {
struct sockaddr_un addrU;
struct sockaddr_in6 addrI;
mode_t old;
int fd;
if (sConfig->ipport > 0) {
syslog(LOG_INFO, "Initialising TCP/IP server socket on %s:%i",
sConfig->iphostname, sConfig->ipport);
fd = socket(PF_INET6, SOCK_STREAM, 0);
if (fd < 0) {
fprintf(stderr, "failed to create IP socket\n");
exit(2);
}
bzero(&addrI, sizeof(addrI));
addrI.sin6_family = AF_INET6;
addrI.sin6_addr = in6addr_any;
addrI.sin6_port = htons(sConfig->ipport);
if (bind(fd, (struct sockaddr *) &addrI, sizeof(addrI)) < 0) {
fprintf(stderr, "socket bind failed for: %s:%i\n",
sConfig->iphostname, sConfig->ipport);
close(fd);
exit(3);
}
} else {
syslog(LOG_INFO, "Initialising unix server socket on %s",
sConfig->socketname);
fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
fprintf(stderr, "failed to create unix socket\n");
exit(2);
}
bzero(&addrU, sizeof(addrU));
addrU.sun_family = AF_UNIX;
strncpy(addrU.sun_path, sConfig->socketname, sizeof(addrU.sun_path) - 1);
unlink(addrU.sun_path);
old = umask(0); // Need daemon socket to be writeable by apache
if (bind(fd, (struct sockaddr *) &addrU, sizeof(addrU)) < 0) {
fprintf(stderr, "socket bind failed for: %s\n", sConfig->socketname);
close(fd);
exit(3);
}
umask(old);
}
if (listen(fd, QUEUE_MAX) < 0) {
fprintf(stderr, "socket listen failed for %d\n", QUEUE_MAX);
close(fd);
exit(4);
}
syslog(LOG_DEBUG, "Created server socket %i", fd);
return fd;
}
/**
* This function is used as a the start function for the slave renderer thread.
* It pulls a request from the central queue of requests and dispatches it to
* the slave renderer. It then blocks and waits for the response with no timeout.
* As it only sends one request at a time (there are as many slave_thread threads as there
* are rendering threads on the slaves) nothing gets queued on the slave and should get
* rendererd immediately. Thus overall, requests should be nicely load balanced between
* all the rendering threads available both locally and in the slaves.
*/
void *slave_thread(void * arg) {
renderd_config * sConfig = (renderd_config *) arg;
int pfd = FD_INVALID;
int retry;
size_t ret_size;
struct protocol * resp;
struct protocol * req_slave;
req_slave = (struct protocol *)malloc(sizeof(struct protocol));
resp = (struct protocol *)malloc(sizeof(struct protocol));
bzero(req_slave, sizeof(struct protocol));
bzero(resp, sizeof(struct protocol));
while (1) {
if (pfd == FD_INVALID) {
pfd = client_socket_init(sConfig);
if (pfd == FD_INVALID) {
if (sConfig->ipport > 0) {
syslog(LOG_ERR,
"Failed to connect to render slave %s:%i, trying again in 30 seconds",
sConfig->iphostname, sConfig->ipport);
} else {
syslog( LOG_ERR,
"Failed to connect to render slave %s, trying again in 30 seconds",
sConfig->socketname);
}
sleep(30);
continue;
}
}
enum protoCmd ret;
struct item *item = fetch_request();
if (item) {
struct protocol *req = &item->req;
req_slave->ver = PROTO_VER;
req_slave->cmd = cmdRender;
strcpy(req_slave->xmlname, req->xmlname);
req_slave->x = req->x;
req_slave->y = req->y;
req_slave->z = req->z;
/*Dispatch request to slave renderd*/
retry = 2;
syslog(LOG_INFO,
"Dispatching request to slave thread on fd %i", pfd);
do {
ret_size = send(pfd, req_slave, sizeof(struct protocol), 0);
if (ret_size == sizeof(struct protocol)) {
//correctly sent command to slave
break;
}
if (errno != EPIPE) {
syslog(LOG_ERR,
"Failed to send cmd to render slave, shutting down thread");
free(resp);
free(req_slave);
close(pfd);
return NULL;
}
syslog(LOG_WARNING, "Failed to send cmd to render slave, retrying");
close(pfd);
pfd = client_socket_init(sConfig);
if (pfd == FD_INVALID) {
syslog(LOG_ERR,
"Failed to re-connect to render slave, dropping request");
ret = cmdNotDone;
send_response(item, ret);
break;
}
} while (retry--);
if (pfd == FD_INVALID || ret_size != sizeof(struct protocol)) {
continue;
}
ret_size = 0;
retry = 10;
while ((ret_size < sizeof(struct protocol)) && (retry > 0)) {
ret_size = recv(pfd, resp + ret_size, (sizeof(struct protocol)
- ret_size), 0);
if ((errno == EPIPE) || ret_size == 0) {
close(pfd);
pfd = FD_INVALID;
ret_size = 0;
syslog(LOG_ERR, "Pipe to render slave closed");
break;
}
retry--;
}
if (ret_size < sizeof(struct protocol)) {
if (sConfig->ipport > 0) {
syslog( LOG_ERR,
"Invalid reply from render slave %s:%i, trying again in 30 seconds",
sConfig->iphostname, sConfig->ipport);
} else {
syslog( LOG_ERR,
"Invalid reply render slave %s, trying again in 30 seconds",
sConfig->socketname);
}
ret = cmdNotDone;
send_response(item, ret);
sleep(30);
} else {
ret = resp->cmd;
send_response(item, ret);
if (resp->cmd != cmdDone) {
if (sConfig->ipport > 0) {
syslog( LOG_ERR,
"Request from render slave %s:%i did not complete correctly",
sConfig->iphostname, sConfig->ipport);
} else {
syslog( LOG_ERR,
"Request from render slave %s did not complete correctly",
sConfig->socketname);
}
//Sleep for a while to make sure we don't overload the renderer
//This only happens if it didn't correctly block on the rendering
//request
sleep(30);
}
}
} else {
sleep(1); // TODO: Use an event to indicate there are new requests
}
}
free(resp);
free(req_slave);
return NULL;
}
int main(int argc, char **argv)
{
int fd, i, j, k;
int c;
int foreground=0;
int active_slave=0;
int log_options;
char config_file_name[PATH_MAX] = RENDERD_CONFIG;
while (1) {
int option_index = 0;
static struct option long_options[] = {
{"config", 1, 0, 'c'},
{"foreground", 1, 0, 'f'},
{"slave", 1, 0, 's'},
{"help", 0, 0, 'h'},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "hfc:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'f':
foreground=1;
break;
case 'c':
strncpy(config_file_name, optarg, PATH_MAX-1);
config_file_name[PATH_MAX-1] = 0;
break;
case 's':
if (sscanf(optarg, "%i", &active_slave) != 1) {
fprintf(stderr, "--slave needs to be nummeric (%s)\n", optarg);
active_slave = 0;
}
break;
case 'h':
fprintf(stderr, "Usage: renderd [OPTION] ...\n");
fprintf(stderr, "Mapnik rendering daemon\n");
fprintf(stderr, " -f, --foreground run in foreground\n");
fprintf(stderr, " -h, --help display this help and exit\n");
fprintf(stderr, " -c, --config=CONFIG set location of config file (default /etc/renderd.conf)\n");
fprintf(stderr, " -s, --slave=CONFIG_NR set which render slave this is (default 0)\n");
exit(0);
default:
fprintf(stderr, "unknown config option '%c'\n", c);
exit(1);
}
}
log_options = LOG_PID;
#ifdef LOG_PERROR
if (foreground)
log_options |= LOG_PERROR;
#endif
openlog("renderd", log_options, LOG_DAEMON);
syslog(LOG_INFO, "Rendering daemon started");
pthread_mutex_init(&qLock, NULL);
pthread_cond_init(&qCond, NULL);
reqHead.next = reqHead.prev = &reqHead;
reqPrioHead.next = reqPrioHead.prev = &reqPrioHead;
reqBulkHead.next = reqBulkHead.prev = &reqBulkHead;
dirtyHead.next = dirtyHead.prev = &dirtyHead;
renderHead.next = renderHead.prev = &renderHead;
hashidxSize = HASHIDX_SIZE;
item_hashidx = (struct item_idx *) malloc(sizeof(struct item_idx) * hashidxSize);
bzero(item_hashidx, sizeof(struct item_idx) * hashidxSize);
stats.noDirtyRender = 0;
stats.noReqDroped = 0;
stats.noReqRender = 0;
stats.noReqPrioRender = 0;
stats.noReqBulkRender = 0;
xmlconfigitem maps[XMLCONFIGS_MAX];
bzero(maps, sizeof(xmlconfigitem) * XMLCONFIGS_MAX);
renderd_config config_slaves[MAX_SLAVES];
bzero(config_slaves, sizeof(renderd_config) * MAX_SLAVES);
bzero(&config, sizeof(renderd_config));
dictionary *ini = iniparser_load(config_file_name);
if (! ini) {
exit(1);
}
noSlaveRenders = 0;
int iconf = -1;
char buffer[PATH_MAX];
for (int section=0; section < iniparser_getnsec(ini); section++) {
char *name = iniparser_getsecname(ini, section);
syslog(LOG_INFO, "Parsing section %s\n", name);
if (strncmp(name, "renderd", 7) && strcmp(name, "mapnik")) {
if (config.tile_dir == NULL) {
fprintf(stderr, "No valid (active) renderd config section available\n");
exit(7);
}
/* this is a map section */
iconf++;
if (iconf >= XMLCONFIGS_MAX) {
fprintf(stderr, "Config: more than %d configurations found\n", XMLCONFIGS_MAX);
exit(7);