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