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