]> git.sesse.net Git - cubemap/blob - main.cpp
Do not segfault on unknown options.
[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 "accesslog.h"
20 #include "acceptor.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 "util.h"
29 #include "version.h"
30
31 using namespace std;
32
33 AccessLogThread *access_log = NULL;
34 ServerPool *servers = NULL;
35 vector<MarkPool *> mark_pools;
36 volatile bool hupped = false;
37 volatile bool stopped = false;
38
39 void hup(int signum)
40 {
41         hupped = true;
42         if (signum == SIGINT) {
43                 stopped = true;
44         }
45 }
46
47 CubemapStateProto collect_state(const timeval &serialize_start,
48                                 const vector<Acceptor *> acceptors,
49                                 const vector<Input *> inputs,
50                                 ServerPool *servers)
51 {
52         CubemapStateProto state = servers->serialize();  // Fills streams() and clients().
53         state.set_serialize_start_sec(serialize_start.tv_sec);
54         state.set_serialize_start_usec(serialize_start.tv_usec);
55         
56         for (size_t i = 0; i < acceptors.size(); ++i) {
57                 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
58         }
59
60         for (size_t i = 0; i < inputs.size(); ++i) {
61                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
62         }
63
64         return state;
65 }
66
67 // Find all port statements in the configuration file, and create acceptors for htem.
68 vector<Acceptor *> create_acceptors(
69         const Config &config,
70         map<int, Acceptor *> *deserialized_acceptors)
71 {
72         vector<Acceptor *> acceptors;
73         for (unsigned i = 0; i < config.acceptors.size(); ++i) {
74                 const AcceptorConfig &acceptor_config = config.acceptors[i];
75                 Acceptor *acceptor = NULL;
76                 map<int, Acceptor *>::iterator deserialized_acceptor_it =
77                         deserialized_acceptors->find(acceptor_config.port);
78                 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
79                         acceptor = deserialized_acceptor_it->second;
80                         deserialized_acceptors->erase(deserialized_acceptor_it);
81                 } else {
82                         int server_sock = create_server_socket(acceptor_config.port, TCP_SOCKET);
83                         acceptor = new Acceptor(server_sock, acceptor_config.port);
84                 }
85                 acceptor->run();
86                 acceptors.push_back(acceptor);
87         }
88
89         // Close all acceptors that are no longer in the configuration file.
90         for (map<int, Acceptor *>::iterator acceptor_it = deserialized_acceptors->begin();
91              acceptor_it != deserialized_acceptors->end();
92              ++acceptor_it) {
93                 acceptor_it->second->close_socket();
94                 delete acceptor_it->second;
95         }
96
97         return acceptors;
98 }
99
100 // Find all streams in the configuration file, and create inputs for them.
101 vector<Input *> create_inputs(const Config &config,
102                               map<string, Input *> *deserialized_inputs)
103 {
104         vector<Input *> inputs;
105         for (unsigned i = 0; i < config.streams.size(); ++i) {
106                 const StreamConfig &stream_config = config.streams[i];
107                 if (stream_config.src.empty()) {
108                         continue;
109                 }
110
111                 string stream_id = stream_config.stream_id;
112                 string src = stream_config.src;
113
114                 Input *input = NULL;
115                 map<string, Input *>::iterator deserialized_input_it =
116                         deserialized_inputs->find(stream_id);
117                 if (deserialized_input_it != deserialized_inputs->end()) {
118                         input = deserialized_input_it->second;
119                         if (input->get_url() != src) {
120                                 log(INFO, "Stream '%s' has changed URL from '%s' to '%s', restarting input.",
121                                         stream_id.c_str(), input->get_url().c_str(), src.c_str());
122                                 input->close_socket();
123                                 delete input;
124                                 input = NULL;
125                         }
126                         deserialized_inputs->erase(deserialized_input_it);
127                 }
128                 if (input == NULL) {
129                         input = create_input(stream_id, src);
130                         if (input == NULL) {
131                                 log(ERROR, "did not understand URL '%s', clients will not get any data.",
132                                         src.c_str());
133                                 continue;
134                         }
135                 }
136                 input->run();
137                 inputs.push_back(input);
138         }
139         return inputs;
140 }
141
142 void create_streams(const Config &config,
143                     const set<string> &deserialized_stream_ids,
144                     map<string, Input *> *deserialized_inputs)
145 {
146         for (unsigned i = 0; i < config.mark_pools.size(); ++i) {
147                 const MarkPoolConfig &mp_config = config.mark_pools[i];
148                 mark_pools.push_back(new MarkPool(mp_config.from, mp_config.to));
149         }
150
151         set<string> expecting_stream_ids = deserialized_stream_ids;
152         for (unsigned i = 0; i < config.streams.size(); ++i) {
153                 const StreamConfig &stream_config = config.streams[i];
154                 if (deserialized_stream_ids.count(stream_config.stream_id) == 0) {
155                         servers->add_stream(stream_config.stream_id, stream_config.backlog_size);
156                 } else {
157                         servers->set_backlog_size(stream_config.stream_id, stream_config.backlog_size);
158                 }
159                 expecting_stream_ids.erase(stream_config.stream_id);
160
161                 if (stream_config.mark_pool != -1) {
162                         servers->set_mark_pool(stream_config.stream_id,
163                                                mark_pools[stream_config.mark_pool]);
164                 }
165         }
166
167         // Warn about any servers we've lost.
168         // TODO: Make an option (delete=yes?) to actually shut down streams.
169         for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
170              stream_it != expecting_stream_ids.end();
171              ++stream_it) {
172                 string stream_id = *stream_it;
173                 log(WARNING, "stream '%s' disappeared from the configuration file. "
174                              "It will not be deleted, but clients will not get any new inputs.",
175                              stream_id.c_str());
176                 if (deserialized_inputs->count(stream_id) != 0) {
177                         delete (*deserialized_inputs)[stream_id];
178                         deserialized_inputs->erase(stream_id);
179                 }
180         }
181 }
182         
183 void open_logs(const vector<LogConfig> &log_destinations)
184 {
185         for (size_t i = 0; i < log_destinations.size(); ++i) {
186                 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
187                         add_log_destination_file(log_destinations[i].filename);
188                 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
189                         add_log_destination_console();
190                 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
191                         add_log_destination_syslog();
192                 } else {
193                         assert(false);
194                 }
195         }
196         start_logging();
197 }
198         
199 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
200 {
201         char *argv0_copy = strdup(argv0.c_str());
202         char *config_filename_copy = strdup(config_filename.c_str());
203
204         pid_t pid = fork();
205         switch (pid) {
206         case -1:
207                 log_perror("fork()");
208                 free(argv0_copy);
209                 free(config_filename_copy);
210                 return false;
211         case 0:
212                 // Child.
213                 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
214                 log_perror(argv0_copy);
215                 _exit(1);
216         default:
217                 // Parent.
218                 break;
219         }
220                 
221         free(argv0_copy);
222         free(config_filename_copy);
223
224         int status;
225         pid_t err;
226         do {
227                 err = waitpid(pid, &status, 0);
228         } while (err == -1 && errno == EINTR);
229
230         if (err == -1) {
231                 log_perror("waitpid()");
232                 return false;
233         }       
234
235         return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
236 }
237
238 int main(int argc, char **argv)
239 {
240         signal(SIGHUP, hup);
241         signal(SIGINT, hup);
242         signal(SIGPIPE, SIG_IGN);
243         
244         // Parse options.
245         int state_fd = -1;
246         bool test_config = false;
247         for ( ;; ) {
248                 static const option long_options[] = {
249                         { "state", required_argument, 0, 's' },
250                         { "test-config", no_argument, 0, 't' },
251                         { 0, 0, 0, 0 }
252                 };
253                 int option_index = 0;
254                 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
255      
256                 if (c == -1) {
257                         break;
258                 }
259                 switch (c) {
260                 case 's':
261                         state_fd = atoi(optarg);
262                         break;
263                 case 't':
264                         test_config = true;
265                         break;
266                 default:
267                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
268                         exit(1);
269                 }
270         }
271
272         string config_filename = "cubemap.config";
273         if (optind < argc) {
274                 config_filename = argv[optind++];
275         }
276
277         // Canonicalize argv[0] and config_filename.
278         char argv0_canon[PATH_MAX];
279         char config_filename_canon[PATH_MAX];
280
281         if (realpath(argv[0], argv0_canon) == NULL) {
282                 log_perror(argv[0]);
283                 exit(1);
284         }
285         if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
286                 log_perror(config_filename.c_str());
287                 exit(1);
288         }
289
290         // Now parse the configuration file.
291         Config config;
292         if (!parse_config(config_filename_canon, &config)) {
293                 exit(1);
294         }
295         if (test_config) {
296                 exit(0);
297         }
298         
299         // Ideally we'd like to daemonize only when we've started up all threads etc.,
300         // but daemon() forks, which is not good in multithreaded software, so we'll
301         // have to do it here.
302         if (config.daemonize) {
303                 if (daemon(0, 0) == -1) {
304                         log_perror("daemon");
305                         exit(1);
306                 }
307         }
308
309 start:
310         // Open logs as soon as possible.
311         open_logs(config.log_destinations);
312
313         log(INFO, "Cubemap " SERVER_VERSION " starting.");
314         if (config.access_log_file.empty()) {
315                 // Create a dummy logger.
316                 access_log = new AccessLogThread();
317         } else {
318                 access_log = new AccessLogThread(config.access_log_file);
319         }
320         access_log->run();
321
322         servers = new ServerPool(config.num_servers);
323
324         CubemapStateProto loaded_state;
325         struct timeval serialize_start;
326         set<string> deserialized_stream_ids;
327         map<string, Input *> deserialized_inputs;
328         map<int, Acceptor *> deserialized_acceptors;
329         if (state_fd != -1) {
330                 log(INFO, "Deserializing state from previous process...");
331                 string serialized;
332                 if (!read_tempfile(state_fd, &serialized)) {
333                         exit(1);
334                 }
335                 if (!loaded_state.ParseFromString(serialized)) {
336                         log(ERROR, "Failed deserialization of state.");
337                         exit(1);
338                 }
339
340                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
341                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
342
343                 // Deserialize the streams.
344                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
345                         servers->add_stream_from_serialized(loaded_state.streams(i));
346                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
347                 }
348
349                 // Deserialize the inputs. Note that we don't actually add them to any state yet.
350                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
351                         deserialized_inputs.insert(make_pair(
352                                 loaded_state.inputs(i).stream_id(),
353                                 create_input(loaded_state.inputs(i))));
354                 } 
355
356                 // Deserialize the acceptors.
357                 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
358                         deserialized_acceptors.insert(make_pair(
359                                 loaded_state.acceptors(i).port(),
360                                 new Acceptor(loaded_state.acceptors(i))));
361                 }
362
363                 log(INFO, "Deserialization done.");
364         }
365
366         // Find all streams in the configuration file, and create them.
367         create_streams(config, deserialized_stream_ids, &deserialized_inputs);
368
369         vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
370         vector<Input *> inputs = create_inputs(config, &deserialized_inputs);
371         
372         // All deserialized inputs should now have been taken care of, one way or the other.
373         assert(deserialized_inputs.empty());
374         
375         // Put back the existing clients. It doesn't matter which server we
376         // allocate them to, so just do round-robin. However, we need to add
377         // them after the mark pools have been set up.
378         for (int i = 0; i < loaded_state.clients_size(); ++i) {
379                 servers->add_client_from_serialized(loaded_state.clients(i));
380         }
381         
382         servers->run();
383
384         // Start writing statistics.
385         StatsThread *stats_thread = NULL;
386         if (!config.stats_file.empty()) {
387                 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
388                 stats_thread->run();
389         }
390
391         struct timeval server_start;
392         gettimeofday(&server_start, NULL);
393         if (state_fd != -1) {
394                 // Measure time from we started deserializing (below) to now, when basically everything
395                 // is up and running. This is, in other words, a conservative estimate of how long our
396                 // “glitch” period was, not counting of course reconnects if the configuration changed.
397                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
398                         1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
399                 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
400         }
401
402         while (!hupped) {
403                 usleep(100000);
404         }
405
406         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
407         gettimeofday(&serialize_start, NULL);
408
409         if (stats_thread != NULL) {
410                 stats_thread->stop();
411                 delete stats_thread;
412         }
413         for (size_t i = 0; i < acceptors.size(); ++i) {
414                 acceptors[i]->stop();
415         }
416         for (size_t i = 0; i < inputs.size(); ++i) {
417                 inputs[i]->stop();
418         }
419         servers->stop();
420
421         CubemapStateProto state;
422         if (stopped) {
423                 log(INFO, "Shutting down.");
424         } else {
425                 log(INFO, "Serializing state and re-execing...");
426                 state = collect_state(
427                         serialize_start, acceptors, inputs, servers);
428                 string serialized;
429                 state.SerializeToString(&serialized);
430                 state_fd = make_tempfile(serialized);
431                 if (state_fd == -1) {
432                         exit(1);
433                 }
434         }
435         delete servers;
436
437         for (unsigned i = 0; i < mark_pools.size(); ++i) {
438                 delete mark_pools[i];
439         }
440         mark_pools.clear();
441
442         access_log->stop();
443         delete access_log;
444         shut_down_logging();
445
446         if (stopped) {
447                 exit(0);
448         }
449
450         // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
451         if (!dry_run_config(argv0_canon, config_filename_canon)) {
452                 open_logs(config.log_destinations);
453                 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
454                 hupped = false;
455                 shut_down_logging();
456                 goto start;
457         }
458          
459         char buf[16];
460         sprintf(buf, "%d", state_fd);
461
462         for ( ;; ) {
463                 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
464                 open_logs(config.log_destinations);
465                 log_perror("execlp");
466                 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);
467                 shut_down_logging();
468                 usleep(200000);
469         }
470 }