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