Update encoding server list when servers disappear (#1176).
[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_socket.h"
28 #include <dcp/raw_convert.h>
29 #include <libcxml/cxml.h>
30 #include <boost/lambda/lambda.hpp>
31 #include <iostream>
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::list;
37 using std::vector;
38 using std::cout;
39 using boost::shared_ptr;
40 using boost::scoped_array;
41 using boost::weak_ptr;
42 using boost::optional;
43 using dcp::raw_convert;
44
45 EncodeServerFinder* EncodeServerFinder::_instance = 0;
46
47 EncodeServerFinder::EncodeServerFinder ()
48         : _search_thread (0)
49         , _listen_thread (0)
50         , _stop (false)
51 {
52         Config::instance()->Changed.connect (boost::bind (&EncodeServerFinder::config_changed, this, _1));
53 }
54
55 void
56 EncodeServerFinder::start ()
57 {
58         _search_thread = new boost::thread (boost::bind (&EncodeServerFinder::search_thread, this));
59         _listen_thread = new boost::thread (boost::bind (&EncodeServerFinder::listen_thread, this));
60 #ifdef DCPOMATIC_LINUX
61         pthread_setname_np (_search_thread->native_handle(), "encode-server-search");
62         pthread_setname_np (_listen_thread->native_handle(), "encode-server-listen");
63 #endif
64 }
65
66
67 EncodeServerFinder::~EncodeServerFinder ()
68 {
69         stop ();
70 }
71
72 void
73 EncodeServerFinder::stop ()
74 {
75         _stop = true;
76
77         _search_condition.notify_all ();
78         if (_search_thread) {
79                 /* Ideally this would be a DCPOMATIC_ASSERT(_search_thread->joinable()) but we
80                    can't throw exceptions from a destructor.
81                 */
82                 if (_search_thread->joinable ()) {
83                         _search_thread->join ();
84                 }
85         }
86         delete _search_thread;
87         _search_thread = 0;
88
89         _listen_io_service.stop ();
90         if (_listen_thread) {
91                 /* Ideally this would be a DCPOMATIC_ASSERT(_listen_thread->joinable()) but we
92                    can't throw exceptions from a destructor.
93                 */
94                 if (_listen_thread->joinable ()) {
95                         _listen_thread->join ();
96                 }
97         }
98         delete _listen_thread;
99         _listen_thread = 0;
100
101         boost::mutex::scoped_lock lm (_servers_mutex);
102         _good_servers.clear ();
103         _bad_servers.clear ();
104 }
105
106 static bool
107 remove_missing (list<EncodeServerDescription>& servers, int since)
108 {
109         bool removed = false;
110         list<EncodeServerDescription>::iterator i = servers.begin();
111         while (i != servers.end()) {
112                 if (i->last_seen_seconds() > since) {
113                         list<EncodeServerDescription>::iterator j = i;
114                         ++j;
115                         servers.erase (i);
116                         i = j;
117                         removed = true;
118                 } else {
119                         ++i;
120                 }
121         }
122         return removed;
123 }
124
125 void
126 EncodeServerFinder::search_thread ()
127 try
128 {
129         boost::system::error_code error;
130         boost::asio::io_service io_service;
131         boost::asio::ip::udp::socket socket (io_service);
132         socket.open (boost::asio::ip::udp::v4(), error);
133         if (error) {
134                 throw NetworkError ("failed to set up broadcast socket");
135         }
136
137         socket.set_option (boost::asio::ip::udp::socket::reuse_address (true));
138         socket.set_option (boost::asio::socket_base::broadcast (true));
139
140         string const data = DCPOMATIC_HELLO;
141         int const interval = 10;
142
143         while (!_stop) {
144                 if (Config::instance()->use_any_servers ()) {
145                         /* Broadcast to look for servers */
146                         try {
147                                 boost::asio::ip::udp::endpoint end_point (boost::asio::ip::address_v4::broadcast(), HELLO_PORT);
148                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
149                         } catch (...) {
150
151                         }
152                 }
153
154                 /* Query our `definite' servers (if there are any) */
155                 vector<string> servers = Config::instance()->servers ();
156                 for (vector<string>::const_iterator i = servers.begin(); i != servers.end(); ++i) {
157                         if (server_found (*i)) {
158                                 /* Don't bother asking a server that we already know about */
159                                 continue;
160                         }
161                         try {
162                                 boost::asio::ip::udp::resolver resolver (io_service);
163                                 boost::asio::ip::udp::resolver::query query (*i, raw_convert<string> (HELLO_PORT));
164                                 boost::asio::ip::udp::endpoint end_point (*resolver.resolve (query));
165                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
166                         } catch (...) {
167
168                         }
169                 }
170
171                 /* Discard servers that we haven't seen for a while */
172                 {
173                         boost::mutex::scoped_lock lm (_servers_mutex);
174                         bool g = remove_missing(_good_servers, 2 * interval);
175                         bool b = remove_missing(_bad_servers, 2 * interval);
176                         if (g || b) {
177                                 emit (boost::bind (boost::ref (ServersListChanged)));
178                         }
179                 }
180
181                 boost::mutex::scoped_lock lm (_search_condition_mutex);
182                 _search_condition.timed_wait (lm, boost::get_system_time() + boost::posix_time::seconds (interval));
183         }
184 }
185 catch (...)
186 {
187         store_current ();
188 }
189
190 void
191 EncodeServerFinder::listen_thread ()
192 try {
193         using namespace boost::asio::ip;
194
195         try {
196                 _listen_acceptor.reset (
197                         new tcp::acceptor (_listen_io_service, tcp::endpoint (tcp::v4(), is_batch_converter ? BATCH_SERVER_PRESENCE_PORT : MAIN_SERVER_PRESENCE_PORT))
198                         );
199         } catch (...) {
200                 boost::throw_exception (NetworkError (_("Could not listen for remote encode servers.  Perhaps another instance of DCP-o-matic is running.")));
201         }
202
203         start_accept ();
204         _listen_io_service.run ();
205 }
206 catch (...)
207 {
208         store_current ();
209 }
210
211 void
212 EncodeServerFinder::start_accept ()
213 {
214         shared_ptr<Socket> socket (new Socket ());
215         _listen_acceptor->async_accept (
216                 socket->socket(),
217                 boost::bind (&EncodeServerFinder::handle_accept, this, boost::asio::placeholders::error, socket)
218                 );
219 }
220
221 void
222 EncodeServerFinder::handle_accept (boost::system::error_code ec, shared_ptr<Socket> socket)
223 {
224         if (ec) {
225                 start_accept ();
226                 return;
227         }
228
229         uint32_t length;
230         socket->read (reinterpret_cast<uint8_t*> (&length), sizeof (uint32_t));
231         length = ntohl (length);
232
233         scoped_array<char> buffer (new char[length]);
234         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
235
236         string s (buffer.get());
237         shared_ptr<cxml::Document> xml (new cxml::Document ("ServerAvailable"));
238         xml->read_string (s);
239
240         string const ip = socket->socket().remote_endpoint().address().to_string ();
241         optional<list<EncodeServerDescription>::iterator> found = server_found (ip);
242         if (found) {
243                 (*found)->set_seen ();
244         } else {
245                 EncodeServerDescription sd (ip, xml->number_child<int>("Threads"), xml->optional_number_child<int>("Version").get_value_or(0));
246                 if (sd.link_version() == SERVER_LINK_VERSION) {
247                         boost::mutex::scoped_lock lm (_servers_mutex);
248                         _good_servers.push_back (sd);
249                 } else {
250                         boost::mutex::scoped_lock lm (_servers_mutex);
251                         _bad_servers.push_back (sd);
252                 }
253                 emit (boost::bind (boost::ref (ServersListChanged)));
254         }
255
256         start_accept ();
257 }
258
259 optional<list<EncodeServerDescription>::iterator>
260 EncodeServerFinder::server_found (string ip)
261 {
262         boost::mutex::scoped_lock lm (_servers_mutex);
263         list<EncodeServerDescription>::iterator i = _good_servers.begin();
264         while (i != _good_servers.end() && i->host_name() != ip) {
265                 ++i;
266         }
267
268         if (i != _good_servers.end()) {
269                 return i;
270         }
271
272         i = _bad_servers.begin();
273         while (i != _bad_servers.end() && i->host_name() != ip) {
274                 ++i;
275         }
276
277         if (i != _bad_servers.end()) {
278                 return i;
279         }
280
281         return optional<list<EncodeServerDescription>::iterator>();
282 }
283
284 EncodeServerFinder*
285 EncodeServerFinder::instance ()
286 {
287         if (!_instance) {
288                 _instance = new EncodeServerFinder ();
289                 _instance->start ();
290         }
291
292         return _instance;
293 }
294
295 void
296 EncodeServerFinder::drop ()
297 {
298         delete _instance;
299         _instance = 0;
300 }
301
302 list<EncodeServerDescription>
303 EncodeServerFinder::good_servers () const
304 {
305         boost::mutex::scoped_lock lm (_servers_mutex);
306         return _good_servers;
307 }
308
309 list<EncodeServerDescription>
310 EncodeServerFinder::bad_servers () const
311 {
312         boost::mutex::scoped_lock lm (_servers_mutex);
313         return _bad_servers;
314 }
315
316 void
317 EncodeServerFinder::config_changed (Config::Property what)
318 {
319         if (what == Config::USE_ANY_SERVERS || what == Config::SERVERS) {
320                 {
321                         boost::mutex::scoped_lock lm (_servers_mutex);
322                         _good_servers.clear ();
323                         _bad_servers.clear ();
324                 }
325                 ServersListChanged ();
326                 _search_condition.notify_all ();
327         }
328 }