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