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