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