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