08559c971d99e1bbe33204ed3698addfa7b234ba
[dcpomatic.git] / src / lib / encode_server_finder.cc
1 /*
2     Copyright (C) 2013-2018 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "encode_server_finder.h"
22 #include "exceptions.h"
23 #include "util.h"
24 #include "config.h"
25 #include "cross.h"
26 #include "encode_server_description.h"
27 #include "dcpomatic_log.h"
28 #include "dcpomatic_socket.h"
29 #include <dcp/raw_convert.h>
30 #include <libcxml/cxml.h>
31 #include <boost/bind/placeholders.hpp>
32 #include <boost/lambda/lambda.hpp>
33 #include <iostream>
34
35 #include "i18n.h"
36
37 using std::string;
38 using std::list;
39 using std::vector;
40 using std::cout;
41 using boost::shared_ptr;
42 using boost::scoped_array;
43 using boost::weak_ptr;
44 using boost::optional;
45 #if BOOST_VERSION >= 106100
46 using namespace boost::placeholders;
47 #endif
48 using dcp::raw_convert;
49
50 EncodeServerFinder* EncodeServerFinder::_instance = 0;
51
52 EncodeServerFinder::EncodeServerFinder ()
53         : _stop (false)
54 {
55         Config::instance()->Changed.connect (boost::bind (&EncodeServerFinder::config_changed, this, _1));
56 }
57
58 void
59 EncodeServerFinder::start ()
60 {
61         _search_thread = boost::thread (boost::bind(&EncodeServerFinder::search_thread, this));
62         _listen_thread = boost::thread (boost::bind(&EncodeServerFinder::listen_thread, this));
63 #ifdef DCPOMATIC_LINUX
64         pthread_setname_np (_search_thread.native_handle(), "encode-server-search");
65         pthread_setname_np (_listen_thread.native_handle(), "encode-server-listen");
66 #endif
67 }
68
69
70 EncodeServerFinder::~EncodeServerFinder ()
71 {
72         stop ();
73 }
74
75 void
76 EncodeServerFinder::stop ()
77 {
78         boost::this_thread::disable_interruption dis;
79
80         _stop = true;
81
82         _search_condition.notify_all ();
83         try {
84                 _search_thread.join();
85         } catch (...) {}
86
87         _listen_io_service.stop ();
88         try {
89                 _listen_thread.join ();
90         } catch (...) {}
91
92         boost::mutex::scoped_lock lm (_servers_mutex);
93         _servers.clear ();
94 }
95
96 void
97 EncodeServerFinder::search_thread ()
98 try
99 {
100         boost::system::error_code error;
101         boost::asio::io_service io_service;
102         boost::asio::ip::udp::socket socket (io_service);
103         socket.open (boost::asio::ip::udp::v4(), error);
104         if (error) {
105                 throw NetworkError ("failed to set up broadcast socket");
106         }
107
108         socket.set_option (boost::asio::ip::udp::socket::reuse_address (true));
109         socket.set_option (boost::asio::socket_base::broadcast (true));
110
111         string const data = DCPOMATIC_HELLO;
112         int const interval = 10;
113
114         while (!_stop) {
115                 if (Config::instance()->use_any_servers ()) {
116                         /* Broadcast to look for servers */
117                         try {
118                                 boost::asio::ip::udp::endpoint end_point (boost::asio::ip::address_v4::broadcast(), HELLO_PORT);
119                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
120                         } catch (...) {
121
122                         }
123                 }
124
125                 /* Query our `definite' servers (if there are any) */
126                 vector<string> servers = Config::instance()->servers ();
127                 for (vector<string>::const_iterator i = servers.begin(); i != servers.end(); ++i) {
128                         if (server_found (*i)) {
129                                 /* Don't bother asking a server that we already know about */
130                                 continue;
131                         }
132                         try {
133                                 LOG_DEBUG_ENCODE_SERVERS("Sending query to configured server %1", *i);
134                                 boost::asio::ip::udp::resolver resolver (io_service);
135                                 boost::asio::ip::udp::resolver::query query (*i, raw_convert<string> (HELLO_PORT));
136                                 boost::asio::ip::udp::endpoint end_point (*resolver.resolve (query));
137                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
138                         } catch (...) {
139
140                         }
141                 }
142
143                 /* Discard servers that we haven't seen for a while */
144                 bool removed = false;
145                 {
146                         boost::mutex::scoped_lock lm (_servers_mutex);
147
148                         list<EncodeServerDescription>::iterator i = _servers.begin();
149                         while (i != _servers.end()) {
150                                 if (i->last_seen_seconds() > 2 * interval) {
151                                         list<EncodeServerDescription>::iterator j = i;
152                                         ++j;
153                                         _servers.erase (i);
154                                         i = j;
155                                         removed = true;
156                                 } else {
157                                         ++i;
158                                 }
159                         }
160                 }
161
162                 if (removed) {
163                         emit (boost::bind (boost::ref (ServersListChanged)));
164                 }
165
166                 boost::mutex::scoped_lock lm (_search_condition_mutex);
167                 _search_condition.timed_wait (lm, boost::get_system_time() + boost::posix_time::seconds (interval));
168         }
169 }
170 catch (...)
171 {
172         store_current ();
173 }
174
175 void
176 EncodeServerFinder::listen_thread ()
177 try {
178         using namespace boost::asio::ip;
179         LOG_DEBUG_ENCODE_SERVERS_NC("Listen thread starting");
180
181         try {
182                 _listen_acceptor.reset (
183                         new tcp::acceptor (_listen_io_service, tcp::endpoint (tcp::v4(), is_batch_converter ? BATCH_SERVER_PRESENCE_PORT : MAIN_SERVER_PRESENCE_PORT))
184                         );
185         } catch (...) {
186                 boost::throw_exception (NetworkError (_("Could not listen for remote encode servers.  Perhaps another instance of DCP-o-matic is running.")));
187         }
188
189         start_accept ();
190         _listen_io_service.run ();
191 }
192 catch (std::exception& e)
193 {
194         LOG_DEBUG_ENCODE_SERVERS("Listen thread terminating (%1)", e.what());
195         store_current ();
196 }
197 catch (...)
198 {
199         LOG_DEBUG_ENCODE_SERVERS_NC("Listen thread terminating (unknown)");
200         store_current ();
201 }
202
203 void
204 EncodeServerFinder::start_accept ()
205 {
206         shared_ptr<Socket> socket (new Socket ());
207         _listen_acceptor->async_accept (
208                 socket->socket(),
209                 boost::bind (&EncodeServerFinder::handle_accept, this, boost::asio::placeholders::error, socket)
210                 );
211 }
212
213 void
214 EncodeServerFinder::handle_accept (boost::system::error_code ec, shared_ptr<Socket> socket)
215 {
216         if (ec) {
217                 LOG_DEBUG_ENCODE_SERVERS_NC("Error arrived at handle_accept");
218                 start_accept ();
219                 return;
220         }
221
222         string const ip = socket->socket().remote_endpoint().address().to_string ();
223         LOG_DEBUG_ENCODE_SERVERS("Received reply from remote server %1", ip);
224
225         uint32_t length;
226         socket->read (reinterpret_cast<uint8_t*> (&length), sizeof (uint32_t));
227         length = ntohl (length);
228
229         scoped_array<char> buffer (new char[length]);
230         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
231
232         string s (buffer.get());
233         shared_ptr<cxml::Document> xml (new cxml::Document ("ServerAvailable"));
234         xml->read_string (s);
235
236         optional<list<EncodeServerDescription>::iterator> found = server_found (ip);
237         if (found) {
238                 LOG_DEBUG_ENCODE_SERVERS("%1 already seen", ip);
239                 (*found)->set_seen ();
240         } else {
241                 EncodeServerDescription sd (ip, xml->number_child<int>("Threads"), xml->optional_number_child<int>("Version").get_value_or(0));
242                 {
243                         boost::mutex::scoped_lock lm (_servers_mutex);
244                         _servers.push_back (sd);
245                 }
246                 LOG_DEBUG_ENCODE_SERVERS("%1 is new; offers %2 threads, version %3", sd.threads(), sd.link_version());
247                 emit (boost::bind (boost::ref (ServersListChanged)));
248         }
249
250         start_accept ();
251 }
252
253 optional<list<EncodeServerDescription>::iterator>
254 EncodeServerFinder::server_found (string ip)
255 {
256         boost::mutex::scoped_lock lm (_servers_mutex);
257         list<EncodeServerDescription>::iterator i = _servers.begin();
258         while (i != _servers.end() && i->host_name() != ip) {
259                 ++i;
260         }
261
262         if (i != _servers.end()) {
263                 return i;
264         }
265
266         return optional<list<EncodeServerDescription>::iterator>();
267 }
268
269 EncodeServerFinder*
270 EncodeServerFinder::instance ()
271 {
272         if (!_instance) {
273                 _instance = new EncodeServerFinder ();
274                 _instance->start ();
275         }
276
277         return _instance;
278 }
279
280 void
281 EncodeServerFinder::drop ()
282 {
283         delete _instance;
284         _instance = 0;
285 }
286
287 list<EncodeServerDescription>
288 EncodeServerFinder::servers () const
289 {
290         boost::mutex::scoped_lock lm (_servers_mutex);
291         return _servers;
292 }
293
294 void
295 EncodeServerFinder::config_changed (Config::Property what)
296 {
297         if (what == Config::USE_ANY_SERVERS || what == Config::SERVERS) {
298                 {
299                         boost::mutex::scoped_lock lm (_servers_mutex);
300                         _servers.clear ();
301                 }
302                 ServersListChanged ();
303                 _search_condition.notify_all ();
304         }
305 }