]> git.sesse.net Git - cubemap/blob - main.cpp
a4a4dbe83489e1e759a7c8d35f965936bf8743f7
[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 int main(int argc, char **argv)
196 {
197         fprintf(stderr, "\nCubemap starting.\n");
198
199         struct timeval serialize_start;
200         bool is_reexec = false;
201
202         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
203         vector<ConfigLine> config = parse_config(config_filename);
204
205         int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
206         int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY);  // Insanely high max limit.
207
208         servers = new ServerPool(num_servers);
209
210         CubemapStateProto loaded_state;
211         int server_sock = -1, old_port = -1;
212         set<string> deserialized_stream_ids;
213         map<string, Input *> deserialized_inputs;
214         if (argc == 4 && strcmp(argv[2], "-state") == 0) {
215                 is_reexec = true;
216
217                 fprintf(stderr, "Deserializing state from previous process... ");
218                 int state_fd = atoi(argv[3]);
219                 loaded_state = read_tempfile(state_fd);
220
221                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
222                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
223
224                 // Deserialize the streams.
225                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
226                         servers->add_stream_from_serialized(loaded_state.streams(i));
227                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
228                 }
229
230                 // Deserialize the inputs. Note that we don't actually add them to any state yet.
231                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
232                         deserialized_inputs.insert(make_pair(
233                                 loaded_state.inputs(i).stream_id(),
234                                 new Input(loaded_state.inputs(i))));
235                 } 
236
237                 // Deserialize the server socket.
238                 server_sock = loaded_state.server_sock();
239                 old_port = loaded_state.port();
240
241                 fprintf(stderr, "done.\n");
242         }
243
244         // Find all streams in the configuration file, and create them.
245         set<string> expecting_stream_ids = deserialized_stream_ids;
246         map<pair<int, int>, MarkPool *> mark_pools;
247         for (unsigned i = 0; i < config.size(); ++i) {
248                 if (config[i].keyword != "stream") {
249                         continue;
250                 }
251                 if (config[i].arguments.size() != 1) {
252                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
253                         exit(1);
254                 }
255                 string stream_id = config[i].arguments[0];
256                 if (deserialized_stream_ids.count(stream_id) == 0) {
257                         servers->add_stream(stream_id);
258                 }
259                 expecting_stream_ids.erase(stream_id);
260
261                 // Set up marks, if so desired.
262                 if (config[i].parameters.count("mark")) {
263                         string mark_str = config[i].parameters["mark"];
264                         size_t split = mark_str.find_first_of('-');
265                         if (split == string::npos) {
266                                 fprintf(stderr, "WARNING: Invalid mark specification '%s' (expected 'X-Y'), ignoring.\n",
267                                         mark_str.c_str());
268                                 continue;
269                         }
270
271                         string from_str(mark_str.begin(), mark_str.begin() + split);
272                         string to_str(mark_str.begin() + split + 1, mark_str.end());
273                         int from = atoi(from_str.c_str());
274                         int to = atoi(to_str.c_str());
275
276                         if (from <= 0 || from >= 65536 || to <= 0 || to >= 65536) {
277                                 fprintf(stderr, "WARNING: Mark pool range %d-%d is outside legal range [1,65536>, ignoring.\n",
278                                         from, to);
279                                 continue;
280                         }
281
282                         MarkPool *mark_pool = get_mark_pool(&mark_pools, from, to);
283                         servers->set_mark_pool(stream_id, mark_pool);
284                 }
285         }
286
287         // Warn about any servers we've lost.
288         // TODO: Make an option (delete=yes?) to actually shut down streams.
289         for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
290              stream_it != expecting_stream_ids.end();
291              ++stream_it) {
292                 string stream_id = *stream_it;
293                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
294                         stream_id.c_str());
295                 fprintf(stderr, "         It will not be deleted, but clients will not get any new inputs.\n");
296                 if (deserialized_inputs.count(stream_id) != 0) {
297                         delete deserialized_inputs[stream_id];
298                         deserialized_inputs.erase(stream_id);
299                 }
300         }
301
302         // Open a new server socket if we do not already have one, or if we changed ports.
303         if (server_sock != -1 && port != old_port) {
304                 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
305                 close(server_sock);
306                 server_sock = -1;
307         }
308         if (server_sock == -1) {
309                 server_sock = create_server_socket(port);
310         }
311
312         // See if the user wants stats.
313         string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
314         int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
315         if (stats_interval != -1 && stats_file.empty()) {
316                 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
317         }
318
319         servers->run();
320
321         pthread_t acceptor_thread;
322         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
323
324         // Find all streams in the configuration file, and create inputs for them.
325         vector<Input *> inputs;
326         for (unsigned i = 0; i < config.size(); ++i) {
327                 if (config[i].keyword != "stream") {
328                         continue;
329                 }
330                 assert(config[i].arguments.size() == 1);
331                 string stream_id = config[i].arguments[0];
332
333                 if (config[i].parameters.count("src") == 0) {
334                         fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
335                                 stream_id.c_str());
336                         continue;
337                 }
338
339                 string src = config[i].parameters["src"];
340                 Input *input = NULL;
341                 if (deserialized_inputs.count(stream_id) != 0) {
342                         input = deserialized_inputs[stream_id];
343                         if (input->get_url() != src) {
344                                 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
345                                         stream_id.c_str(), input->get_url().c_str(), src.c_str());
346                                 delete input;
347                                 input = NULL;
348                         }
349                         deserialized_inputs.erase(stream_id);
350                 }
351                 if (input == NULL) {
352                         input = new Input(stream_id, src);
353                 }
354                 input->run();
355                 inputs.push_back(input);
356         }
357         
358         if (is_reexec) {        
359                 // Put back the existing clients. It doesn't matter which server we
360                 // allocate them to, so just do round-robin. However, we need to add
361                 // them after the mark pools have been set up.
362                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
363                         servers->add_client_from_serialized(loaded_state.clients(i));
364                 }
365         }
366
367         // All deserialized inputs should now have been taken care of, one way or the other.
368         assert(deserialized_inputs.empty());
369
370         // Start writing statistics.
371         pthread_t stats_thread;
372         StatsThreadParameters stats_parameters;  // Must live for as long as the stats thread does.
373         if (!stats_file.empty()) {
374                 stats_parameters.stats_file = stats_file;
375                 stats_parameters.stats_interval = stats_interval;
376                 pthread_create(&stats_thread, NULL, stats_thread_run, &stats_parameters);
377         }
378
379         signal(SIGHUP, hup);
380         
381         struct timeval server_start;
382         gettimeofday(&server_start, NULL);
383         if (is_reexec) {
384                 // Measure time from we started deserializing (below) to now, when basically everything
385                 // is up and running. This is, in other words, a conservative estimate of how long our
386                 // “glitch” period was, not counting of course reconnects if the configuration changed.
387                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
388                         1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
389                 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
390         }
391
392         while (!hupped) {
393                 usleep(100000);
394         }
395
396         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
397         gettimeofday(&serialize_start, NULL);
398
399         if (!stats_file.empty()) {
400                 pthread_kill(stats_thread, SIGHUP);
401                 if (pthread_join(stats_thread, NULL) == -1) {
402                         perror("pthread_join");
403                         exit(1);
404                 }
405         }
406         pthread_kill(acceptor_thread, SIGHUP);
407         if (pthread_join(acceptor_thread, NULL) == -1) {
408                 perror("pthread_join");
409                 exit(1);
410         }
411
412         CubemapStateProto state;
413         state.set_serialize_start_sec(serialize_start.tv_sec);
414         state.set_serialize_start_usec(serialize_start.tv_usec);
415         state.set_server_sock(server_sock);
416         state.set_port(port);
417
418         for (size_t i = 0; i < inputs.size(); ++i) {
419                 inputs[i]->stop();
420                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
421         }
422
423         for (int i = 0; i < num_servers; ++i) { 
424                 servers->get_server(i)->stop();
425
426                 CubemapStateProto local_state = servers->get_server(i)->serialize();
427
428                 // The stream state should be identical between the servers, so we only store it once.
429                 if (i == 0) {
430                         state.mutable_streams()->MergeFrom(local_state.streams());
431                 }
432                 for (int j = 0; j < local_state.clients_size(); ++j) {
433                         state.add_clients()->MergeFrom(local_state.clients(j));
434                 }
435         }
436         delete servers;
437
438         fprintf(stderr, "Serializing state and re-execing...\n");
439         int state_fd = make_tempfile(state);
440
441         char buf[16];
442         sprintf(buf, "%d", state_fd);
443
444         for ( ;; ) {
445                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
446                 perror("execlp");
447                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
448                 usleep(200000);
449         }
450 }