]> git.sesse.net Git - cubemap/blob - main.cpp
Split HTTP header parsing into a common function.
[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 timeval &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_usec);
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_encoding(stream_index,
189                                               Stream::Encoding(stream_config.encoding));
190                 }
191
192                 servers->set_pacing_rate(stream_index, stream_config.pacing_rate);
193
194                 string src = stream_config.src;
195                 if (!src.empty()) {
196                         multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
197                         if (input_it != inputs->end()) {
198                                 input_it->second.input->add_destination(stream_index);
199                                 ++input_it->second.refcount;
200                         }
201                 }
202         }
203
204         // Warn about any streams servers we've lost.
205         for (set<string>::const_iterator stream_it = expecting_urls.begin();
206              stream_it != expecting_urls.end();
207              ++stream_it) {
208                 string url = *stream_it;
209                 log(WARNING, "stream '%s' disappeared from the configuration file. "
210                              "It will not be deleted, but clients will not get any new inputs. "
211                              "If you really meant to delete it, set src=delete and reload.",
212                              url.c_str());
213         }
214
215         // UDP streams.
216         for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
217                 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
218                 int stream_index = servers->add_udpstream(
219                         udpstream_config.dst,
220                         udpstream_config.pacing_rate,
221                         udpstream_config.ttl,
222                         udpstream_config.multicast_iface_index);
223
224                 string src = udpstream_config.src;
225                 if (!src.empty()) {
226                         multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
227                         assert(input_it != inputs->end());
228                         input_it->second.input->add_destination(stream_index);
229                         ++input_it->second.refcount;
230                 }
231         }
232 }
233         
234 void open_logs(const vector<LogConfig> &log_destinations)
235 {
236         for (size_t i = 0; i < log_destinations.size(); ++i) {
237                 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
238                         add_log_destination_file(log_destinations[i].filename);
239                 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
240                         add_log_destination_console();
241                 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
242                         add_log_destination_syslog();
243                 } else {
244                         assert(false);
245                 }
246         }
247         start_logging();
248 }
249         
250 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
251 {
252         char *argv0_copy = strdup(argv0.c_str());
253         char *config_filename_copy = strdup(config_filename.c_str());
254
255         pid_t pid = fork();
256         switch (pid) {
257         case -1:
258                 log_perror("fork()");
259                 free(argv0_copy);
260                 free(config_filename_copy);
261                 return false;
262         case 0:
263                 // Child.
264                 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
265                 log_perror(argv0_copy);
266                 _exit(1);
267         default:
268                 // Parent.
269                 break;
270         }
271                 
272         free(argv0_copy);
273         free(config_filename_copy);
274
275         int status;
276         pid_t err;
277         do {
278                 err = waitpid(pid, &status, 0);
279         } while (err == -1 && errno == EINTR);
280
281         if (err == -1) {
282                 log_perror("waitpid()");
283                 return false;
284         }       
285
286         return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
287 }
288
289 void find_deleted_streams(const Config &config, set<string> *deleted_urls)
290 {
291         for (unsigned i = 0; i < config.streams.size(); ++i) {
292                 const StreamConfig &stream_config = config.streams[i];
293                 if (stream_config.src == "delete") {
294                         log(INFO, "Deleting stream '%s'.", stream_config.url.c_str());
295                         deleted_urls->insert(stream_config.url);
296                 }
297         }
298 }
299
300 int main(int argc, char **argv)
301 {
302         signal(SIGHUP, hup);
303         signal(SIGINT, hup);
304         signal(SIGUSR1, do_nothing);  // Used in internal signalling.
305         signal(SIGPIPE, SIG_IGN);
306         
307         // Parse options.
308         int state_fd = -1;
309         bool test_config = false;
310         for ( ;; ) {
311                 static const option long_options[] = {
312                         { "state", required_argument, 0, 's' },
313                         { "test-config", no_argument, 0, 't' },
314                         { 0, 0, 0, 0 }
315                 };
316                 int option_index = 0;
317                 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
318      
319                 if (c == -1) {
320                         break;
321                 }
322                 switch (c) {
323                 case 's':
324                         state_fd = atoi(optarg);
325                         break;
326                 case 't':
327                         test_config = true;
328                         break;
329                 default:
330                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
331                         exit(1);
332                 }
333         }
334
335         string config_filename = "cubemap.config";
336         if (optind < argc) {
337                 config_filename = argv[optind++];
338         }
339
340         // Canonicalize argv[0] and config_filename.
341         char argv0_canon[PATH_MAX];
342         char config_filename_canon[PATH_MAX];
343
344         if (realpath("/proc/self/exe", argv0_canon) == NULL) {
345                 log_perror(argv[0]);
346                 exit(1);
347         }
348         if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
349                 log_perror(config_filename.c_str());
350                 exit(1);
351         }
352
353         // Now parse the configuration file.
354         Config config;
355         if (!parse_config(config_filename_canon, &config)) {
356                 exit(1);
357         }
358         if (test_config) {
359                 exit(0);
360         }
361         
362         // Ideally we'd like to daemonize only when we've started up all threads etc.,
363         // but daemon() forks, which is not good in multithreaded software, so we'll
364         // have to do it here.
365         if (config.daemonize) {
366                 if (daemon(0, 0) == -1) {
367                         log_perror("daemon");
368                         exit(1);
369                 }
370         }
371
372 start:
373         // Open logs as soon as possible.
374         open_logs(config.log_destinations);
375
376         log(INFO, "Cubemap " SERVER_VERSION " starting.");
377         if (config.access_log_file.empty()) {
378                 // Create a dummy logger.
379                 access_log = new AccessLogThread();
380         } else {
381                 access_log = new AccessLogThread(config.access_log_file);
382         }
383         access_log->run();
384
385         servers = new ServerPool(config.num_servers);
386
387         // Find all the streams that are to be deleted.
388         set<string> deleted_urls;
389         find_deleted_streams(config, &deleted_urls);
390
391         CubemapStateProto loaded_state;
392         struct timeval serialize_start;
393         set<string> deserialized_urls;
394         map<sockaddr_in6, Acceptor *, Sockaddr6Compare> deserialized_acceptors;
395         multimap<string, InputWithRefcount> inputs;  // multimap due to older versions without deduplication.
396         if (state_fd != -1) {
397                 log(INFO, "Deserializing state from previous process...");
398                 string serialized;
399                 if (!read_tempfile_and_close(state_fd, &serialized)) {
400                         exit(1);
401                 }
402                 if (!loaded_state.ParseFromString(serialized)) {
403                         log(ERROR, "Failed deserialization of state.");
404                         exit(1);
405                 }
406
407                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
408                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
409
410                 // Deserialize the streams.
411                 map<string, string> stream_headers_for_url;  // See below.
412                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
413                         const StreamProto &stream = loaded_state.streams(i);
414
415                         if (deleted_urls.count(stream.url()) != 0) {
416                                 // Delete the stream backlogs.
417                                 for (int j = 0; j < stream.data_fds_size(); ++j) {
418                                         safe_close(stream.data_fds(j));
419                                 }
420                         } else {
421                                 vector<int> data_fds;
422                                 for (int j = 0; j < stream.data_fds_size(); ++j) {
423                                         data_fds.push_back(stream.data_fds(j));
424                                 }
425
426                                 servers->add_stream_from_serialized(stream, data_fds);
427                                 deserialized_urls.insert(stream.url());
428
429                                 stream_headers_for_url.insert(make_pair(stream.url(), stream.stream_header()));
430                         }
431                 }
432
433                 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
434                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
435                         InputProto serialized_input = loaded_state.inputs(i);
436
437                         InputWithRefcount iwr;
438                         iwr.input = create_input(serialized_input);
439                         iwr.refcount = 0;
440                         inputs.insert(make_pair(serialized_input.url(), iwr));
441                 } 
442
443                 // Deserialize the acceptors.
444                 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
445                         sockaddr_in6 sin6 = extract_address_from_acceptor_proto(loaded_state.acceptors(i));
446                         deserialized_acceptors.insert(make_pair(
447                                 sin6,
448                                 new Acceptor(loaded_state.acceptors(i))));
449                 }
450
451                 log(INFO, "Deserialization done.");
452         }
453
454         // Add any new inputs coming from the config.
455         create_config_inputs(config, &inputs);
456         
457         // Find all streams in the configuration file, create them, and connect to the inputs.
458         create_streams(config, deserialized_urls, &inputs);
459         vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
460
461         // Convert old-style timestamps to new-style timestamps for all clients;
462         // this simplifies the sort below.
463         {
464                 timespec now_monotonic;
465                 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now_monotonic) == -1) {
466                         log(ERROR, "clock_gettime(CLOCK_MONOTONIC_COARSE) failed.");
467                         exit(1);
468                 }
469                 long delta_sec = now_monotonic.tv_sec - time(NULL);
470
471                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
472                         ClientProto* client = loaded_state.mutable_clients(i);
473                         if (client->has_connect_time_old()) {
474                                 client->set_connect_time_sec(client->connect_time_old() + delta_sec);
475                                 client->set_connect_time_nsec(now_monotonic.tv_nsec);
476                                 client->clear_connect_time_old();
477                         }
478                 }
479         }
480         
481         // Put back the existing clients. It doesn't matter which server we
482         // allocate them to, so just do round-robin. However, we need to sort them
483         // by connection time first, since add_client_serialized() expects that.
484         sort(loaded_state.mutable_clients()->begin(),
485              loaded_state.mutable_clients()->end(),
486              OrderByConnectionTime());
487         for (int i = 0; i < loaded_state.clients_size(); ++i) {
488                 if (deleted_urls.count(loaded_state.clients(i).url()) != 0) {
489                         safe_close(loaded_state.clients(i).sock());
490                 } else {
491                         servers->add_client_from_serialized(loaded_state.clients(i));
492                 }
493         }
494         
495         servers->run();
496
497         // Now delete all inputs that are longer in use, and start the others.
498         for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
499              input_it != inputs.end(); ) {
500                 if (input_it->second.refcount == 0) {
501                         log(WARNING, "Input '%s' no longer in use, closing.",
502                             input_it->first.c_str());
503                         input_it->second.input->close_socket();
504                         delete input_it->second.input;
505                         inputs.erase(input_it++);
506                 } else {
507                         input_it->second.input->run();
508                         ++input_it;
509                 }
510         }
511
512         // Start writing statistics.
513         StatsThread *stats_thread = NULL;
514         if (!config.stats_file.empty()) {
515                 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
516                 stats_thread->run();
517         }
518
519         InputStatsThread *input_stats_thread = NULL;
520         if (!config.input_stats_file.empty()) {
521                 vector<Input*> inputs_no_refcount;
522                 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
523                      input_it != inputs.end(); ++input_it) {
524                         inputs_no_refcount.push_back(input_it->second.input);
525                 }
526
527                 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
528                 input_stats_thread->run();
529         }
530
531         struct timeval server_start;
532         gettimeofday(&server_start, NULL);
533         if (state_fd != -1) {
534                 // Measure time from we started deserializing (below) to now, when basically everything
535                 // is up and running. This is, in other words, a conservative estimate of how long our
536                 // “glitch” period was, not counting of course reconnects if the configuration changed.
537                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
538                         1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
539                 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
540         }
541
542         while (!hupped) {
543                 usleep(100000);
544         }
545
546         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
547         gettimeofday(&serialize_start, NULL);
548
549         if (input_stats_thread != NULL) {
550                 input_stats_thread->stop();
551                 delete input_stats_thread;
552         }
553         if (stats_thread != NULL) {
554                 stats_thread->stop();
555                 delete stats_thread;
556         }
557         for (size_t i = 0; i < acceptors.size(); ++i) {
558                 acceptors[i]->stop();
559         }
560         for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
561              input_it != inputs.end();
562              ++input_it) {
563                 input_it->second.input->stop();
564         }
565         servers->stop();
566
567         CubemapStateProto state;
568         if (stopped) {
569                 log(INFO, "Shutting down.");
570         } else {
571                 log(INFO, "Serializing state and re-execing...");
572                 state = collect_state(
573                         serialize_start, acceptors, inputs, servers);
574                 string serialized;
575                 state.SerializeToString(&serialized);
576                 state_fd = make_tempfile(serialized);
577                 if (state_fd == -1) {
578                         exit(1);
579                 }
580         }
581         delete servers;
582
583         access_log->stop();
584         delete access_log;
585         shut_down_logging();
586
587         if (stopped) {
588                 exit(0);
589         }
590
591         // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
592         if (!dry_run_config(argv0_canon, config_filename_canon)) {
593                 open_logs(config.log_destinations);
594                 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
595                 hupped = false;
596                 shut_down_logging();
597                 goto start;
598         }
599          
600         char buf[16];
601         sprintf(buf, "%d", state_fd);
602
603         for ( ;; ) {
604                 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
605                 open_logs(config.log_destinations);
606                 log_perror("execlp");
607                 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);
608                 shut_down_logging();
609                 usleep(200000);
610         }
611 }