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