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