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