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