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