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