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