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