]> git.sesse.net Git - cubemap/blob - main.cpp
Support UDP input. Also fix some issues with socket closing.
[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, TCP_SOCKET);
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                                 input->close_socket();
266                                 delete input;
267                                 input = NULL;
268                         }
269                         deserialized_inputs->erase(deserialized_input_it);
270                 }
271                 if (input == NULL) {
272                         input = create_input(stream_id, src);
273                         if (input == NULL) {
274                                 fprintf(stderr, "ERROR: did not understand URL '%s', clients will not get any data.\n",
275                                         src.c_str());
276                                 continue;
277                         }
278                 }
279                 input->run();
280                 inputs.push_back(input);
281         }
282         return inputs;
283 }
284
285 void create_streams(const vector<ConfigLine> &config,
286                     const set<string> &deserialized_stream_ids,
287                     map<string, Input *> *deserialized_inputs)
288 {
289         set<string> expecting_stream_ids = deserialized_stream_ids;
290         map<pair<int, int>, MarkPool *> mark_pools;
291         for (unsigned i = 0; i < config.size(); ++i) {
292                 if (config[i].keyword != "stream") {
293                         continue;
294                 }
295                 if (config[i].arguments.size() != 1) {
296                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
297                         exit(1);
298                 }
299                 string stream_id = config[i].arguments[0];
300                 if (deserialized_stream_ids.count(stream_id) == 0) {
301                         servers->add_stream(stream_id);
302                 }
303                 expecting_stream_ids.erase(stream_id);
304
305                 // Set up marks, if so desired.
306                 map<string, string>::const_iterator mark_parm_it =
307                         config[i].parameters.find("mark");
308                 if (mark_parm_it != config[i].parameters.end()) {
309                         MarkPool *mark_pool = parse_mark_pool(&mark_pools, mark_parm_it->second);
310                         servers->set_mark_pool(stream_id, mark_pool);
311                 }
312         }
313
314         // Warn about any servers we've lost.
315         // TODO: Make an option (delete=yes?) to actually shut down streams.
316         for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
317              stream_it != expecting_stream_ids.end();
318              ++stream_it) {
319                 string stream_id = *stream_it;
320                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
321                         stream_id.c_str());
322                 fprintf(stderr, "         It will not be deleted, but clients will not get any new inputs.\n");
323                 if (deserialized_inputs->count(stream_id) != 0) {
324                         delete (*deserialized_inputs)[stream_id];
325                         deserialized_inputs->erase(stream_id);
326                 }
327         }
328 }
329
330 int main(int argc, char **argv)
331 {
332         fprintf(stderr, "\nCubemap " SERVER_VERSION " starting.\n");
333
334         struct timeval serialize_start;
335         bool is_reexec = false;
336
337         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
338         vector<ConfigLine> config = parse_config(config_filename);
339
340         int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY);  // Insanely high max limit.
341
342         servers = new ServerPool(num_servers);
343
344         CubemapStateProto loaded_state;
345         set<string> deserialized_stream_ids;
346         map<string, Input *> deserialized_inputs;
347         map<int, Acceptor *> deserialized_acceptors;
348         if (argc == 4 && strcmp(argv[2], "-state") == 0) {
349                 is_reexec = true;
350
351                 fprintf(stderr, "Deserializing state from previous process... ");
352                 int state_fd = atoi(argv[3]);
353                 loaded_state = read_tempfile(state_fd);
354
355                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
356                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
357
358                 // Deserialize the streams.
359                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
360                         servers->add_stream_from_serialized(loaded_state.streams(i));
361                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
362                 }
363
364                 // Deserialize the inputs. Note that we don't actually add them to any state yet.
365                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
366                         deserialized_inputs.insert(make_pair(
367                                 loaded_state.inputs(i).stream_id(),
368                                 create_input(loaded_state.inputs(i))));
369                 } 
370
371                 // Convert the acceptor from older serialized formats.
372                 if (loaded_state.has_server_sock() && loaded_state.has_port()) {
373                         AcceptorProto *acceptor = loaded_state.add_acceptors();
374                         acceptor->set_server_sock(loaded_state.server_sock());
375                         acceptor->set_port(loaded_state.port());
376                 }
377
378                 // Deserialize the acceptors.
379                 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
380                         deserialized_acceptors.insert(make_pair(
381                                 loaded_state.acceptors(i).port(),
382                                 new Acceptor(loaded_state.acceptors(i))));
383                 }
384
385                 fprintf(stderr, "done.\n");
386         }
387
388         // Find all streams in the configuration file, and create them.
389         create_streams(config, deserialized_stream_ids, &deserialized_inputs);
390
391         // See if the user wants stats.
392         string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
393         int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
394         if (stats_interval != -1 && stats_file.empty()) {
395                 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
396         }
397
398         servers->run();
399
400         vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
401         vector<Input *> inputs = create_inputs(config, &deserialized_inputs);
402         
403         // All deserialized inputs should now have been taken care of, one way or the other.
404         assert(deserialized_inputs.empty());
405         
406         if (is_reexec) {        
407                 // Put back the existing clients. It doesn't matter which server we
408                 // allocate them to, so just do round-robin. However, we need to add
409                 // them after the mark pools have been set up.
410                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
411                         servers->add_client_from_serialized(loaded_state.clients(i));
412                 }
413         }
414
415         // Start writing statistics.
416         StatsThread *stats_thread = NULL;
417         if (!stats_file.empty()) {
418                 stats_thread = new StatsThread(stats_file, stats_interval);
419                 stats_thread->run();
420         }
421
422         signal(SIGHUP, hup);
423         
424         struct timeval server_start;
425         gettimeofday(&server_start, NULL);
426         if (is_reexec) {
427                 // Measure time from we started deserializing (below) to now, when basically everything
428                 // is up and running. This is, in other words, a conservative estimate of how long our
429                 // “glitch” period was, not counting of course reconnects if the configuration changed.
430                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
431                         1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
432                 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
433         }
434
435         while (!hupped) {
436                 usleep(100000);
437         }
438
439         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
440         gettimeofday(&serialize_start, NULL);
441
442         if (stats_thread != NULL) {
443                 stats_thread->stop();
444         }
445         for (size_t i = 0; i < acceptors.size(); ++i) {
446                 acceptors[i]->stop();
447         }
448         for (size_t i = 0; i < inputs.size(); ++i) {
449                 inputs[i]->stop();
450         }
451         servers->stop();
452
453         fprintf(stderr, "Serializing state and re-execing...\n");
454         int state_fd = make_tempfile(collect_state(
455                 serialize_start, acceptors, inputs, servers, num_servers));
456         delete servers;
457          
458         char buf[16];
459         sprintf(buf, "%d", state_fd);
460
461         for ( ;; ) {
462                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
463                 perror("execlp");
464                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
465                 usleep(200000);
466         }
467 }