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);
273 fprintf(stderr, "ERROR: did not understand URL '%s', clients will not get any data.\n",
279 inputs.push_back(input);
284 void create_streams(const vector<ConfigLine> &config,
285 const set<string> &deserialized_stream_ids,
286 map<string, Input *> *deserialized_inputs)
288 set<string> expecting_stream_ids = deserialized_stream_ids;
289 map<pair<int, int>, MarkPool *> mark_pools;
290 for (unsigned i = 0; i < config.size(); ++i) {
291 if (config[i].keyword != "stream") {
294 if (config[i].arguments.size() != 1) {
295 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
298 string stream_id = config[i].arguments[0];
299 if (deserialized_stream_ids.count(stream_id) == 0) {
300 servers->add_stream(stream_id);
302 expecting_stream_ids.erase(stream_id);
304 // Set up marks, if so desired.
305 map<string, string>::const_iterator mark_parm_it =
306 config[i].parameters.find("mark");
307 if (mark_parm_it != config[i].parameters.end()) {
308 MarkPool *mark_pool = parse_mark_pool(&mark_pools, mark_parm_it->second);
309 servers->set_mark_pool(stream_id, mark_pool);
313 // Warn about any servers we've lost.
314 // TODO: Make an option (delete=yes?) to actually shut down streams.
315 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
316 stream_it != expecting_stream_ids.end();
318 string stream_id = *stream_it;
319 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
321 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
322 if (deserialized_inputs->count(stream_id) != 0) {
323 delete (*deserialized_inputs)[stream_id];
324 deserialized_inputs->erase(stream_id);
329 int main(int argc, char **argv)
331 fprintf(stderr, "\nCubemap " SERVER_VERSION " starting.\n");
333 struct timeval serialize_start;
334 bool is_reexec = false;
336 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
337 vector<ConfigLine> config = parse_config(config_filename);
339 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
341 servers = new ServerPool(num_servers);
343 CubemapStateProto loaded_state;
344 set<string> deserialized_stream_ids;
345 map<string, Input *> deserialized_inputs;
346 map<int, Acceptor *> deserialized_acceptors;
347 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
350 fprintf(stderr, "Deserializing state from previous process... ");
351 int state_fd = atoi(argv[3]);
352 loaded_state = read_tempfile(state_fd);
354 serialize_start.tv_sec = loaded_state.serialize_start_sec();
355 serialize_start.tv_usec = loaded_state.serialize_start_usec();
357 // Deserialize the streams.
358 for (int i = 0; i < loaded_state.streams_size(); ++i) {
359 servers->add_stream_from_serialized(loaded_state.streams(i));
360 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
363 // Deserialize the inputs. Note that we don't actually add them to any state yet.
364 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
365 deserialized_inputs.insert(make_pair(
366 loaded_state.inputs(i).stream_id(),
367 create_input(loaded_state.inputs(i))));
370 // Convert the acceptor from older serialized formats.
371 if (loaded_state.has_server_sock() && loaded_state.has_port()) {
372 AcceptorProto *acceptor = loaded_state.add_acceptors();
373 acceptor->set_server_sock(loaded_state.server_sock());
374 acceptor->set_port(loaded_state.port());
377 // Deserialize the acceptors.
378 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
379 deserialized_acceptors.insert(make_pair(
380 loaded_state.acceptors(i).port(),
381 new Acceptor(loaded_state.acceptors(i))));
384 fprintf(stderr, "done.\n");
387 // Find all streams in the configuration file, and create them.
388 create_streams(config, deserialized_stream_ids, &deserialized_inputs);
390 // See if the user wants stats.
391 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
392 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
393 if (stats_interval != -1 && stats_file.empty()) {
394 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
399 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
400 vector<Input *> inputs = create_inputs(config, &deserialized_inputs);
402 // All deserialized inputs should now have been taken care of, one way or the other.
403 assert(deserialized_inputs.empty());
406 // Put back the existing clients. It doesn't matter which server we
407 // allocate them to, so just do round-robin. However, we need to add
408 // them after the mark pools have been set up.
409 for (int i = 0; i < loaded_state.clients_size(); ++i) {
410 servers->add_client_from_serialized(loaded_state.clients(i));
414 // Start writing statistics.
415 StatsThread *stats_thread = NULL;
416 if (!stats_file.empty()) {
417 stats_thread = new StatsThread(stats_file, stats_interval);
423 struct timeval server_start;
424 gettimeofday(&server_start, NULL);
426 // Measure time from we started deserializing (below) to now, when basically everything
427 // is up and running. This is, in other words, a conservative estimate of how long our
428 // “glitch” period was, not counting of course reconnects if the configuration changed.
429 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
430 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
431 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
438 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
439 gettimeofday(&serialize_start, NULL);
441 if (stats_thread != NULL) {
442 stats_thread->stop();
444 for (size_t i = 0; i < acceptors.size(); ++i) {
445 acceptors[i]->stop();
447 for (size_t i = 0; i < inputs.size(); ++i) {
452 fprintf(stderr, "Serializing state and re-execing...\n");
453 int state_fd = make_tempfile(collect_state(
454 serialize_start, acceptors, inputs, servers, num_servers));
458 sprintf(buf, "%d", state_fd);
461 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
463 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);