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