]> git.sesse.net Git - cubemap/blob - main.cpp
faf4be8ad6e7a07b30204412c9937dfbbb01a634
[cubemap] / main.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <getopt.h>
4 #include <limits.h>
5 #include <signal.h>
6 #include <stddef.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/time.h>
11 #include <sys/wait.h>
12 #include <systemd/sd-daemon.h>
13 #include <unistd.h>
14 #include <algorithm>
15 #include <map>
16 #include <set>
17 #include <string>
18 #include <utility>
19 #include <vector>
20
21 #include "acceptor.h"
22 #include "accesslog.h"
23 #include "config.h"
24 #include "input.h"
25 #include "input_stats.h"
26 #include "log.h"
27 #include "sa_compare.h"
28 #include "serverpool.h"
29 #include "state.pb.h"
30 #include "stats.h"
31 #include "stream.h"
32 #include "util.h"
33 #include "version.h"
34
35 using namespace std;
36
37 AccessLogThread *access_log = NULL;
38 ServerPool *servers = NULL;
39 volatile bool hupped = false;
40 volatile bool stopped = false;
41
42 namespace {
43
44 struct OrderByConnectionTime {
45         bool operator() (const ClientProto &a, const ClientProto &b) const {
46                 if (a.connect_time_sec() != b.connect_time_sec())
47                         return a.connect_time_sec() < b.connect_time_sec();
48                 return a.connect_time_nsec() < b.connect_time_nsec();
49         }
50 };
51
52 }  // namespace
53
54 struct InputWithRefcount {
55         Input *input;
56         int refcount;
57 };
58
59 void hup(int signum)
60 {
61         hupped = true;
62         if (signum == SIGINT) {
63                 stopped = true;
64         }
65 }
66
67 void do_nothing(int signum)
68 {
69 }
70
71 CubemapStateProto collect_state(const timespec &serialize_start,
72                                 const vector<Acceptor *> acceptors,
73                                 const multimap<string, InputWithRefcount> inputs,
74                                 ServerPool *servers)
75 {
76         CubemapStateProto state = servers->serialize();  // Fills streams() and clients().
77         state.set_serialize_start_sec(serialize_start.tv_sec);
78         state.set_serialize_start_usec(serialize_start.tv_nsec / 1000);
79         
80         for (size_t i = 0; i < acceptors.size(); ++i) {
81                 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
82         }
83
84         for (multimap<string, InputWithRefcount>::const_iterator input_it = inputs.begin();
85              input_it != inputs.end();
86              ++input_it) {
87                 state.add_inputs()->MergeFrom(input_it->second.input->serialize());
88         }
89
90         return state;
91 }
92
93 // Find all port statements in the configuration file, and create acceptors for htem.
94 vector<Acceptor *> create_acceptors(
95         const Config &config,
96         map<sockaddr_in6, Acceptor *, Sockaddr6Compare> *deserialized_acceptors)
97 {
98         vector<Acceptor *> acceptors;
99         for (unsigned i = 0; i < config.acceptors.size(); ++i) {
100                 const AcceptorConfig &acceptor_config = config.acceptors[i];
101                 Acceptor *acceptor = NULL;
102                 map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator deserialized_acceptor_it =
103                         deserialized_acceptors->find(acceptor_config.addr);
104                 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
105                         acceptor = deserialized_acceptor_it->second;
106                         deserialized_acceptors->erase(deserialized_acceptor_it);
107                 } else {
108                         int server_sock = create_server_socket(acceptor_config.addr, TCP_SOCKET);
109                         acceptor = new Acceptor(server_sock, acceptor_config.addr);
110                 }
111                 acceptor->run();
112                 acceptors.push_back(acceptor);
113         }
114
115         // Close all acceptors that are no longer in the configuration file.
116         for (map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator
117                  acceptor_it = deserialized_acceptors->begin();
118              acceptor_it != deserialized_acceptors->end();
119              ++acceptor_it) {
120                 acceptor_it->second->close_socket();
121                 delete acceptor_it->second;
122         }
123
124         return acceptors;
125 }
126
127 void create_config_input(const string &src, multimap<string, InputWithRefcount> *inputs)
128 {
129         if (src.empty()) {
130                 return;
131         }
132         if (inputs->count(src) != 0) {
133                 return;
134         }
135
136         InputWithRefcount iwr;
137         iwr.input = create_input(src);
138         if (iwr.input == NULL) {
139                 log(ERROR, "did not understand URL '%s', clients will not get any data.",
140                         src.c_str());
141                 return;
142         }
143         iwr.refcount = 0;
144         inputs->insert(make_pair(src, iwr));
145 }
146
147 // Find all streams in the configuration file, and create inputs for them.
148 void create_config_inputs(const Config &config, multimap<string, InputWithRefcount> *inputs)
149 {
150         for (unsigned i = 0; i < config.streams.size(); ++i) {
151                 const StreamConfig &stream_config = config.streams[i];
152                 if (stream_config.src != "delete") {
153                         create_config_input(stream_config.src, inputs);
154                 }
155         }
156         for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
157                 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
158                 create_config_input(udpstream_config.src, inputs);
159         }
160 }
161
162 void create_streams(const Config &config,
163                     const set<string> &deserialized_urls,
164                     multimap<string, InputWithRefcount> *inputs)
165 {
166         // HTTP streams.
167         set<string> expecting_urls = deserialized_urls;
168         for (unsigned i = 0; i < config.streams.size(); ++i) {
169                 const StreamConfig &stream_config = config.streams[i];
170                 int stream_index;
171
172                 expecting_urls.erase(stream_config.url);
173
174                 // Special-case deleted streams; they were never deserialized in the first place,
175                 // so just ignore them.
176                 if (stream_config.src == "delete") {
177                         continue;
178                 }
179
180                 if (deserialized_urls.count(stream_config.url) == 0) {
181                         stream_index = servers->add_stream(stream_config.url,
182                                                            stream_config.backlog_size,
183                                                            stream_config.prebuffering_bytes,
184                                                            Stream::Encoding(stream_config.encoding));
185                 } else {
186                         stream_index = servers->lookup_stream_by_url(stream_config.url);
187                         assert(stream_index != -1);
188                         servers->set_backlog_size(stream_index, stream_config.backlog_size);
189                         servers->set_prebuffering_bytes(stream_index, stream_config.prebuffering_bytes);
190                         servers->set_encoding(stream_index,
191                                               Stream::Encoding(stream_config.encoding));
192                 }
193
194                 servers->set_pacing_rate(stream_index, stream_config.pacing_rate);
195
196                 string src = stream_config.src;
197                 if (!src.empty()) {
198                         multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
199                         if (input_it != inputs->end()) {
200                                 input_it->second.input->add_destination(stream_index);
201                                 ++input_it->second.refcount;
202                         }
203                 }
204         }
205
206         // Warn about any streams servers we've lost.
207         for (set<string>::const_iterator stream_it = expecting_urls.begin();
208              stream_it != expecting_urls.end();
209              ++stream_it) {
210                 string url = *stream_it;
211                 log(WARNING, "stream '%s' disappeared from the configuration file. "
212                              "It will not be deleted, but clients will not get any new inputs. "
213                              "If you really meant to delete it, set src=delete and reload.",
214                              url.c_str());
215         }
216
217         // UDP streams.
218         for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
219                 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
220                 int stream_index = servers->add_udpstream(
221                         udpstream_config.dst,
222                         udpstream_config.pacing_rate,
223                         udpstream_config.ttl,
224                         udpstream_config.multicast_iface_index);
225
226                 string src = udpstream_config.src;
227                 if (!src.empty()) {
228                         multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
229                         assert(input_it != inputs->end());
230                         input_it->second.input->add_destination(stream_index);
231                         ++input_it->second.refcount;
232                 }
233         }
234
235         // HTTP ping endpoints.
236         for (unsigned i = 0; i < config.pings.size(); ++i) {
237                 const PingConfig &ping_config = config.pings[i];
238                 servers->add_ping(ping_config.url, ping_config.allow_origin);
239         }
240 }
241         
242 void open_logs(const vector<LogConfig> &log_destinations)
243 {
244         for (size_t i = 0; i < log_destinations.size(); ++i) {
245                 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
246                         add_log_destination_file(log_destinations[i].filename);
247                 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
248                         add_log_destination_console();
249                 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
250                         add_log_destination_syslog();
251                 } else {
252                         assert(false);
253                 }
254         }
255         start_logging();
256 }
257         
258 bool dry_run_config(const string &argv0, const string &config_filename)
259 {
260         char *argv0_copy = strdup(argv0.c_str());
261         char *config_filename_copy = strdup(config_filename.c_str());
262
263         pid_t pid = fork();
264         switch (pid) {
265         case -1:
266                 log_perror("fork()");
267                 free(argv0_copy);
268                 free(config_filename_copy);
269                 return false;
270         case 0:
271                 // Child.
272                 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
273                 log_perror(argv0_copy);
274                 _exit(1);
275         default:
276                 // Parent.
277                 break;
278         }
279                 
280         free(argv0_copy);
281         free(config_filename_copy);
282
283         int status;
284         pid_t err;
285         do {
286                 err = waitpid(pid, &status, 0);
287         } while (err == -1 && errno == EINTR);
288
289         if (err == -1) {
290                 log_perror("waitpid()");
291                 return false;
292         }       
293
294         return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
295 }
296
297 void find_deleted_streams(const Config &config, set<string> *deleted_urls)
298 {
299         for (unsigned i = 0; i < config.streams.size(); ++i) {
300                 const StreamConfig &stream_config = config.streams[i];
301                 if (stream_config.src == "delete") {
302                         log(INFO, "Deleting stream '%s'.", stream_config.url.c_str());
303                         deleted_urls->insert(stream_config.url);
304                 }
305         }
306 }
307
308 int main(int argc, char **argv)
309 {
310         signal(SIGHUP, hup);
311         signal(SIGINT, hup);
312         signal(SIGUSR1, do_nothing);  // Used in internal signalling.
313         signal(SIGPIPE, SIG_IGN);
314         
315         // Parse options.
316         int state_fd = -1;
317         bool test_config = false;
318         for ( ;; ) {
319                 static const option long_options[] = {
320                         { "state", required_argument, 0, 's' },
321                         { "test-config", no_argument, 0, 't' },
322                         { 0, 0, 0, 0 }
323                 };
324                 int option_index = 0;
325                 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
326      
327                 if (c == -1) {
328                         break;
329                 }
330                 switch (c) {
331                 case 's':
332                         state_fd = atoi(optarg);
333                         break;
334                 case 't':
335                         test_config = true;
336                         break;
337                 default:
338                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
339                         exit(1);
340                 }
341         }
342
343         string config_filename = "cubemap.config";
344         if (optind < argc) {
345                 config_filename = argv[optind++];
346         }
347
348         // Canonicalize argv[0] and config_filename.
349         char argv0_canon[PATH_MAX];
350         char config_filename_canon[PATH_MAX];
351
352         if (realpath("/proc/self/exe", argv0_canon) == NULL) {
353                 log_perror(argv[0]);
354                 exit(1);
355         }
356         if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
357                 log_perror(config_filename.c_str());
358                 exit(1);
359         }
360
361         // Now parse the configuration file.
362         Config config;
363         if (!parse_config(config_filename_canon, &config)) {
364                 exit(1);
365         }
366         if (test_config) {
367                 exit(0);
368         }
369         
370         // Ideally we'd like to daemonize only when we've started up all threads etc.,
371         // but daemon() forks, which is not good in multithreaded software, so we'll
372         // have to do it here.
373         if (config.daemonize) {
374                 if (daemon(0, 0) == -1) {
375                         log_perror("daemon");
376                         exit(1);
377                 }
378         }
379
380 start:
381         // Open logs as soon as possible.
382         open_logs(config.log_destinations);
383
384         log(INFO, "Cubemap " SERVER_VERSION " starting.");
385         if (config.access_log_file.empty()) {
386                 // Create a dummy logger.
387                 access_log = new AccessLogThread();
388         } else {
389                 access_log = new AccessLogThread(config.access_log_file);
390         }
391         access_log->run();
392
393         servers = new ServerPool(config.num_servers);
394
395         // Find all the streams that are to be deleted.
396         set<string> deleted_urls;
397         find_deleted_streams(config, &deleted_urls);
398
399         CubemapStateProto loaded_state;
400         timespec serialize_start;
401         set<string> deserialized_urls;
402         map<sockaddr_in6, Acceptor *, Sockaddr6Compare> deserialized_acceptors;
403         multimap<string, InputWithRefcount> inputs;  // multimap due to older versions without deduplication.
404         if (state_fd != -1) {
405                 log(INFO, "Deserializing state from previous process...");
406                 string serialized;
407                 if (!read_tempfile_and_close(state_fd, &serialized)) {
408                         exit(1);
409                 }
410                 if (!loaded_state.ParseFromString(serialized)) {
411                         log(ERROR, "Failed deserialization of state.");
412                         exit(1);
413                 }
414
415                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
416                 serialize_start.tv_nsec = loaded_state.serialize_start_usec() * 1000ull;
417
418                 // Deserialize the streams.
419                 map<string, string> stream_headers_for_url;  // See below.
420                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
421                         const StreamProto &stream = loaded_state.streams(i);
422
423                         if (deleted_urls.count(stream.url()) != 0) {
424                                 // Delete the stream backlogs.
425                                 for (int j = 0; j < stream.data_fds_size(); ++j) {
426                                         safe_close(stream.data_fds(j));
427                                 }
428                         } else {
429                                 vector<int> data_fds;
430                                 for (int j = 0; j < stream.data_fds_size(); ++j) {
431                                         data_fds.push_back(stream.data_fds(j));
432                                 }
433
434                                 servers->add_stream_from_serialized(stream, data_fds);
435                                 deserialized_urls.insert(stream.url());
436
437                                 stream_headers_for_url.insert(make_pair(stream.url(), stream.stream_header()));
438                         }
439                 }
440
441                 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
442                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
443                         InputProto serialized_input = loaded_state.inputs(i);
444
445                         InputWithRefcount iwr;
446                         iwr.input = create_input(serialized_input);
447                         iwr.refcount = 0;
448                         inputs.insert(make_pair(serialized_input.url(), iwr));
449                 } 
450
451                 // Deserialize the acceptors.
452                 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
453                         sockaddr_in6 sin6 = extract_address_from_acceptor_proto(loaded_state.acceptors(i));
454                         deserialized_acceptors.insert(make_pair(
455                                 sin6,
456                                 new Acceptor(loaded_state.acceptors(i))));
457                 }
458
459                 log(INFO, "Deserialization done.");
460         }
461
462         // Add any new inputs coming from the config.
463         create_config_inputs(config, &inputs);
464         
465         // Find all streams in the configuration file, create them, and connect to the inputs.
466         create_streams(config, deserialized_urls, &inputs);
467         vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
468
469         // Convert old-style timestamps to new-style timestamps for all clients;
470         // this simplifies the sort below.
471         {
472                 timespec now_monotonic;
473                 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now_monotonic) == -1) {
474                         log(ERROR, "clock_gettime(CLOCK_MONOTONIC_COARSE) failed.");
475                         exit(1);
476                 }
477                 long delta_sec = now_monotonic.tv_sec - time(NULL);
478
479                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
480                         ClientProto* client = loaded_state.mutable_clients(i);
481                         if (client->has_connect_time_old()) {
482                                 client->set_connect_time_sec(client->connect_time_old() + delta_sec);
483                                 client->set_connect_time_nsec(now_monotonic.tv_nsec);
484                                 client->clear_connect_time_old();
485                         }
486                 }
487         }
488         
489         // Put back the existing clients. It doesn't matter which server we
490         // allocate them to, so just do round-robin. However, we need to sort them
491         // by connection time first, since add_client_serialized() expects that.
492         sort(loaded_state.mutable_clients()->begin(),
493              loaded_state.mutable_clients()->end(),
494              OrderByConnectionTime());
495         for (int i = 0; i < loaded_state.clients_size(); ++i) {
496                 if (deleted_urls.count(loaded_state.clients(i).url()) != 0) {
497                         safe_close(loaded_state.clients(i).sock());
498                 } else {
499                         servers->add_client_from_serialized(loaded_state.clients(i));
500                 }
501         }
502         
503         servers->run();
504
505         // Now delete all inputs that are longer in use, and start the others.
506         for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
507              input_it != inputs.end(); ) {
508                 if (input_it->second.refcount == 0) {
509                         log(WARNING, "Input '%s' no longer in use, closing.",
510                             input_it->first.c_str());
511                         input_it->second.input->close_socket();
512                         delete input_it->second.input;
513                         inputs.erase(input_it++);
514                 } else {
515                         input_it->second.input->run();
516                         ++input_it;
517                 }
518         }
519
520         // Start writing statistics.
521         StatsThread *stats_thread = NULL;
522         if (!config.stats_file.empty()) {
523                 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
524                 stats_thread->run();
525         }
526
527         InputStatsThread *input_stats_thread = NULL;
528         if (!config.input_stats_file.empty()) {
529                 vector<Input*> inputs_no_refcount;
530                 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
531                      input_it != inputs.end(); ++input_it) {
532                         inputs_no_refcount.push_back(input_it->second.input);
533                 }
534
535                 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
536                 input_stats_thread->run();
537         }
538
539         timespec server_start;
540         int err = clock_gettime(CLOCK_MONOTONIC, &server_start);
541         assert(err != -1);
542         if (state_fd != -1) {
543                 // Measure time from we started deserializing (below) to now, when basically everything
544                 // is up and running. This is, in other words, a conservative estimate of how long our
545                 // “glitch” period was, not counting of course reconnects if the configuration changed.
546                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
547                         1e-9 * (server_start.tv_nsec - serialize_start.tv_nsec);
548                 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
549         }
550
551         sd_notify(0, "READY=1");
552
553         while (!hupped) {
554                 usleep(100000);
555         }
556
557         if (stopped) {
558                 sd_notify(0, "STOPPING=1");
559         } else {
560                 sd_notify(0, "RELOADING=1");
561         }
562
563         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
564         err = clock_gettime(CLOCK_MONOTONIC, &serialize_start);
565         assert(err != -1);
566
567         if (input_stats_thread != NULL) {
568                 input_stats_thread->stop();
569                 delete input_stats_thread;
570         }
571         if (stats_thread != NULL) {
572                 stats_thread->stop();
573                 delete stats_thread;
574         }
575         for (size_t i = 0; i < acceptors.size(); ++i) {
576                 acceptors[i]->stop();
577         }
578         for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
579              input_it != inputs.end();
580              ++input_it) {
581                 input_it->second.input->stop();
582         }
583         servers->stop();
584
585         CubemapStateProto state;
586         if (stopped) {
587                 log(INFO, "Shutting down.");
588         } else {
589                 log(INFO, "Serializing state and re-execing...");
590                 state = collect_state(
591                         serialize_start, acceptors, inputs, servers);
592                 string serialized;
593                 state.SerializeToString(&serialized);
594                 state_fd = make_tempfile(serialized);
595                 if (state_fd == -1) {
596                         exit(1);
597                 }
598         }
599         delete servers;
600
601         access_log->stop();
602         delete access_log;
603         shut_down_logging();
604
605         if (stopped) {
606                 exit(0);
607         }
608
609         // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
610         if (!dry_run_config(argv0_canon, config_filename_canon)) {
611                 open_logs(config.log_destinations);
612                 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
613                 hupped = false;
614                 shut_down_logging();
615                 goto start;
616         }
617          
618         char buf[16];
619         sprintf(buf, "%d", state_fd);
620
621         for ( ;; ) {
622                 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
623                 open_logs(config.log_destinations);
624                 log_perror("execlp");
625                 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);
626                 shut_down_logging();
627                 usleep(200000);
628         }
629 }