6 #include <sys/socket.h>
26 #include "serverpool.h"
33 ServerPool *servers = NULL;
34 volatile bool hupped = false;
41 // Serialize the given state to a file descriptor, and return the (still open)
43 int make_tempfile(const CubemapStateProto &state)
45 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
46 int state_fd = mkstemp(tmpl);
53 state.SerializeToString(&serialized);
55 const char *ptr = serialized.data();
56 size_t to_write = serialized.size();
57 while (to_write > 0) {
58 ssize_t ret = write(state_fd, ptr, to_write);
71 // Read the state back from the file descriptor made by make_tempfile,
73 CubemapStateProto read_tempfile(int state_fd)
75 if (lseek(state_fd, 0, SEEK_SET) == -1) {
83 ssize_t ret = read(state_fd, buf, sizeof(buf));
93 serialized.append(string(buf, buf + ret));
96 close(state_fd); // Implicitly deletes the file.
98 CubemapStateProto state;
99 if (!state.ParseFromString(serialized)) {
100 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
107 // Reuse mark pools if one already exists.
108 MarkPool *get_mark_pool(map<pair<int, int>, MarkPool *> *mark_pools, int from, int to)
110 pair<int, int> mark_range(from, to);
111 if (mark_pools->count(mark_range) != 0) {
112 return (*mark_pools)[mark_range];
115 // Check if we're overlapping some other mark pool.
116 for (map<pair<int, int>, MarkPool *>::const_iterator mp_it = mark_pools->begin();
117 mp_it != mark_pools->end();
119 int other_from = mp_it->first.first;
120 int other_to = mp_it->first.second;
121 if ((from >= other_from && from < other_to) ||
122 (to >= other_from && to < other_to)) {
123 fprintf(stderr, "WARNING: Mark pool %d-%d partially overlaps with %d-%d, you may get duplicate marks.\n",
124 from, to, other_from, other_to);
125 fprintf(stderr, " Mark pools must either be completely disjunct, or completely overlapping.\n");
129 MarkPool *mark_pool = new MarkPool(from, to);
130 mark_pools->insert(make_pair(mark_range, mark_pool));
134 int main(int argc, char **argv)
136 fprintf(stderr, "\nCubemap starting.\n");
138 struct timeval serialize_start;
139 bool is_reexec = false;
141 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
142 vector<ConfigLine> config = parse_config(config_filename);
144 int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
145 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
147 servers = new ServerPool(num_servers);
149 CubemapStateProto loaded_state;
150 int server_sock = -1, old_port = -1;
151 set<string> deserialized_stream_ids;
152 map<string, Input *> deserialized_inputs;
153 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
156 fprintf(stderr, "Deserializing state from previous process... ");
157 int state_fd = atoi(argv[3]);
158 loaded_state = read_tempfile(state_fd);
160 serialize_start.tv_sec = loaded_state.serialize_start_sec();
161 serialize_start.tv_usec = loaded_state.serialize_start_usec();
163 // Deserialize the streams.
164 for (int i = 0; i < loaded_state.streams_size(); ++i) {
165 servers->add_stream_from_serialized(loaded_state.streams(i));
166 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
169 // Deserialize the inputs. Note that we don't actually add them to any state yet.
170 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
171 deserialized_inputs.insert(make_pair(
172 loaded_state.inputs(i).stream_id(),
173 new Input(loaded_state.inputs(i))));
176 // Deserialize the server socket.
177 server_sock = loaded_state.server_sock();
178 old_port = loaded_state.port();
180 fprintf(stderr, "done.\n");
183 // Find all streams in the configuration file, and create them.
184 set<string> expecting_stream_ids = deserialized_stream_ids;
185 map<pair<int, int>, MarkPool *> mark_pools;
186 for (unsigned i = 0; i < config.size(); ++i) {
187 if (config[i].keyword != "stream") {
190 if (config[i].arguments.size() != 1) {
191 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
194 string stream_id = config[i].arguments[0];
195 if (deserialized_stream_ids.count(stream_id) == 0) {
196 servers->add_stream(stream_id);
198 expecting_stream_ids.erase(stream_id);
200 // Set up marks, if so desired.
201 if (config[i].parameters.count("mark")) {
202 string mark_str = config[i].parameters["mark"];
203 size_t split = mark_str.find_first_of('-');
204 if (split == string::npos) {
205 fprintf(stderr, "WARNING: Invalid mark specification '%s' (expected 'X-Y'), ignoring.\n",
210 string from_str(mark_str.begin(), mark_str.begin() + split);
211 string to_str(mark_str.begin() + split + 1, mark_str.end());
212 int from = atoi(from_str.c_str());
213 int to = atoi(to_str.c_str());
215 if (from <= 0 || from >= 65536 || to <= 0 || to >= 65536) {
216 fprintf(stderr, "WARNING: Mark pool range %d-%d is outside legal range [1,65536>, ignoring.\n",
221 MarkPool *mark_pool = get_mark_pool(&mark_pools, from, to);
222 servers->set_mark_pool(stream_id, mark_pool);
226 // Warn about any servers we've lost.
227 // TODO: Make an option (delete=yes?) to actually shut down streams.
228 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
229 stream_it != expecting_stream_ids.end();
231 string stream_id = *stream_it;
232 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
234 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
235 if (deserialized_inputs.count(stream_id) != 0) {
236 delete deserialized_inputs[stream_id];
237 deserialized_inputs.erase(stream_id);
241 // Open a new server socket if we do not already have one, or if we changed ports.
242 if (server_sock != -1 && port != old_port) {
243 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
247 if (server_sock == -1) {
248 server_sock = create_server_socket(port);
251 // See if the user wants stats.
252 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
253 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
254 if (stats_interval != -1 && stats_file.empty()) {
255 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
257 StatsThread *stats_thread = NULL;
258 if (!stats_file.empty()) {
259 stats_thread = new StatsThread(stats_file, stats_interval);
264 pthread_t acceptor_thread;
265 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
267 // Find all streams in the configuration file, and create inputs for them.
268 vector<Input *> inputs;
269 for (unsigned i = 0; i < config.size(); ++i) {
270 if (config[i].keyword != "stream") {
273 assert(config[i].arguments.size() == 1);
274 string stream_id = config[i].arguments[0];
276 if (config[i].parameters.count("src") == 0) {
277 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
282 string src = config[i].parameters["src"];
284 if (deserialized_inputs.count(stream_id) != 0) {
285 input = deserialized_inputs[stream_id];
286 if (input->get_url() != src) {
287 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
288 stream_id.c_str(), input->get_url().c_str(), src.c_str());
292 deserialized_inputs.erase(stream_id);
295 input = new Input(stream_id, src);
298 inputs.push_back(input);
302 // Put back the existing clients. It doesn't matter which server we
303 // allocate them to, so just do round-robin. However, we need to add
304 // them after the mark pools have been set up.
305 for (int i = 0; i < loaded_state.clients_size(); ++i) {
306 servers->add_client_from_serialized(loaded_state.clients(i));
310 // All deserialized inputs should now have been taken care of, one way or the other.
311 assert(deserialized_inputs.empty());
313 // Start writing statistics.
314 if (stats_thread != NULL) {
320 struct timeval server_start;
321 gettimeofday(&server_start, NULL);
323 // Measure time from we started deserializing (below) to now, when basically everything
324 // is up and running. This is, in other words, a conservative estimate of how long our
325 // “glitch” period was, not counting of course reconnects if the configuration changed.
326 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
327 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
328 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
335 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
336 gettimeofday(&serialize_start, NULL);
338 if (stats_thread != NULL) {
339 stats_thread->stop();
341 pthread_kill(acceptor_thread, SIGHUP);
342 if (pthread_join(acceptor_thread, NULL) == -1) {
343 perror("pthread_join");
347 CubemapStateProto state;
348 state.set_serialize_start_sec(serialize_start.tv_sec);
349 state.set_serialize_start_usec(serialize_start.tv_usec);
350 state.set_server_sock(server_sock);
351 state.set_port(port);
353 for (size_t i = 0; i < inputs.size(); ++i) {
355 state.add_inputs()->MergeFrom(inputs[i]->serialize());
358 for (int i = 0; i < num_servers; ++i) {
359 servers->get_server(i)->stop();
361 CubemapStateProto local_state = servers->get_server(i)->serialize();
363 // The stream state should be identical between the servers, so we only store it once.
365 state.mutable_streams()->MergeFrom(local_state.streams());
367 for (int j = 0; j < local_state.clients_size(); ++j) {
368 state.add_clients()->MergeFrom(local_state.clients(j));
373 fprintf(stderr, "Serializing state and re-execing...\n");
374 int state_fd = make_tempfile(state);
377 sprintf(buf, "%d", state_fd);
380 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
382 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);