]> git.sesse.net Git - cubemap/blob - main.cpp
Log all finished accesses to an access log.
[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 volatile bool hupped = false;
36 volatile bool stopped = false;
37
38 void hup(int signum)
39 {
40         hupped = true;
41         if (signum == SIGINT) {
42                 stopped = true;
43         }
44 }
45
46 CubemapStateProto collect_state(const timeval &serialize_start,
47                                 const vector<Acceptor *> acceptors,
48                                 const vector<Input *> inputs,
49                                 ServerPool *servers)
50 {
51         CubemapStateProto state = servers->serialize();  // Fills streams() and clients().
52         state.set_serialize_start_sec(serialize_start.tv_sec);
53         state.set_serialize_start_usec(serialize_start.tv_usec);
54         
55         for (size_t i = 0; i < acceptors.size(); ++i) {
56                 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
57         }
58
59         for (size_t i = 0; i < inputs.size(); ++i) {
60                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
61         }
62
63         return state;
64 }
65
66 // Find all port statements in the configuration file, and create acceptors for htem.
67 vector<Acceptor *> create_acceptors(
68         const Config &config,
69         map<int, Acceptor *> *deserialized_acceptors)
70 {
71         vector<Acceptor *> acceptors;
72         for (unsigned i = 0; i < config.acceptors.size(); ++i) {
73                 const AcceptorConfig &acceptor_config = config.acceptors[i];
74                 Acceptor *acceptor = NULL;
75                 map<int, Acceptor *>::iterator deserialized_acceptor_it =
76                         deserialized_acceptors->find(acceptor_config.port);
77                 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
78                         acceptor = deserialized_acceptor_it->second;
79                         deserialized_acceptors->erase(deserialized_acceptor_it);
80                 } else {
81                         int server_sock = create_server_socket(acceptor_config.port, TCP_SOCKET);
82                         acceptor = new Acceptor(server_sock, acceptor_config.port);
83                 }
84                 acceptor->run();
85                 acceptors.push_back(acceptor);
86         }
87
88         // Close all acceptors that are no longer in the configuration file.
89         for (map<int, Acceptor *>::iterator acceptor_it = deserialized_acceptors->begin();
90              acceptor_it != deserialized_acceptors->end();
91              ++acceptor_it) {
92                 acceptor_it->second->close_socket();
93                 delete acceptor_it->second;
94         }
95
96         return acceptors;
97 }
98
99 // Find all streams in the configuration file, and create inputs for them.
100 vector<Input *> create_inputs(const Config &config,
101                               map<string, Input *> *deserialized_inputs)
102 {
103         vector<Input *> inputs;
104         for (unsigned i = 0; i < config.streams.size(); ++i) {
105                 const StreamConfig &stream_config = config.streams[i];
106                 if (stream_config.src.empty()) {
107                         continue;
108                 }
109
110                 string stream_id = stream_config.stream_id;
111                 string src = stream_config.src;
112
113                 Input *input = NULL;
114                 map<string, Input *>::iterator deserialized_input_it =
115                         deserialized_inputs->find(stream_id);
116                 if (deserialized_input_it != deserialized_inputs->end()) {
117                         input = deserialized_input_it->second;
118                         if (input->get_url() != src) {
119                                 log(INFO, "Stream '%s' has changed URL from '%s' to '%s', restarting input.",
120                                         stream_id.c_str(), input->get_url().c_str(), src.c_str());
121                                 input->close_socket();
122                                 delete input;
123                                 input = NULL;
124                         }
125                         deserialized_inputs->erase(deserialized_input_it);
126                 }
127                 if (input == NULL) {
128                         input = create_input(stream_id, src);
129                         if (input == NULL) {
130                                 log(ERROR, "did not understand URL '%s', clients will not get any data.",
131                                         src.c_str());
132                                 continue;
133                         }
134                 }
135                 input->run();
136                 inputs.push_back(input);
137         }
138         return inputs;
139 }
140
141 void create_streams(const Config &config,
142                     const set<string> &deserialized_stream_ids,
143                     map<string, Input *> *deserialized_inputs)
144 {
145         vector<MarkPool *> mark_pools;  // FIXME: leak
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         access_log->stop();
434         delete access_log;
435         shut_down_logging();
436
437         if (stopped) {
438                 exit(0);
439         }
440
441         // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
442         if (!dry_run_config(argv0_canon, config_filename_canon)) {
443                 open_logs(config.log_destinations);
444                 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
445                 hupped = false;
446                 shut_down_logging();
447                 goto start;
448         }
449          
450         char buf[16];
451         sprintf(buf, "%d", state_fd);
452
453         for ( ;; ) {
454                 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
455                 open_logs(config.log_destinations);
456                 log_perror("execlp");
457                 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);
458                 shut_down_logging();
459                 usleep(200000);
460         }
461 }