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