-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphp-master.cpp
More file actions
1908 lines (1578 loc) · 50.4 KB
/
php-master.cpp
File metadata and controls
1908 lines (1578 loc) · 50.4 KB
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
/*
$Author = Sargis Ananyan;
$Corp = RedM Inc;
$Web = https://redm.pro/;
$Lincese = BSD 3;
$Name = mLang;
$Description = A programming language for web programming.;
*/
#define _FILE_OFFSET_BITS 64
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/signalfd.h>
#include <poll.h>
#include <string>
#include <algorithm>
#include "php-master.h"
extern "C" {
#include "kdb-data-common.h"
#include "server-functions.h"
#include "net-events.h"
#include "net-connections.h"
#include "net-memcache-server.h"
#include "net-rpc-client.h"
#include "net-rpc-server.h"
#include "net-rpc-common.h"
#include "vv-tl-parse.h"
#include "vv-tl-aio.h"
#include "php-engine-vars.h"
#include "dl-utils-lite.h"
extern const char *engine_tag;
}
//do not kill more then MAX_KILL at the same time
#define MAX_KILL 5
//ATTENTION: the file has .cpp extention due to usage of "pthread_mutexattr_setrobust_np" which is by some strange reason unsupported for .c
//ATTENTION: do NOT change this structures without changing the magic
#define SHARED_DATA_MAGIC 0x3b720002
#define PHP_MASTER_VERSION "0.1"
static int save_verbosity;
typedef struct {
int valid_flag;
pid_t pid;
unsigned long long start_time;
long long rate;
long long generation;
int running_workers_n;
int dying_workers_n;
int to_kill;
long long to_kill_generation;
int own_http_fd;
int http_fd_port;
int ask_http_fd_generation;
int sent_http_fd_generation;
int reserved[50];
} master_data_t;
typedef struct {
int magic;
int is_inited;
int init_owner;
pthread_mutex_t main_mutex;
pthread_cond_t main_cond;
int id;
master_data_t masters[2];
} shared_data_t;
static std::string socket_name, shmem_name;
static int cpu_cnt;
static sigset_t mask;
static sigset_t orig_mask;
static sigset_t empty_mask;
static shared_data_t *shared_data;
static master_data_t *me, *other;
static double my_now;
/*** Shared data functions ***/
void mem_info_add (mem_info_t *dst, const mem_info_t &other) {
dst->vm_peak += other.vm_peak;
dst->vm += other.vm;
dst->rss_peak += other.rss_peak;
dst->rss += other.rss;
}
/*** Stats ***/
long tot_workers_started;
long tot_workers_dead;
long tot_workers_strange_dead;
long workers_killed;
long workers_hung;
long workers_terminated;
long workers_failed;
void acc_stats_update (acc_stats_t *to, const acc_stats_t &from) {
to->tot_queries += from.tot_queries;
to->worked_time += from.worked_time;
to->net_time += from.net_time;
to->script_time += from.script_time;
to->tot_script_queries += from.tot_script_queries;
to->tot_idle_time += from.tot_idle_time;
to->tot_idle_percent += from.tot_idle_percent;
to->a_idle_percent += from.a_idle_percent;
to->cnt++;
}
std::string acc_stats_to_str (std::string pid_s, const acc_stats_t &acc) {
char buf[1000];
std::string res;
int cnt = acc.cnt;
if (cnt == 0) {
cnt = 1;
}
sprintf (buf, "tot_queries%s\t%ld\n", pid_s.c_str(), acc.tot_queries);
res += buf;
sprintf (buf, "worked_time%s\t%.3lf\n", pid_s.c_str(), acc.worked_time);
res += buf;
sprintf (buf, "net_time%s\t%.3lf\n", pid_s.c_str(), acc.net_time);
res += buf;
sprintf (buf, "script_time%s\t%.3lf\n", pid_s.c_str(), acc.script_time);
res += buf;
sprintf (buf, "tot_script_queries%s\t%ld\n", pid_s.c_str(), acc.tot_script_queries);
res += buf;
sprintf (buf, "tot_idle_time%s\t%.3lf\n", pid_s.c_str(), acc.tot_idle_time);
res += buf;
sprintf (buf, "tot_idle_percent%s\t%.3lf%%\n", pid_s.c_str(), acc.tot_idle_percent / cnt);
res += buf;
sprintf (buf, "recent_idle_percent%s\t%.3lf%%\n", pid_s.c_str(), acc.a_idle_percent / cnt);
res += buf;
return res;
}
struct CpuStatTimestamp {
double timestamp;
unsigned long long utime;
unsigned long long stime;
unsigned long long total_time;
CpuStatTimestamp(){
}
CpuStatTimestamp (double timestamp, unsigned long long utime,
unsigned long long stime, unsigned long long total_time)
: timestamp (timestamp), utime (utime), stime (stime), total_time (total_time) {
}
};
struct CpuStat {
double cpu_usage;
double cpu_u_usage;
double cpu_s_usage;
CpuStat()
: cpu_usage (0),
cpu_u_usage (0),
cpu_s_usage (0) {
}
CpuStat (const CpuStatTimestamp &from, const CpuStatTimestamp &to) {
unsigned long long total_diff = to.total_time - from.total_time;
cpu_u_usage = (double)(to.utime - from.utime) / (double)total_diff;
cpu_s_usage = (double)(to.stime - from.stime) / (double)total_diff;
cpu_usage = cpu_u_usage + cpu_s_usage;
}
};
struct CpuStatSegment {
typedef CpuStat Stat;
CpuStatTimestamp first, last;
void init (const CpuStatTimestamp &from) {
first = from;
last = from;
}
void update (const CpuStatTimestamp &from) {
last = from;
}
double duration() {
return last.timestamp - first.timestamp;
}
Stat get_stat() {
return Stat (first, last);
}
};
struct MiscStat {
int running_workers_max;
double running_workers_avg;
};
struct MiscStatTimestamp {
double timestamp;
int running_workers;
MiscStatTimestamp (double timestamp, int running_workers)
: timestamp (timestamp), running_workers (running_workers) {
}
};
struct MiscStatSegment {
typedef MiscStat Stat;
unsigned long long stat_cnt;
unsigned long long running_workers_sum;
int running_workers_max;
double first_timestamp, last_timestamp;
void update (const MiscStatTimestamp &from) {
last_timestamp = from.timestamp;
stat_cnt++;
running_workers_sum += from.running_workers;
if (from.running_workers > running_workers_max) {
running_workers_max = from.running_workers;
}
}
void init (const MiscStatTimestamp &from) {
stat_cnt = 0;
running_workers_max = 0;
running_workers_sum = 0;
first_timestamp = from.timestamp;
update (from);
}
double duration() {
return last_timestamp - first_timestamp;
}
MiscStat get_stat() {
MiscStat res;
res.running_workers_max = running_workers_max;
res.running_workers_avg = stat_cnt != 0 ? (double)running_workers_sum / (double)stat_cnt: -1.0;
return res;
}
};
template <class StatSegment, class StatTimestamp>
struct StatImpl {
StatSegment first, second;
double period;
bool is_inited;
StatImpl ()
: period ((double)60 * 60 * 24 * 100000), is_inited (false) {
}
void set_period (double new_period) {
period = new_period;
}
void add_timestamp (const StatTimestamp &new_timestamp) {
if (!is_inited) {
first.init (new_timestamp);
second.init (new_timestamp);
is_inited = true;
return;
}
first.update (new_timestamp);
second.update (new_timestamp);
if (second.duration() > period) {
first = second;
second.init (new_timestamp);
}
}
typename StatSegment::Stat get_stat (void) {
if (!is_inited) {
return typename StatSegment::Stat();
}
return first.get_stat();
}
};
const int periods_n = 4;
const double periods_len[] = {0, 60, 60 * 10, 60 * 60};
const char *periods_desc[] = {"now", "1m", "10m", "1h"};
struct Stats {
std::string engine_stats;
std::string cpu_desc, misc_desc;
php_immediate_stats_t istats;
mem_info_t mem_info;
StatImpl <CpuStatSegment, CpuStatTimestamp> cpu[periods_n];
StatImpl <MiscStatSegment, MiscStatTimestamp> misc[periods_n];
acc_stats_t acc_stats;
Stats() {
for (int i = 0; i < periods_n; i++) {
cpu[i].set_period (periods_len[i]);
misc[i].set_period (periods_len[i]);
}
for (int i = 0; i < periods_n; i++) {
if (!cpu_desc.empty()) {
cpu_desc += ",";
}
cpu_desc += periods_desc[i];
}
for (int i = 1; i < periods_n; i++) {
if (!misc_desc.empty()) {
misc_desc += ",";
}
misc_desc += periods_desc[i];
}
memset (&istats, 0, sizeof (istats));
memset (&acc_stats, 0, sizeof (acc_stats));
}
void update (const CpuStatTimestamp &cpu_timestamp) {
for (int i = 0; i < periods_n; i++) {
cpu[i].add_timestamp (cpu_timestamp);
}
}
void update (const MiscStatTimestamp &misc_timestamp) {
for (int i = 1; i < periods_n; i++) {
misc[i].add_timestamp (misc_timestamp);
}
}
std::string to_string (int pid, bool full_flag = true, bool is_main = false) {
std::string res;
if (full_flag) {
res += engine_stats;
}
char buffer[1000];
std::string pid_s;
if (!is_main) {
assert (snprintf (buffer, 1000, " %d", pid) < 1000);
pid_s = buffer;
}
// sprintf (buffer, "is_running = %d\n", istats.is_running);
// sprintf (buffer, "is_paused = %d\n", istats.is_wait_net);
std::string cpu_vals;
for (int i = 0; i < periods_n; i++) {
CpuStat s = cpu[i].get_stat();
sprintf (buffer, " %6.2lf%%", cpu_cnt * (s.cpu_usage * 100));
cpu_vals += buffer;
}
res += "cpu_usage" + pid_s + "(" + cpu_desc + ")\t" + cpu_vals + "\n";
sprintf (buffer, "VM%s\t%lluKb\n", pid_s.c_str(), mem_info.vm);
res += buffer;
sprintf (buffer, "VM_max%s\t%lluKb\n", pid_s.c_str(), mem_info.vm_peak);
res += buffer;
sprintf (buffer, "RSS%s\t%lluKb\n", pid_s.c_str(), mem_info.rss);
res += buffer;
sprintf (buffer, "RSS_max%s\t%lluKb\n", pid_s.c_str(), mem_info.rss_peak);
res += buffer;
if (is_main) {
std::string running_workers_max_vals;
std::string running_workers_avg_vals;
for (int i = 1; i < periods_n; i++) {
MiscStat s = misc[i].get_stat();
sprintf (buffer, " %7.3lf", s.running_workers_avg);
running_workers_avg_vals += buffer;
sprintf (buffer, " %7d", s.running_workers_max);
running_workers_max_vals += buffer;
}
res += "running_workers_avg" + pid_s + "(" + misc_desc + ")\t" + running_workers_avg_vals + "\n";
res += "running_workers_max" + pid_s + "(" + misc_desc + ")\t" + running_workers_max_vals + "\n";
}
if (full_flag) {
res += acc_stats_to_str (pid_s, acc_stats);
}
return res;
}
};
void init_mutex (pthread_mutex_t *mutex) {
pthread_mutexattr_t attr;
int err;
err = pthread_mutexattr_init (&attr);
assert (err == 0 && "failed to init mutexattr");
err = pthread_mutexattr_setrobust_np (&attr, PTHREAD_MUTEX_ROBUST_NP);
assert (err == 0 && "failed to setrobust_np for mutex");
err = pthread_mutexattr_setpshared (&attr, PTHREAD_PROCESS_SHARED);
assert (err == 0 && "failed to setpshared for mutex");
err = pthread_mutex_init (mutex, &attr);
assert (err == 0 && "failed to init mutex");
}
void shared_data_init (shared_data_t *data) {
vkprintf (2, "Init shared data: begin\n");
init_mutex (&data->main_mutex);
data->magic = SHARED_DATA_MAGIC;
data->is_inited = 1;
vkprintf (2, "Init shared data: end\n");
}
shared_data_t *get_shared_data (const char *name) {
int ret;
vkprintf (2, "Get shared data: begin\n");
int fid = shm_open (name, O_RDWR, 0777);
int init_flag = 0;
if (fid == -1) {
if (errno == ENOENT) {
vkprintf (1, "shared memory entry is not exists\n");
vkprintf (1, "create shared memory\n");
fid = shm_open (name, O_RDWR | O_CREAT | O_EXCL, 0777);
if (fid == -1) {
vkprintf (1, "failed to create shared memory\n");
assert (errno == EEXIST && "failed to created shared memory for unknown reason");
vkprintf (1, "somebody created it before us! so lets just open it\n");
fid = shm_open (name, O_RDWR, 0777);
assert (fid != -1 && "failed to open shared memory");
} else {
init_flag = 1;
}
}
}
assert (fid != -1);
size_t mem_len = sizeof (shared_data_t);
ret = ftruncate (fid, mem_len);
assert (ret == 0 && "failed to ftruncate shared memory");
shared_data_t *data = (shared_data_t *)mmap (0, mem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fid, 0);
assert (data != MAP_FAILED && "failed to mmap shared memory");
if (init_flag) {
shared_data_init (data);
} else {
if (data->is_inited == 0) {
vkprintf (1, "somebody is trying to init shared data right now. lets wait for a second\n");
sleep (1);
}
assert (data->is_inited == 1 && "shared data is not inited yet");
//TODO: handle this without assert. Use magic in shared_data_t
assert (data->magic == SHARED_DATA_MAGIC && "wrong magic in shared data");
}
vkprintf (1, "Get shared data: end\n");
return data;
}
void shared_data_lock (shared_data_t *data) {
int err = pthread_mutex_lock (&data->main_mutex);
if (err != 0) {
if (err == EOWNERDEAD) {
vkprintf (1, "owner of shared memory mutex is dead. trying to make mutex and memory consitent\n");
err = pthread_mutex_consistent_np (&data->main_mutex);
assert (err == 0 && "failed to make mutex constistent_np");
} else {
assert (0 && "unknown mutex lock error");
}
}
}
void shared_data_unlock (shared_data_t *data) {
int err = pthread_mutex_unlock (&data->main_mutex);
assert (err == 0 && "unknown mutex unlock error");
}
void master_data_remove_if_dead (master_data_t *master) {
if (master->valid_flag) {
unsigned long long start_time = get_pid_start_time (master->pid);
if (start_time != master->start_time) {
master->valid_flag = 0;
dl_assert (me == NULL || master != me, dl_pstr ("[start_time = %llu] [master->start_time = %llu]",
start_time, master->start_time));
}
}
}
void shared_data_update (shared_data_t *shared_data) {
master_data_remove_if_dead (&shared_data->masters[0]);
master_data_remove_if_dead (&shared_data->masters[1]);
}
void shared_data_get_masters (shared_data_t *shared_data, master_data_t **me, master_data_t **other) {
*me = NULL;
if (shared_data->masters[0].valid_flag == 0) {
*me = &shared_data->masters[0];
*other = &shared_data->masters[1];
} else if (shared_data->masters[1].valid_flag == 0) {
*me = &shared_data->masters[1];
*other = &shared_data->masters[0];
}
}
void master_init (master_data_t *me, master_data_t *other) {
assert (me != NULL);
memset (me, 0, sizeof (*me));
if (other->valid_flag) {
me->rate = other->rate + 1;
} else {
me->rate = 1;
}
me->pid = getpid();
me->start_time = get_pid_start_time (me->pid);
assert (me->start_time != 0);
if (other->valid_flag) {
me->generation = other->generation + 1;
} else {
me->generation = 1;
}
me->running_workers_n = 0;
me->dying_workers_n = 0;
me->to_kill = 0;
me->own_http_fd = 0;
me->http_fd_port = -1;
me->ask_http_fd_generation = 0;
me->sent_http_fd_generation = 0;
me->valid_flag = 1; //NB: must be the last operation.
}
void run_master();
static volatile long long local_pending_signals = 0;
static void sigusr1_handler (const int sig) {
const char message[] = "got SIGUSR1, rotate logs.\n";
kwrite (2, message, sizeof (message) - (size_t)1);
local_pending_signals |= (1ll << sig);
dl_signal (sig, sigusr1_handler);
}
struct worker_stats_t {
long long total_cpu_time;
long long used_cpu_time;
long long total_queries;
long long total_time;
};
typedef enum {mst_on, mst_off} master_state_t;
#define MAX_WORKER_STATS_LEN 10000
//TODO: save it as pointer
typedef struct {
int pipe_read;
int pipe_in_packet_num;
int pipe_out_packet_num;
struct connection *reader;
struct connection pending_stat_queue;
} pipe_info_t;
typedef struct worker_info_tmp_t {
worker_info_tmp_t *next_worker;
int generation;
pid_t pid;
int is_dying;
double last_activity_time;
double start_time;
double kill_time;
int kill_flag;
int stats_flag;
pipe_info_t pipes[2];
pid_info_t my_info;
int valid_my_info;
int logname_id;
Stats *stats;
} worker_info_t;
static worker_info_t *workers[MAX_WORKERS];
static int worker_ids[MAX_WORKERS];
static int worker_ids_n;
static Stats stats;
static unsigned long long dead_stime, dead_utime;
static int me_workers_n;
static int me_running_workers_n;
static int me_dying_workers_n;
static double last_failed;
static int *http_fd;
static int http_fd_port;
static int (*try_get_http_fd)(void);
static master_state_t state;
static int signal_fd;
static int changed = 0;
static int failed = 0;
static int socket_fd = -1;
static int to_kill = 0, to_run = 0, to_exit = 0;
static long long generation;
static int receive_fd_attempts_cnt = 0;
static worker_info_t *free_workers = NULL;
void worker_init (worker_info_t *w) {
w->stats = new Stats();
w->valid_my_info = 0;
}
void worker_free (worker_info_t *w) {
delete w->stats;
w->stats = NULL;
}
worker_info_t *new_worker() {
worker_info_t *w = free_workers;
if (w == NULL) {
w = (worker_info_t *)zmalloc0 (sizeof (worker_info_t));
} else {
free_workers = free_workers->next_worker;
}
worker_init (w);
return w;
}
int get_logname_id() {
assert (worker_ids_n > 0);
return worker_ids[--worker_ids_n];
}
void add_logname_id (int id) {
assert (worker_ids_n < MAX_WORKERS);
worker_ids[worker_ids_n++] = id;
}
void delete_worker (worker_info_t *w) {
add_logname_id (w->logname_id);
if (w->valid_my_info) {
dead_utime += w->my_info.utime;
dead_stime += w->my_info.stime;
}
worker_free (w);
w->next_worker = free_workers;
free_workers = w;
}
void start_master (int *new_http_fd, int (*new_try_get_http_fd)(void), int new_http_fd_port) {
save_verbosity = verbosity;
if (verbosity < 1) {
//verbosity = 1;
}
for (int i = MAX_WORKERS - 1; i >= 0; i--) {
add_logname_id (i);
}
std::string s = cluster_name;
for (int i = 0; i < (int)s.size(); i++) {
if (!((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z') || s[i] == '_')) {
s[i] = '_';
}
}
shmem_name = std::string() + "/" + s + "_mlang_shm";
socket_name = std::string() + s + "_mlang_fd_transfer";
dl_assert (shmem_name.size() < NAME_MAX, "too long name for shared memory file");
dl_assert (socket_name.size() < NAME_MAX, "too long socket name (for fd transfer)");
printf ("[%s] [%s]\n", shmem_name.c_str(), socket_name.c_str());
http_fd = new_http_fd;
http_fd_port = new_http_fd_port;
try_get_http_fd = new_try_get_http_fd;
vkprintf (1, "start master: begin\n");
sigemptyset (&empty_mask);
//currently all signals are blocked
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
sigaddset (&mask, SIGPOLL);
signal_fd = signalfd (-1, &mask, SFD_NONBLOCK);
dl_passert (signal_fd >= 0, "failed to create signalfd");
dl_signal (SIGUSR1, sigusr1_handler);
//allow all signals except SIGPOLL and SIGCHLD
if (sigprocmask (SIG_SETMASK, &mask, &orig_mask) < 0) {
perror ("sigprocmask");
_exit (1);
}
//TODO: other signals, daemonize, change user...
if (shared_data == NULL) {
shared_data = get_shared_data (shmem_name.c_str());
}
int attempts_to_start = 2;
int is_inited = 0;
while (attempts_to_start-- > 0) {
vkprintf (1, "attemt to init master. [left attempts = %d]\n", attempts_to_start);
shared_data_lock (shared_data);
shared_data_update (shared_data);
shared_data_get_masters (shared_data, &me, &other);
if (me != NULL) {
master_init (me, other);
is_inited = 1;
}
shared_data_unlock (shared_data);
if (!is_inited) {
vkprintf (1, "other restart is in progress. sleep 5 seconds. [left attempts = %d]\n", attempts_to_start);
sleep (5);
} else {
break;
}
}
if (!is_inited) {
vkprintf (0, "Failed to init master. It seems that two other masters are running\n");
_exit (1);
}
vkprintf (1, "start master: end\n");
run_master();
}
void terminate_worker (worker_info_t *w) {
vkprintf (1, "kill_worker: send SIGTERM to [pid = %d]\n", (int)w->pid);
kill (w->pid, SIGTERM);
w->is_dying = 1;
w->kill_time = my_now + 35;
w->kill_flag = 0;
workers_terminated++;
me_running_workers_n--;
me_dying_workers_n++;
changed = 1;
}
int kill_worker (void) {
int i;
for (i = 0; i < me_workers_n; i++) {
if (!workers[i]->is_dying) {
terminate_worker (workers[i]);
return 1;
}
}
return 0;
}
#define MAX_HANGING_TIME 65.0
void kill_hanging_workers (void) {
int i;
static double last_terminated = -1;
if (last_terminated + 30 < my_now) {
for (i = 0; i < me_workers_n; i++) {
if (!workers[i]->is_dying && workers[i]->last_activity_time + MAX_HANGING_TIME <= my_now) {
vkprintf (1, "No stats recieved from worker [pid = %d]. Terminate it\n", (int)workers[i]->pid);
workers_hung++;
terminate_worker (workers[i]);
last_terminated = my_now;
break;
}
}
}
for (i = 0; i < me_workers_n; i++) {
if (workers[i]->is_dying && workers[i]->kill_time <= my_now && workers[i]->kill_flag == 0) {
vkprintf (1, "kill_hanging_worker: send SIGKILL to [pid = %d]\n", (int)workers[i]->pid);
kill (workers[i]->pid, SIGKILL);
workers_killed++;
workers[i]->kill_flag = 1;
changed = 1;
}
}
}
void workers_send_signal (int sig) {
int i;
for (i = 0; i < me_workers_n; i++) {
if (!workers[i]->is_dying) {
kill (workers[i]->pid, sig);
}
}
}
void pipe_on_get_packet (pipe_info_t *p, int packet_num) {
assert (packet_num > p->pipe_in_packet_num);
p->pipe_in_packet_num = packet_num;
struct connection *c = &p->pending_stat_queue;
while (c->first_query != (struct conn_query *)c) {
struct conn_query *q = c->first_query;
dl_assert (q != NULL, "...");
dl_assert (q->requester != NULL, "...");
// fprintf (stderr, "processing delayed query %p for target %p initiated by %p (%d:%d<=%d)\n", q, c->target, q->requester, q->requester->fd, q->req_generation, q->requester->generation);
if (q->requester->generation == q->req_generation) {
int need_packet_num = *(int *)&q->extra;
//vkprintf (1, "%d vs %d\n", need_packet_num, packet_num);
//use sign of difference to handle int overflow
int diff = packet_num - need_packet_num;
assert (abs (diff) < 1000000000);
if (diff >= 0) {
assert (diff == 0);
//TODO: use PMM_DATA (q->requester);
q->cq_type->close (q);
} else {
break;
}
} else {
q->cq_type->close (q);
}
}
}
void worker_set_stats (worker_info_t *w, const char *data) {
acc_stats_t *acc_stats = (acc_stats_t *) data;
w->stats->acc_stats = *acc_stats;
data += sizeof (acc_stats_t);
w->stats->engine_stats = data;
}
void worker_set_immediate_stats (worker_info_t *w, php_immediate_stats_t *istats) {
w->stats->istats = *istats;
}
/*** PIPE connection ***/
struct pr_data {
worker_info_t *worker;
int worker_generation;
pipe_info_t *pipe_info;
};
#define PR_DATA(c) ((struct pr_data *)(RPCC_DATA (c) + 1))
int pr_execute (struct connection *c, int op, int len) {
vkprintf (3, "pr_execute: fd=%d, op=%d, len=%d\n", c->fd, op, len);
int head[5];
nb_iterator_t Iter;
char *data;
int data_len;
switch (op) {
case RPC_PHP_FULL_STATS:
case RPC_PHP_IMMEDIATE_STATS:
assert (len % (int)sizeof (int) == 0);
len /= (int)sizeof (int);
assert (len >= 3);
nbit_set (&Iter, &c->In);
assert (nbit_read_in (&Iter, head, sizeof (int) * 3) == sizeof (int) * 3);
int packet_num = head[1];
//long long id = *(long long *)(&head[3]);
data_len = len - 3 - 1;
data = (char *)malloc (sizeof (int) * data_len);
assert (nbit_read_in (&Iter, data, data_len * (int)sizeof (int)));
nbit_clear (&Iter);
worker_info_t *w = PR_DATA (c)->worker;
pipe_info_t *p = PR_DATA (c)->pipe_info;
if (w->generation == PR_DATA (c)->worker_generation) {
if (op == RPC_PHP_FULL_STATS) {
w->last_activity_time = my_now;
worker_set_stats (w, data);
}
if (op == RPC_PHP_IMMEDIATE_STATS) {
worker_set_immediate_stats (w, (php_immediate_stats_t *)data);
}
pipe_on_get_packet (p, packet_num);
} else {
vkprintf (1, "connection [%p:%d] will be closed soon\n", c, c->fd);
}
free (data);
break;
}
return SKIP_ALL_BYTES;
}
struct rpc_client_functions pipe_reader_methods;
void init_pipe_reader_methods (void) {
pipe_reader_methods.execute = pr_execute;
}
struct connection *create_pipe_reader (int pipe_fd, conn_type_t *type, void *extra) {
//fprintf (stderr, "create_pipe_reader [%d]\n", pipe_fd);
if (check_conn_functions (type) < 0) {
return NULL;
}
if (pipe_fd >= MAX_CONNECTIONS || pipe_fd < 0) {
return NULL;
}
event_t *ev;
struct connection *c;
ev = Events + pipe_fd;
c = Connections + pipe_fd;
memset (c, 0, sizeof (struct connection));
c->fd = pipe_fd;
c->ev = ev;
//c->target = NULL;
c->generation = ++conn_generation;
c->flags = C_WANTRD;
init_builtin_buffer (&c->In, c->in_buff, BUFF_SIZE);
init_builtin_buffer (&c->Out, c->out_buff, BUFF_SIZE);
c->timer.wakeup = conn_timer_wakeup_gateway;
c->type = type;
c->extra = extra;
c->basic_type = ct_pipe; //why not?
c->status = conn_wait_answer;
active_connections++;
c->first_query = c->last_query = (struct conn_query *) c;
//assert (c->type->init_outbound (c) >= 0);
//fprintf (stderr, "epoll_sethandler\n");
epoll_sethandler (pipe_fd, 0, server_read_write_gateway, c);
//fprintf (stderr, "epoll_insert");
epoll_insert (pipe_fd, (c->flags & C_WANTRD ? EVT_READ : 0) | (c->flags & C_WANTWR ? EVT_WRITE : 0) | EVT_SPEC);
//fprintf (stderr, "exit create_pipe_reader [c = %p]\n", c);
return c;
}
void init_pipe_info (pipe_info_t *info, worker_info_t *worker, int pipe) {
info->pipe_read = pipe;
info->pipe_out_packet_num = -1;
info->pipe_in_packet_num = -1;
struct connection *reader = create_pipe_reader (pipe, &ct_rpc_client, (void *)&pipe_reader_methods);
if (reader != NULL) {
PR_DATA (reader)->worker = worker;
PR_DATA (reader)->worker_generation = worker->generation;
PR_DATA (reader)->pipe_info = info;
} else {
vkprintf (0, "failed to create pipe_reader [fd = %d]", pipe);
}
info->reader = reader;
struct connection *c = &info->pending_stat_queue;