6 #include <sys/socket.h>
26 #include "serverpool.h"
32 ServerPool *servers = NULL;
33 volatile bool hupped = false;
40 struct StatsThreadParameters {
45 void *stats_thread_run(void *arg)
47 const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
52 vector<ClientStats> client_stats;
54 // Open a new, temporary file.
55 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
56 fd = mkostemp(filename, O_WRONLY);
73 client_stats = servers->get_client_stats();
74 for (size_t i = 0; i < client_stats.size(); ++i) {
75 fprintf(fp, "%s %s %d %llu\n",
76 client_stats[i].remote_addr.c_str(),
77 client_stats[i].stream_id.c_str(),
78 int(now - client_stats[i].connect_time),
79 (long long unsigned)(client_stats[i].bytes_sent));
81 if (fclose(fp) == EOF) {
88 if (rename(filename, parms->stats_file.c_str()) == -1) {
94 int left_to_sleep = parms->stats_interval;
96 left_to_sleep = sleep(left_to_sleep);
97 } while (left_to_sleep > 0 && !hupped);
102 // Serialize the given state to a file descriptor, and return the (still open)
104 int make_tempfile(const CubemapStateProto &state)
106 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
107 int state_fd = mkstemp(tmpl);
108 if (state_fd == -1) {
114 state.SerializeToString(&serialized);
116 const char *ptr = serialized.data();
117 size_t to_write = serialized.size();
118 while (to_write > 0) {
119 ssize_t ret = write(state_fd, ptr, to_write);
132 // Read the state back from the file descriptor made by make_tempfile,
134 CubemapStateProto read_tempfile(int state_fd)
136 if (lseek(state_fd, 0, SEEK_SET) == -1) {
144 ssize_t ret = read(state_fd, buf, sizeof(buf));
154 serialized.append(string(buf, buf + ret));
157 close(state_fd); // Implicitly deletes the file.
159 CubemapStateProto state;
160 if (!state.ParseFromString(serialized)) {
161 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
168 // Reuse mark pools if one already exists.
169 MarkPool *get_mark_pool(map<pair<int, int>, MarkPool *> *mark_pools, int from, int to)
171 pair<int, int> mark_range(from, to);
172 if (mark_pools->count(mark_range) != 0) {
173 return (*mark_pools)[mark_range];
176 // Check if we're overlapping some other mark pool.
177 for (map<pair<int, int>, MarkPool *>::const_iterator mp_it = mark_pools->begin();
178 mp_it != mark_pools->end();
180 int other_from = mp_it->first.first;
181 int other_to = mp_it->first.second;
182 if ((from >= other_from && from < other_to) ||
183 (to >= other_from && to < other_to)) {
184 fprintf(stderr, "WARNING: Mark pool %d-%d partially overlaps with %d-%d, you may get duplicate marks.\n",
185 from, to, other_from, other_to);
186 fprintf(stderr, " Mark pools must either be completely disjunct, or completely overlapping.\n");
190 MarkPool *mark_pool = new MarkPool(from, to);
191 mark_pools->insert(make_pair(mark_range, mark_pool));
195 int main(int argc, char **argv)
197 fprintf(stderr, "\nCubemap starting.\n");
199 struct timeval serialize_start;
200 bool is_reexec = false;
202 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
203 vector<ConfigLine> config = parse_config(config_filename);
205 int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
206 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
208 servers = new ServerPool(num_servers);
210 CubemapStateProto loaded_state;
211 int server_sock = -1, old_port = -1;
212 set<string> deserialized_stream_ids;
213 map<string, Input *> deserialized_inputs;
214 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
217 fprintf(stderr, "Deserializing state from previous process... ");
218 int state_fd = atoi(argv[3]);
219 loaded_state = read_tempfile(state_fd);
221 serialize_start.tv_sec = loaded_state.serialize_start_sec();
222 serialize_start.tv_usec = loaded_state.serialize_start_usec();
224 // Deserialize the streams.
225 for (int i = 0; i < loaded_state.streams_size(); ++i) {
226 servers->add_stream_from_serialized(loaded_state.streams(i));
227 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
230 // Deserialize the inputs. Note that we don't actually add them to any state yet.
231 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
232 deserialized_inputs.insert(make_pair(
233 loaded_state.inputs(i).stream_id(),
234 new Input(loaded_state.inputs(i))));
237 // Deserialize the server socket.
238 server_sock = loaded_state.server_sock();
239 old_port = loaded_state.port();
241 fprintf(stderr, "done.\n");
244 // Find all streams in the configuration file, and create them.
245 set<string> expecting_stream_ids = deserialized_stream_ids;
246 map<pair<int, int>, MarkPool *> mark_pools;
247 for (unsigned i = 0; i < config.size(); ++i) {
248 if (config[i].keyword != "stream") {
251 if (config[i].arguments.size() != 1) {
252 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
255 string stream_id = config[i].arguments[0];
256 if (deserialized_stream_ids.count(stream_id) == 0) {
257 servers->add_stream(stream_id);
259 expecting_stream_ids.erase(stream_id);
261 // Set up marks, if so desired.
262 if (config[i].parameters.count("mark")) {
263 string mark_str = config[i].parameters["mark"];
264 size_t split = mark_str.find_first_of('-');
265 if (split == string::npos) {
266 fprintf(stderr, "WARNING: Invalid mark specification '%s' (expected 'X-Y'), ignoring.\n",
271 string from_str(mark_str.begin(), mark_str.begin() + split);
272 string to_str(mark_str.begin() + split + 1, mark_str.end());
273 int from = atoi(from_str.c_str());
274 int to = atoi(to_str.c_str());
276 if (from <= 0 || from >= 65536 || to <= 0 || to >= 65536) {
277 fprintf(stderr, "WARNING: Mark pool range %d-%d is outside legal range [1,65536>, ignoring.\n",
282 MarkPool *mark_pool = get_mark_pool(&mark_pools, from, to);
283 servers->set_mark_pool(stream_id, mark_pool);
287 // Warn about any servers we've lost.
288 // TODO: Make an option (delete=yes?) to actually shut down streams.
289 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
290 stream_it != expecting_stream_ids.end();
292 string stream_id = *stream_it;
293 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
295 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
296 if (deserialized_inputs.count(stream_id) != 0) {
297 delete deserialized_inputs[stream_id];
298 deserialized_inputs.erase(stream_id);
302 // Open a new server socket if we do not already have one, or if we changed ports.
303 if (server_sock != -1 && port != old_port) {
304 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
308 if (server_sock == -1) {
309 server_sock = create_server_socket(port);
312 // See if the user wants stats.
313 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
314 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
315 if (stats_interval != -1 && stats_file.empty()) {
316 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
321 pthread_t acceptor_thread;
322 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
324 // Find all streams in the configuration file, and create inputs for them.
325 vector<Input *> inputs;
326 for (unsigned i = 0; i < config.size(); ++i) {
327 if (config[i].keyword != "stream") {
330 assert(config[i].arguments.size() == 1);
331 string stream_id = config[i].arguments[0];
333 if (config[i].parameters.count("src") == 0) {
334 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
339 string src = config[i].parameters["src"];
341 if (deserialized_inputs.count(stream_id) != 0) {
342 input = deserialized_inputs[stream_id];
343 if (input->get_url() != src) {
344 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
345 stream_id.c_str(), input->get_url().c_str(), src.c_str());
349 deserialized_inputs.erase(stream_id);
352 input = new Input(stream_id, src);
355 inputs.push_back(input);
359 // Put back the existing clients. It doesn't matter which server we
360 // allocate them to, so just do round-robin. However, we need to add
361 // them after the mark pools have been set up.
362 for (int i = 0; i < loaded_state.clients_size(); ++i) {
363 servers->add_client_from_serialized(loaded_state.clients(i));
367 // All deserialized inputs should now have been taken care of, one way or the other.
368 assert(deserialized_inputs.empty());
370 // Start writing statistics.
371 pthread_t stats_thread;
372 StatsThreadParameters stats_parameters; // Must live for as long as the stats thread does.
373 if (!stats_file.empty()) {
374 stats_parameters.stats_file = stats_file;
375 stats_parameters.stats_interval = stats_interval;
376 pthread_create(&stats_thread, NULL, stats_thread_run, &stats_parameters);
381 struct timeval server_start;
382 gettimeofday(&server_start, NULL);
384 // Measure time from we started deserializing (below) to now, when basically everything
385 // is up and running. This is, in other words, a conservative estimate of how long our
386 // “glitch” period was, not counting of course reconnects if the configuration changed.
387 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
388 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
389 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
396 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
397 gettimeofday(&serialize_start, NULL);
399 if (!stats_file.empty()) {
400 pthread_kill(stats_thread, SIGHUP);
401 if (pthread_join(stats_thread, NULL) == -1) {
402 perror("pthread_join");
406 pthread_kill(acceptor_thread, SIGHUP);
407 if (pthread_join(acceptor_thread, NULL) == -1) {
408 perror("pthread_join");
412 CubemapStateProto state;
413 state.set_serialize_start_sec(serialize_start.tv_sec);
414 state.set_serialize_start_usec(serialize_start.tv_usec);
415 state.set_server_sock(server_sock);
416 state.set_port(port);
418 for (size_t i = 0; i < inputs.size(); ++i) {
420 state.add_inputs()->MergeFrom(inputs[i]->serialize());
423 for (int i = 0; i < num_servers; ++i) {
424 servers->get_server(i)->stop();
426 CubemapStateProto local_state = servers->get_server(i)->serialize();
428 // The stream state should be identical between the servers, so we only store it once.
430 state.mutable_streams()->MergeFrom(local_state.streams());
432 for (int j = 0; j < local_state.clients_size(); ++j) {
433 state.add_clients()->MergeFrom(local_state.clients(j));
438 fprintf(stderr, "Serializing state and re-execing...\n");
439 int state_fd = make_tempfile(state);
442 sprintf(buf, "%d", state_fd);
445 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
447 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);