95142707f572b2cb9d4e8ab7d54d95911d8c9cac
[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                 };
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                         assert(false);
267                 }
268         }
269
270         string config_filename = "cubemap.config";
271         if (optind < argc) {
272                 config_filename = argv[optind++];
273         }
274
275         // Canonicalize argv[0] and config_filename.
276         char argv0_canon[PATH_MAX];
277         char config_filename_canon[PATH_MAX];
278
279         if (realpath(argv[0], argv0_canon) == NULL) {
280                 log_perror(argv[0]);
281                 exit(1);
282         }
283         if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
284                 log_perror(config_filename.c_str());
285                 exit(1);
286         }
287
288         // Now parse the configuration file.
289         Config config;
290         if (!parse_config(config_filename_canon, &config)) {
291                 exit(1);
292         }
293         if (test_config) {
294                 exit(0);
295         }
296         
297         // Ideally we'd like to daemonize only when we've started up all threads etc.,
298         // but daemon() forks, which is not good in multithreaded software, so we'll
299         // have to do it here.
300         if (config.daemonize) {
301                 if (daemon(0, 0) == -1) {
302                         log_perror("daemon");
303                         exit(1);
304                 }
305         }
306
307 start:
308         // Open logs as soon as possible.
309         open_logs(config.log_destinations);
310
311         log(INFO, "Cubemap " SERVER_VERSION " starting.");
312         if (config.access_log_file.empty()) {
313                 // Create a dummy logger.
314                 access_log = new AccessLogThread();
315         } else {
316                 access_log = new AccessLogThread(config.access_log_file);
317         }
318         access_log->run();
319
320         servers = new ServerPool(config.num_servers);
321
322         CubemapStateProto loaded_state;
323         struct timeval serialize_start;
324         set<string> deserialized_stream_ids;
325         map<string, Input *> deserialized_inputs;
326         map<int, Acceptor *> deserialized_acceptors;
327         if (state_fd != -1) {
328                 log(INFO, "Deserializing state from previous process...");
329                 string serialized;
330                 if (!read_tempfile(state_fd, &serialized)) {
331                         exit(1);
332                 }
333                 if (!loaded_state.ParseFromString(serialized)) {
334                         log(ERROR, "Failed deserialization of state.");
335                         exit(1);
336                 }
337
338                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
339                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
340
341                 // Deserialize the streams.
342                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
343                         servers->add_stream_from_serialized(loaded_state.streams(i));
344                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
345                 }
346
347                 // Deserialize the inputs. Note that we don't actually add them to any state yet.
348                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
349                         deserialized_inputs.insert(make_pair(
350                                 loaded_state.inputs(i).stream_id(),
351                                 create_input(loaded_state.inputs(i))));
352                 } 
353
354                 // Deserialize the acceptors.
355                 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
356                         deserialized_acceptors.insert(make_pair(
357                                 loaded_state.acceptors(i).port(),
358                                 new Acceptor(loaded_state.acceptors(i))));
359                 }
360
361                 log(INFO, "Deserialization done.");
362         }
363
364         // Find all streams in the configuration file, and create them.
365         create_streams(config, deserialized_stream_ids, &deserialized_inputs);
366
367         vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
368         vector<Input *> inputs = create_inputs(config, &deserialized_inputs);
369         
370         // All deserialized inputs should now have been taken care of, one way or the other.
371         assert(deserialized_inputs.empty());
372         
373         // Put back the existing clients. It doesn't matter which server we
374         // allocate them to, so just do round-robin. However, we need to add
375         // them after the mark pools have been set up.
376         for (int i = 0; i < loaded_state.clients_size(); ++i) {
377                 servers->add_client_from_serialized(loaded_state.clients(i));
378         }
379         
380         servers->run();
381
382         // Start writing statistics.
383         StatsThread *stats_thread = NULL;
384         if (!config.stats_file.empty()) {
385                 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
386                 stats_thread->run();
387         }
388
389         struct timeval server_start;
390         gettimeofday(&server_start, NULL);
391         if (state_fd != -1) {
392                 // Measure time from we started deserializing (below) to now, when basically everything
393                 // is up and running. This is, in other words, a conservative estimate of how long our
394                 // “glitch” period was, not counting of course reconnects if the configuration changed.
395                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
396                         1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
397                 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
398         }
399
400         while (!hupped) {
401                 usleep(100000);
402         }
403
404         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
405         gettimeofday(&serialize_start, NULL);
406
407         if (stats_thread != NULL) {
408                 stats_thread->stop();
409         }
410         for (size_t i = 0; i < acceptors.size(); ++i) {
411                 acceptors[i]->stop();
412         }
413         for (size_t i = 0; i < inputs.size(); ++i) {
414                 inputs[i]->stop();
415         }
416         servers->stop();
417
418         CubemapStateProto state;
419         if (stopped) {
420                 log(INFO, "Shutting down.");
421         } else {
422                 log(INFO, "Serializing state and re-execing...");
423                 state = collect_state(
424                         serialize_start, acceptors, inputs, servers);
425                 string serialized;
426                 state.SerializeToString(&serialized);
427                 state_fd = make_tempfile(serialized);
428                 if (state_fd == -1) {
429                         exit(1);
430                 }
431         }
432         delete servers;
433
434         for (unsigned i = 0; i < mark_pools.size(); ++i) {
435                 delete mark_pools[i];
436         }
437         mark_pools.clear();
438
439         access_log->stop();
440         delete access_log;
441         shut_down_logging();
442
443         if (stopped) {
444                 exit(0);
445         }
446
447         // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
448         if (!dry_run_config(argv0_canon, config_filename_canon)) {
449                 open_logs(config.log_destinations);
450                 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
451                 hupped = false;
452                 shut_down_logging();
453                 goto start;
454         }
455          
456         char buf[16];
457         sprintf(buf, "%d", state_fd);
458
459         for ( ;; ) {
460                 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
461                 open_logs(config.log_destinations);
462                 log_perror("execlp");
463                 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);
464                 shut_down_logging();
465                 usleep(200000);
466         }
467 }