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