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