6 #include <sys/socket.h>
26 #include "serverpool.h"
34 ServerPool *servers = NULL;
35 volatile bool hupped = false;
42 // Serialize the given state to a file descriptor, and return the (still open)
44 int make_tempfile(const CubemapStateProto &state)
46 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
47 int state_fd = mkstemp(tmpl);
54 state.SerializeToString(&serialized);
56 const char *ptr = serialized.data();
57 size_t to_write = serialized.size();
58 while (to_write > 0) {
59 ssize_t ret = write(state_fd, ptr, to_write);
72 CubemapStateProto collect_state(const timeval &serialize_start,
73 const vector<Acceptor *> acceptors,
74 const vector<Input *> inputs,
78 CubemapStateProto state;
79 state.set_serialize_start_sec(serialize_start.tv_sec);
80 state.set_serialize_start_usec(serialize_start.tv_usec);
82 for (size_t i = 0; i < acceptors.size(); ++i) {
83 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
86 for (size_t i = 0; i < inputs.size(); ++i) {
87 state.add_inputs()->MergeFrom(inputs[i]->serialize());
90 for (int i = 0; i < num_servers; ++i) {
91 CubemapStateProto local_state = servers->get_server(i)->serialize();
93 // The stream state should be identical between the servers, so we only store it once.
95 state.mutable_streams()->MergeFrom(local_state.streams());
97 for (int j = 0; j < local_state.clients_size(); ++j) {
98 state.add_clients()->MergeFrom(local_state.clients(j));
105 // Read the state back from the file descriptor made by make_tempfile,
107 CubemapStateProto read_tempfile(int state_fd)
109 if (lseek(state_fd, 0, SEEK_SET) == -1) {
117 ssize_t ret = read(state_fd, buf, sizeof(buf));
127 serialized.append(string(buf, buf + ret));
130 close(state_fd); // Implicitly deletes the file.
132 CubemapStateProto state;
133 if (!state.ParseFromString(serialized)) {
134 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
141 // Reuse mark pools if one already exists.
142 MarkPool *get_mark_pool(map<pair<int, int>, MarkPool *> *mark_pools, int from, int to)
144 pair<int, int> mark_range(from, to);
145 if (mark_pools->count(mark_range) != 0) {
146 return (*mark_pools)[mark_range];
149 // Check if we're overlapping some other mark pool.
150 for (map<pair<int, int>, MarkPool *>::const_iterator mp_it = mark_pools->begin();
151 mp_it != mark_pools->end();
153 int other_from = mp_it->first.first;
154 int other_to = mp_it->first.second;
155 if ((from >= other_from && from < other_to) ||
156 (to >= other_from && to < other_to)) {
157 fprintf(stderr, "WARNING: Mark pool %d-%d partially overlaps with %d-%d, you may get duplicate marks.\n",
158 from, to, other_from, other_to);
159 fprintf(stderr, " Mark pools must either be completely disjunct, or completely overlapping.\n");
163 MarkPool *mark_pool = new MarkPool(from, to);
164 mark_pools->insert(make_pair(mark_range, mark_pool));
168 MarkPool *parse_mark_pool(map<pair<int, int>, MarkPool *> *mark_pools, const string &mark_str)
170 size_t split = mark_str.find_first_of('-');
171 if (split == string::npos) {
172 fprintf(stderr, "WARNING: Invalid mark specification '%s' (expected 'X-Y'), ignoring.\n",
177 string from_str(mark_str.begin(), mark_str.begin() + split);
178 string to_str(mark_str.begin() + split + 1, mark_str.end());
179 int from = atoi(from_str.c_str());
180 int to = atoi(to_str.c_str());
182 if (from <= 0 || from >= 65536 || to <= 0 || to >= 65536) {
183 fprintf(stderr, "WARNING: Mark pool range %d-%d is outside legal range [1,65536>, ignoring.\n",
188 return get_mark_pool(mark_pools, from, to);
191 // Find all port statements in the configuration file, and create acceptors for htem.
192 vector<Acceptor *> create_acceptors(
193 const vector<ConfigLine> &config,
194 map<int, Acceptor *> *deserialized_acceptors)
196 vector<Acceptor *> acceptors;
197 for (unsigned i = 0; i < config.size(); ++i) {
198 if (config[i].keyword != "port") {
201 if (config[i].arguments.size() != 1) {
202 fprintf(stderr, "ERROR: 'port' takes exactly one argument\n");
205 int port = atoi(config[i].arguments[0].c_str());
206 if (port < 1 || port >= 65536) {
207 fprintf(stderr, "WARNING: port %d is out of range (must be [1,65536>), ignoring\n", port);
211 Acceptor *acceptor = NULL;
212 map<int, Acceptor *>::iterator deserialized_acceptor_it =
213 deserialized_acceptors->find(port);
214 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
215 acceptor = deserialized_acceptor_it->second;
216 deserialized_acceptors->erase(deserialized_acceptor_it);
218 int server_sock = create_server_socket(port);
219 acceptor = new Acceptor(server_sock, port);
222 acceptors.push_back(acceptor);
225 // Close all acceptors that are no longer in the configuration file.
226 for (map<int, Acceptor *>::iterator acceptor_it = deserialized_acceptors->begin();
227 acceptor_it != deserialized_acceptors->end();
229 acceptor_it->second->close_socket();
230 delete acceptor_it->second;
236 // Find all streams in the configuration file, and create inputs for them.
237 vector<Input *> create_inputs(const vector<ConfigLine> &config,
238 map<string, Input *> *deserialized_inputs)
240 vector<Input *> inputs;
241 for (unsigned i = 0; i < config.size(); ++i) {
242 if (config[i].keyword != "stream") {
245 assert(config[i].arguments.size() == 1);
246 string stream_id = config[i].arguments[0];
248 map<string, string>::const_iterator src_it =
249 config[i].parameters.find("src");
250 if (src_it == config[i].parameters.end()) {
251 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
256 string src = src_it->second;
258 map<string, Input *>::iterator deserialized_input_it =
259 deserialized_inputs->find(stream_id);
260 if (deserialized_input_it != deserialized_inputs->end()) {
261 input = deserialized_input_it->second;
262 if (input->get_url() != src) {
263 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
264 stream_id.c_str(), input->get_url().c_str(), src.c_str());
268 deserialized_inputs->erase(deserialized_input_it);
271 input = create_input(stream_id, src);
274 inputs.push_back(input);
279 void create_streams(const vector<ConfigLine> &config,
280 const set<string> &deserialized_stream_ids,
281 map<string, Input *> *deserialized_inputs)
283 set<string> expecting_stream_ids = deserialized_stream_ids;
284 map<pair<int, int>, MarkPool *> mark_pools;
285 for (unsigned i = 0; i < config.size(); ++i) {
286 if (config[i].keyword != "stream") {
289 if (config[i].arguments.size() != 1) {
290 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
293 string stream_id = config[i].arguments[0];
294 if (deserialized_stream_ids.count(stream_id) == 0) {
295 servers->add_stream(stream_id);
297 expecting_stream_ids.erase(stream_id);
299 // Set up marks, if so desired.
300 map<string, string>::const_iterator mark_parm_it =
301 config[i].parameters.find("mark");
302 if (mark_parm_it != config[i].parameters.end()) {
303 MarkPool *mark_pool = parse_mark_pool(&mark_pools, mark_parm_it->second);
304 servers->set_mark_pool(stream_id, mark_pool);
308 // Warn about any servers we've lost.
309 // TODO: Make an option (delete=yes?) to actually shut down streams.
310 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
311 stream_it != expecting_stream_ids.end();
313 string stream_id = *stream_it;
314 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
316 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
317 if (deserialized_inputs->count(stream_id) != 0) {
318 delete (*deserialized_inputs)[stream_id];
319 deserialized_inputs->erase(stream_id);
324 int main(int argc, char **argv)
326 fprintf(stderr, "\nCubemap " SERVER_VERSION " starting.\n");
328 struct timeval serialize_start;
329 bool is_reexec = false;
331 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
332 vector<ConfigLine> config = parse_config(config_filename);
334 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
336 servers = new ServerPool(num_servers);
338 CubemapStateProto loaded_state;
339 set<string> deserialized_stream_ids;
340 map<string, Input *> deserialized_inputs;
341 map<int, Acceptor *> deserialized_acceptors;
342 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
345 fprintf(stderr, "Deserializing state from previous process... ");
346 int state_fd = atoi(argv[3]);
347 loaded_state = read_tempfile(state_fd);
349 serialize_start.tv_sec = loaded_state.serialize_start_sec();
350 serialize_start.tv_usec = loaded_state.serialize_start_usec();
352 // Deserialize the streams.
353 for (int i = 0; i < loaded_state.streams_size(); ++i) {
354 servers->add_stream_from_serialized(loaded_state.streams(i));
355 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
358 // Deserialize the inputs. Note that we don't actually add them to any state yet.
359 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
360 deserialized_inputs.insert(make_pair(
361 loaded_state.inputs(i).stream_id(),
362 create_input(loaded_state.inputs(i))));
365 // Convert the acceptor from older serialized formats.
366 if (loaded_state.has_server_sock() && loaded_state.has_port()) {
367 AcceptorProto *acceptor = loaded_state.add_acceptors();
368 acceptor->set_server_sock(loaded_state.server_sock());
369 acceptor->set_port(loaded_state.port());
372 // Deserialize the acceptors.
373 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
374 deserialized_acceptors.insert(make_pair(
375 loaded_state.acceptors(i).port(),
376 new Acceptor(loaded_state.acceptors(i))));
379 fprintf(stderr, "done.\n");
382 // Find all streams in the configuration file, and create them.
383 create_streams(config, deserialized_stream_ids, &deserialized_inputs);
385 // See if the user wants stats.
386 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
387 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
388 if (stats_interval != -1 && stats_file.empty()) {
389 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
394 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
395 vector<Input *> inputs = create_inputs(config, &deserialized_inputs);
397 // All deserialized inputs should now have been taken care of, one way or the other.
398 assert(deserialized_inputs.empty());
401 // Put back the existing clients. It doesn't matter which server we
402 // allocate them to, so just do round-robin. However, we need to add
403 // them after the mark pools have been set up.
404 for (int i = 0; i < loaded_state.clients_size(); ++i) {
405 servers->add_client_from_serialized(loaded_state.clients(i));
409 // Start writing statistics.
410 StatsThread *stats_thread = NULL;
411 if (!stats_file.empty()) {
412 stats_thread = new StatsThread(stats_file, stats_interval);
418 struct timeval server_start;
419 gettimeofday(&server_start, NULL);
421 // Measure time from we started deserializing (below) to now, when basically everything
422 // is up and running. This is, in other words, a conservative estimate of how long our
423 // “glitch” period was, not counting of course reconnects if the configuration changed.
424 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
425 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
426 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
433 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
434 gettimeofday(&serialize_start, NULL);
436 if (stats_thread != NULL) {
437 stats_thread->stop();
439 for (size_t i = 0; i < acceptors.size(); ++i) {
440 acceptors[i]->stop();
442 for (size_t i = 0; i < inputs.size(); ++i) {
447 fprintf(stderr, "Serializing state and re-execing...\n");
448 int state_fd = make_tempfile(collect_state(
449 serialize_start, acceptors, inputs, servers, num_servers));
453 sprintf(buf, "%d", state_fd);
456 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
458 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);