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