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