]> git.sesse.net Git - cubemap/blob - main.cpp
f220cfb7ebb012b718814c337af31581e7d6b339
[cubemap] / main.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <getopt.h>
6 #include <arpa/inet.h>
7 #include <sys/socket.h>
8 #include <pthread.h>
9 #include <sys/types.h>
10 #include <sys/ioctl.h>
11 #include <sys/poll.h>
12 #include <sys/time.h>
13 #include <signal.h>
14 #include <errno.h>
15 #include <ctype.h>
16 #include <fcntl.h>
17 #include <vector>
18 #include <string>
19 #include <map>
20 #include <set>
21
22 #include "acceptor.h"
23 #include "config.h"
24 #include "markpool.h"
25 #include "metacube.h"
26 #include "parse.h"
27 #include "server.h"
28 #include "serverpool.h"
29 #include "input.h"
30 #include "stats.h"
31 #include "version.h"
32 #include "state.pb.h"
33
34 using namespace std;
35
36 ServerPool *servers = NULL;
37 volatile bool hupped = false;
38
39 void hup(int ignored)
40 {
41         hupped = true;
42 }
43
44 // Serialize the given state to a file descriptor, and return the (still open)
45 // descriptor.
46 int make_tempfile(const CubemapStateProto &state)
47 {
48         char tmpl[] = "/tmp/cubemapstate.XXXXXX";
49         int state_fd = mkstemp(tmpl);
50         if (state_fd == -1) {
51                 perror("mkstemp");
52                 exit(1);
53         }
54
55         string serialized;
56         state.SerializeToString(&serialized);
57
58         const char *ptr = serialized.data();
59         size_t to_write = serialized.size();
60         while (to_write > 0) {
61                 ssize_t ret = write(state_fd, ptr, to_write);
62                 if (ret == -1) {
63                         perror("write");
64                         exit(1);
65                 }
66
67                 ptr += ret;
68                 to_write -= ret;
69         }
70
71         return state_fd;
72 }
73
74 CubemapStateProto collect_state(const timeval &serialize_start,
75                                 const vector<Acceptor *> acceptors,
76                                 const vector<Input *> inputs,
77                                 ServerPool *servers)
78 {
79         CubemapStateProto state = servers->serialize();  // Fills streams() and clients().
80         state.set_serialize_start_sec(serialize_start.tv_sec);
81         state.set_serialize_start_usec(serialize_start.tv_usec);
82         
83         for (size_t i = 0; i < acceptors.size(); ++i) {
84                 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
85         }
86
87         for (size_t i = 0; i < inputs.size(); ++i) {
88                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
89         }
90
91         return state;
92 }
93
94 // Read the state back from the file descriptor made by make_tempfile,
95 // and close it.
96 CubemapStateProto read_tempfile(int state_fd)
97 {
98         if (lseek(state_fd, 0, SEEK_SET) == -1) {
99                 perror("lseek");
100                 exit(1);
101         }
102
103         string serialized;
104         char buf[4096];
105         for ( ;; ) {
106                 ssize_t ret = read(state_fd, buf, sizeof(buf));
107                 if (ret == -1) {
108                         perror("read");
109                         exit(1);
110                 }
111                 if (ret == 0) {
112                         // EOF.
113                         break;
114                 }
115
116                 serialized.append(string(buf, buf + ret));
117         }
118
119         close(state_fd);  // Implicitly deletes the file.
120
121         CubemapStateProto state;
122         if (!state.ParseFromString(serialized)) {
123                 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
124                 exit(1);
125         }
126
127         return state;
128 }
129         
130 // Find all port statements in the configuration file, and create acceptors for htem.
131 vector<Acceptor *> create_acceptors(
132         const Config &config,
133         map<int, Acceptor *> *deserialized_acceptors)
134 {
135         vector<Acceptor *> acceptors;
136         for (unsigned i = 0; i < config.acceptors.size(); ++i) {
137                 const AcceptorConfig &acceptor_config = config.acceptors[i];
138                 Acceptor *acceptor = NULL;
139                 map<int, Acceptor *>::iterator deserialized_acceptor_it =
140                         deserialized_acceptors->find(acceptor_config.port);
141                 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
142                         acceptor = deserialized_acceptor_it->second;
143                         deserialized_acceptors->erase(deserialized_acceptor_it);
144                 } else {
145                         int server_sock = create_server_socket(acceptor_config.port, TCP_SOCKET);
146                         acceptor = new Acceptor(server_sock, acceptor_config.port);
147                 }
148                 acceptor->run();
149                 acceptors.push_back(acceptor);
150         }
151
152         // Close all acceptors that are no longer in the configuration file.
153         for (map<int, Acceptor *>::iterator acceptor_it = deserialized_acceptors->begin();
154              acceptor_it != deserialized_acceptors->end();
155              ++acceptor_it) {
156                 acceptor_it->second->close_socket();
157                 delete acceptor_it->second;
158         }
159
160         return acceptors;
161 }
162
163 // Find all streams in the configuration file, and create inputs for them.
164 vector<Input *> create_inputs(const Config &config,
165                               map<string, Input *> *deserialized_inputs)
166 {
167         vector<Input *> inputs;
168         for (unsigned i = 0; i < config.streams.size(); ++i) {
169                 const StreamConfig &stream_config = config.streams[i];
170                 if (stream_config.src.empty()) {
171                         continue;
172                 }
173
174                 string stream_id = stream_config.stream_id;
175                 string src = stream_config.src;
176
177                 Input *input = NULL;
178                 map<string, Input *>::iterator deserialized_input_it =
179                         deserialized_inputs->find(stream_id);
180                 if (deserialized_input_it != deserialized_inputs->end()) {
181                         input = deserialized_input_it->second;
182                         if (input->get_url() != src) {
183                                 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
184                                         stream_id.c_str(), input->get_url().c_str(), src.c_str());
185                                 input->close_socket();
186                                 delete input;
187                                 input = NULL;
188                         }
189                         deserialized_inputs->erase(deserialized_input_it);
190                 }
191                 if (input == NULL) {
192                         input = create_input(stream_id, src);
193                         if (input == NULL) {
194                                 fprintf(stderr, "ERROR: did not understand URL '%s', clients will not get any data.\n",
195                                         src.c_str());
196                                 continue;
197                         }
198                 }
199                 input->run();
200                 inputs.push_back(input);
201         }
202         return inputs;
203 }
204
205 void create_streams(const Config &config,
206                     const set<string> &deserialized_stream_ids,
207                     map<string, Input *> *deserialized_inputs)
208 {
209         vector<MarkPool *> mark_pools;  // FIXME: leak
210         for (unsigned i = 0; i < config.mark_pools.size(); ++i) {
211                 const MarkPoolConfig &mp_config = config.mark_pools[i];
212                 mark_pools.push_back(new MarkPool(mp_config.from, mp_config.to));
213         }
214
215         set<string> expecting_stream_ids = deserialized_stream_ids;
216         for (unsigned i = 0; i < config.streams.size(); ++i) {
217                 const StreamConfig &stream_config = config.streams[i];
218                 if (deserialized_stream_ids.count(stream_config.stream_id) == 0) {
219                         servers->add_stream(stream_config.stream_id);
220                 }
221                 expecting_stream_ids.erase(stream_config.stream_id);
222
223                 if (stream_config.mark_pool != -1) {
224                         servers->set_mark_pool(stream_config.stream_id,
225                                                mark_pools[stream_config.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         // Parse options.
248         int state_fd = -1;
249         bool test_config = false;
250         for ( ;; ) {
251                 static const option long_options[] = {
252                         { "state", required_argument, 0, 's' },
253                         { "test-config", no_argument, 0, 't' },
254                 };
255                 int option_index = 0;
256                 int c = getopt_long (argc, argv, "s:t", long_options, &option_index);
257      
258                 if (c == -1) {
259                         break;
260                 }
261                 switch (c) {
262                 case 's':
263                         state_fd = atoi(optarg);
264                         break;
265                 case 't':
266                         test_config = true;
267                         break;
268                 default:
269                         assert(false);
270                 }
271         }
272
273         string config_filename = "cubemap.config";
274         if (optind < argc) {
275                 config_filename = argv[optind++];
276         }
277
278         struct timeval serialize_start;
279
280         Config config;
281         if (!parse_config(config_filename, &config)) {
282                 exit(1);
283         }
284         if (test_config) {
285                 exit(0);
286         }
287
288         fprintf(stderr, "\nCubemap " SERVER_VERSION " starting.\n");
289         servers = new ServerPool(config.num_servers);
290
291         CubemapStateProto loaded_state;
292         set<string> deserialized_stream_ids;
293         map<string, Input *> deserialized_inputs;
294         map<int, Acceptor *> deserialized_acceptors;
295         if (state_fd != -1) {
296                 fprintf(stderr, "Deserializing state from previous process... ");
297                 loaded_state = read_tempfile(state_fd);
298
299                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
300                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
301
302                 // Deserialize the streams.
303                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
304                         servers->add_stream_from_serialized(loaded_state.streams(i));
305                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
306                 }
307
308                 // Deserialize the inputs. Note that we don't actually add them to any state yet.
309                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
310                         deserialized_inputs.insert(make_pair(
311                                 loaded_state.inputs(i).stream_id(),
312                                 create_input(loaded_state.inputs(i))));
313                 } 
314
315                 // Deserialize the acceptors.
316                 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
317                         deserialized_acceptors.insert(make_pair(
318                                 loaded_state.acceptors(i).port(),
319                                 new Acceptor(loaded_state.acceptors(i))));
320                 }
321
322                 fprintf(stderr, "done.\n");
323         }
324
325         // Find all streams in the configuration file, and create them.
326         create_streams(config, deserialized_stream_ids, &deserialized_inputs);
327
328         servers->run();
329
330         vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
331         vector<Input *> inputs = create_inputs(config, &deserialized_inputs);
332         
333         // All deserialized inputs should now have been taken care of, one way or the other.
334         assert(deserialized_inputs.empty());
335         
336         // Put back the existing clients. It doesn't matter which server we
337         // allocate them to, so just do round-robin. However, we need to add
338         // them after the mark pools have been set up.
339         for (int i = 0; i < loaded_state.clients_size(); ++i) {
340                 servers->add_client_from_serialized(loaded_state.clients(i));
341         }
342
343         // Start writing statistics.
344         StatsThread *stats_thread = NULL;
345         if (!config.stats_file.empty()) {
346                 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
347                 stats_thread->run();
348         } else if (config.stats_interval != -1) {
349                 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
350         }
351
352         signal(SIGHUP, hup);
353         
354         struct timeval server_start;
355         gettimeofday(&server_start, NULL);
356         if (state_fd != -1) {
357                 // Measure time from we started deserializing (below) to now, when basically everything
358                 // is up and running. This is, in other words, a conservative estimate of how long our
359                 // “glitch” period was, not counting of course reconnects if the configuration changed.
360                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
361                         1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
362                 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
363         }
364
365         while (!hupped) {
366                 usleep(100000);
367         }
368
369         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
370         gettimeofday(&serialize_start, NULL);
371
372         if (stats_thread != NULL) {
373                 stats_thread->stop();
374         }
375         for (size_t i = 0; i < acceptors.size(); ++i) {
376                 acceptors[i]->stop();
377         }
378         for (size_t i = 0; i < inputs.size(); ++i) {
379                 inputs[i]->stop();
380         }
381         servers->stop();
382
383         fprintf(stderr, "Serializing state and re-execing...\n");
384         state_fd = make_tempfile(collect_state(
385                 serialize_start, acceptors, inputs, servers));
386         delete servers;
387          
388         char buf[16];
389         sprintf(buf, "%d", state_fd);
390
391         for ( ;; ) {
392                 execlp(argv[0], argv[0], config_filename.c_str(), "--state", buf, NULL);
393                 perror("execlp");
394                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
395                 usleep(200000);
396         }
397 }