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