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