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