1 // terrasync.cxx -- scenery fetcher
3 // Started by Curtis Olson, November 2002.
5 // Copyright (C) 2002 Curtis L. Olson - http://www.flightgear.org/~curt
6 // Copyright (C) 2008 Alexander R. Perry <alex.perry@ieee.org>
7 // Copyright (C) 2011 Thorsten Brehm <brehmt@gmail.com>
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 # include <simgear_config.h>
29 #include <simgear/compiler.h>
38 #elif defined(_MSC_VER)
40 # ifndef HAVE_SVN_CLIENT_H
46 #include <stdlib.h> // atoi() atof() abs() system()
47 #include <signal.h> // signal()
54 #include <simgear/compiler.h>
56 #include "terrasync.hxx"
57 #include <simgear/bucket/newbucket.hxx>
58 #include <simgear/misc/sg_path.hxx>
59 #include <simgear/misc/strutils.hxx>
60 #include <simgear/threads/SGQueue.hxx>
61 #include <simgear/scene/tgdb/TileCache.hxx>
62 #include <simgear/misc/sg_dir.hxx>
63 #include <OpenThreads/Thread>
65 #ifdef HAVE_SVN_CLIENT_H
66 # ifdef HAVE_LIBSVN_CLIENT_1
67 # include <svn_version.h>
68 # include <svn_auth.h>
69 # include <svn_client.h>
70 # include <svn_cmdline.h>
71 # include <svn_pools.h>
73 # undef HAVE_SVN_CLIENT_H
77 #ifdef HAVE_SVN_CLIENT_H
78 static const svn_version_checklist_t mysvn_checklist[] = {
79 { "svn_subr", svn_subr_version },
80 { "svn_client", svn_client_version },
83 static const bool svn_built_in_available = true;
85 static const bool svn_built_in_available = false;
88 using namespace simgear;
90 const char* rsync_cmd =
91 "rsync --verbose --archive --delete --perms --owner --group";
93 const char* svn_options =
96 typedef map<string,time_t> CompletedTiles;
98 ///////////////////////////////////////////////////////////////////////////////
99 // WaitingTile ////////////////////////////////////////////////////////////////
100 ///////////////////////////////////////////////////////////////////////////////
104 WaitingTile(string dir,bool refresh) :
105 _dir(dir), _refreshScenery(refresh) {}
107 bool _refreshScenery;
110 ///////////////////////////////////////////////////////////////////////////////
111 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
112 ///////////////////////////////////////////////////////////////////////////////
113 class SGTerraSync::SvnThread : public OpenThreads::Thread
117 virtual ~SvnThread( ) { stop(); }
122 bool isIdle() {return waitingTiles.empty();}
123 void request(const WaitingTile& dir) {waitingTiles.push_front(dir);}
124 bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
125 bool hasNewTiles() { return !_freshTiles.empty();}
126 WaitingTile getNewTile() { return _freshTiles.pop_front();}
128 void setSvnServer(string server) { _svn_server = simgear::strutils::strip(server);}
129 void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);}
130 void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);}
131 void setLocalDir(string dir) { _local_dir = simgear::strutils::strip(dir);}
132 string getLocalDir() { return _local_dir;}
133 void setUseSvn(bool use_svn) { _use_svn = use_svn;}
135 #ifdef HAVE_SVN_CLIENT_H
136 void setUseBuiltin(bool built_in) { _use_built_in = built_in;}
139 volatile bool _active;
140 volatile bool _running;
142 volatile bool _stalled;
143 volatile int _fail_count;
144 volatile int _updated_tile_count;
145 volatile int _success_count;
146 volatile int _consecutive_errors;
150 bool syncTree(const char* dir, bool& isNewDirectory);
151 bool syncTreeExternal(const char* dir);
153 #ifdef HAVE_SVN_CLIENT_H
154 static int svnClientSetup(void);
155 bool syncTreeInternal(const char* dir);
159 // Things we need for doing subversion checkout - often
160 static apr_pool_t *_svn_pool;
161 static svn_client_ctx_t *_svn_ctx;
162 static svn_opt_revision_t *_svn_rev;
163 static svn_opt_revision_t *_svn_rev_peg;
166 volatile bool _is_dirty;
168 SGBlockingDeque <WaitingTile> waitingTiles;
169 CompletedTiles _completedTiles;
170 SGBlockingDeque <WaitingTile> _freshTiles;
174 string _rsync_server;
178 #ifdef HAVE_SVN_CLIENT_H
179 apr_pool_t* SGTerraSync::SvnThread::_svn_pool = NULL;
180 svn_client_ctx_t* SGTerraSync::SvnThread::_svn_ctx = NULL;
181 svn_opt_revision_t* SGTerraSync::SvnThread::_svn_rev = NULL;
182 svn_opt_revision_t* SGTerraSync::SvnThread::_svn_rev_peg = NULL;
185 SGTerraSync::SvnThread::SvnThread() :
191 _updated_tile_count(0),
193 _consecutive_errors(0),
194 #ifdef HAVE_SVN_CLIENT_H
201 #ifdef HAVE_SVN_CLIENT_H
202 int errCode = SGTerraSync::SvnThread::svnClientSetup();
203 if (errCode != EXIT_SUCCESS)
205 SG_LOG(SG_TERRAIN,SG_ALERT,
206 "Failed to initialize built-in SVN client, error = " << errCode);
211 void SGTerraSync::SvnThread::stop()
213 // drop any pending requests
214 waitingTiles.clear();
219 // set stop flag and wake up the thread with an empty request
221 WaitingTile w("",false);
227 bool SGTerraSync::SvnThread::start()
234 SG_LOG(SG_TERRAIN,SG_ALERT,
235 "Cannot start scenery download. Local cache directory is undefined.");
241 SGPath path(_local_dir);
244 SG_LOG(SG_TERRAIN,SG_ALERT,
245 "Cannot start scenery download. Directory '" << _local_dir <<
246 "' does not exist. Set correct directory path or create directory folder.");
252 path.append("version");
255 SG_LOG(SG_TERRAIN,SG_ALERT,
256 "Cannot start scenery download. Directory '" << _local_dir <<
257 "' contains the base package. Use a separate directory.");
262 #ifdef HAVE_SVN_CLIENT_H
263 _use_svn |= _use_built_in;
266 if ((_use_svn)&&(_svn_server==""))
268 SG_LOG(SG_TERRAIN,SG_ALERT,
269 "Cannot start scenery download. Subversion scenery server is undefined.");
275 if ((!_use_svn)&&(_rsync_server==""))
277 SG_LOG(SG_TERRAIN,SG_ALERT,
278 "Cannot start scenery download. Rsync scenery server is undefined.");
285 _updated_tile_count = 0;
287 _consecutive_errors = 0;
293 #ifdef HAVE_SVN_CLIENT_H
294 if (_use_svn && _use_built_in)
295 status = "Using built-in SVN support. ";
300 status = "Using external SVN utility '";
301 status += _svn_command;
306 status = "Using RSYNC. ";
309 // not really an alert - but we want to (always) see this message, so user is
310 // aware we're downloading scenery (and using bandwidth).
311 SG_LOG(SG_TERRAIN,SG_ALERT,
312 "Starting automatic scenery download/synchronization. "
314 << "Directory: '" << _local_dir << "'.");
316 OpenThreads::Thread::start();
320 // sync one directory tree
321 bool SGTerraSync::SvnThread::syncTree(const char* dir, bool& isNewDirectory)
324 SGPath path( _local_dir );
327 isNewDirectory = !path.exists();
330 rc = path.create_dir( 0755 );
333 SG_LOG(SG_TERRAIN,SG_ALERT,
334 "Cannot create directory '" << dir << "', return code = " << rc );
339 #ifdef HAVE_SVN_CLIENT_H
341 return syncTreeInternal(dir);
345 return syncTreeExternal(dir);
350 #ifdef HAVE_SVN_CLIENT_H
351 bool SGTerraSync::SvnThread::syncTreeInternal(const char* dir)
353 SG_LOG(SG_TERRAIN,SG_DEBUG, "Synchronizing scenery directory " << dir);
356 SG_LOG(SG_TERRAIN,SG_ALERT,
357 "Built-in SVN client failed to initialize.");
362 char dest_base_dir[512];
363 snprintf( command, 512,
364 "%s/%s", _svn_server.c_str(), dir);
365 snprintf( dest_base_dir, 512,
366 "%s/%s", _local_dir.c_str(), dir);
368 apr_pool_t *subpool = svn_pool_create(_svn_pool);
370 svn_error_t *err = NULL;
371 #if (SVN_VER_MINOR >= 5)
372 err = svn_client_checkout3(NULL,
378 0, // ignore-externals = false
379 0, // allow unver obstructions = false
384 err = svn_client_checkout2(NULL,
389 1, // recurse=true - same as svn_depth_infinity for checkout3 above
390 0, // ignore externals = false
395 bool ReturnValue = true;
398 // Report errors from the checkout attempt
399 if (err->apr_err == SVN_ERR_RA_ILLEGAL_URL)
401 // ignore errors when remote path doesn't exist (no scenery data for ocean areas)
405 SG_LOG(SG_TERRAIN,SG_ALERT,
406 "Failed to synchronize directory '" << dir << "', " <<
407 err->message << " (code " << err->apr_err << ").");
408 svn_error_clear(err);
410 err = svn_client_cleanup(dest_base_dir,
414 SG_LOG(SG_TERRAIN,SG_ALERT,
415 "SVN repository cleanup successful for '" << dir << "'.");
421 SG_LOG(SG_TERRAIN,SG_DEBUG, "Done with scenery directory " << dir);
423 svn_pool_destroy(subpool);
428 bool SGTerraSync::SvnThread::syncTreeExternal(const char* dir)
434 snprintf( command, 512,
435 "\"%s\" %s %s/%s \"%s/%s\"", _svn_command.c_str(), svn_options,
436 _svn_server.c_str(), dir,
437 _local_dir.c_str(), dir );
439 snprintf( command, 512,
440 "%s %s/%s/ \"%s/%s/\"", rsync_cmd,
441 _rsync_server.c_str(), dir,
442 _local_dir.c_str(), dir );
444 SG_LOG(SG_TERRAIN,SG_DEBUG, "sync command '" << command << "'");
445 rc = system( command );
448 SG_LOG(SG_TERRAIN,SG_ALERT,
449 "Failed to synchronize directory '" << dir << "', " <<
450 "error code= " << rc);
456 void SGTerraSync::SvnThread::run()
461 WaitingTile next = waitingTiles.pop_front();
465 CompletedTiles::iterator ii =
466 _completedTiles.find( next._dir );
467 time_t now = time(0);
468 if ((ii == _completedTiles.end())||
469 ((ii->second + 60*60*24) < now ))
471 bool isNewDirectory = false;
474 if (!syncTree(next._dir.c_str(),isNewDirectory))
476 _consecutive_errors++;
481 _consecutive_errors = 0;
483 SG_LOG(SG_TERRAIN,SG_INFO,
484 "Successfully synchronized directory '" << next._dir << "'");
485 if (next._refreshScenery)
488 _updated_tile_count++;
491 // for now only report new directories to refresh display
492 // (i.e. only when ocean needs to be replaced with actual data)
493 _freshTiles.push_back(next);
499 _completedTiles[ next._dir ] = now;
502 if (_consecutive_errors >= 5)
514 #ifdef HAVE_SVN_CLIENT_H
515 // Configure our subversion session
516 int SGTerraSync::SvnThread::svnClientSetup(void)
518 // Are we already prepared?
519 if (_svn_pool) return EXIT_SUCCESS;
520 // No, so initialize svn internals generally
523 // there is a segfault when providing an error stream.
524 // Apparently, calling setvbuf with a nul buffer is
525 // not supported under msvc 7.1 ( code inside svn_cmdline_init )
526 if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
529 if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
532 /* Oh no! svn_cmdline_init configures the locale - affecting numeric output
533 * formats (i.e. sprintf("%f", ...)). fgfs relies on "C" locale in many places
534 * (including assumptions on required sprintf buffer sizes). Things go horribly
535 * wrong when the locale is changed to anything else but "C". Might be enough to
536 * revert LC_NUMERIC locale - but we'll do a complete revert for now...*/
537 setlocale(LC_ALL,"C");
540 apr_pool_create(&pool, NULL);
541 svn_error_t *err = NULL;
542 SVN_VERSION_DEFINE(_svn_version);
543 err = svn_ver_check_list(&_svn_version, mysvn_checklist);
545 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
546 err = svn_ra_initialize(pool);
548 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
549 char *config_dir = NULL;
550 err = svn_config_ensure(config_dir, pool);
552 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
553 err = svn_client_create_context(&_svn_ctx, pool);
555 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
556 err = svn_config_get_config(&(_svn_ctx->config),
559 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
561 cfg = ( svn_config_t*) apr_hash_get(
563 SVN_CONFIG_CATEGORY_CONFIG,
564 APR_HASH_KEY_STRING);
566 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
568 svn_auth_baton_t *ab=NULL;
570 #if (SVN_VER_MINOR >= 6)
571 err = svn_cmdline_create_auth_baton (&ab,
572 TRUE, NULL, NULL, config_dir, TRUE, FALSE, cfg,
573 _svn_ctx->cancel_func, _svn_ctx->cancel_baton, pool);
575 err = svn_cmdline_setup_auth_baton(&ab,
576 TRUE, NULL, NULL, config_dir, TRUE, cfg,
577 _svn_ctx->cancel_func, _svn_ctx->cancel_baton, pool);
581 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
583 _svn_ctx->auth_baton = ab;
584 #if (SVN_VER_MINOR >= 5)
585 _svn_ctx->conflict_func = NULL;
586 _svn_ctx->conflict_baton = NULL;
589 // Now our magic revisions
590 _svn_rev = (svn_opt_revision_t*) apr_palloc(pool,
591 sizeof(svn_opt_revision_t));
594 _svn_rev_peg = (svn_opt_revision_t*) apr_palloc(pool,
595 sizeof(svn_opt_revision_t));
598 _svn_rev->kind = svn_opt_revision_head;
599 _svn_rev_peg->kind = svn_opt_revision_unspecified;
600 // Success if we got this far
606 ///////////////////////////////////////////////////////////////////////////////
607 // SGTerraSync ////////////////////////////////////////////////////////////////
608 ///////////////////////////////////////////////////////////////////////////////
609 SGTerraSync::SGTerraSync(SGPropertyNode_ptr root) :
613 _terraRoot(root->getNode("/sim/terrasync",true)),
616 _svnThread = new SvnThread();
619 SGTerraSync::~SGTerraSync()
621 _tiedProperties.Untie();
626 void SGTerraSync::init()
628 _refresh_display = _terraRoot->getNode("refresh-display",true);
629 _terraRoot->getNode("built-in-svn-available",true)->setBoolValue(svn_built_in_available);
633 void SGTerraSync::reinit()
635 // do not reinit when enabled and we're already up and running
636 if ((_terraRoot->getBoolValue("enabled",false))&&
637 (_svnThread->_active && _svnThread->_running))
642 if (_terraRoot->getBoolValue("enabled",false))
644 _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
645 _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
646 _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
648 #ifdef HAVE_SVN_CLIENT_H
649 _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
651 _terraRoot->getNode("use-built-in-svn",true)->setBoolValue(false);
653 _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
654 _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
656 if (_svnThread->start())
657 syncAirportsModels();
660 _stalled_node->setBoolValue(_svnThread->_stalled);
665 void SGTerraSync::bind()
667 _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
668 _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
669 _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
670 _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
671 _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
672 _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
673 _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
674 _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
675 _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
676 _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
677 _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
678 _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
679 // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
680 _stalled_node = _terraRoot->getNode("stalled", true);
681 _stalled_node->setBoolValue(_svnThread->_stalled);
682 _stalled_node->setAttribute(SGPropertyNode::PRESERVE,true);
685 void SGTerraSync::unbind()
688 _tiedProperties.Untie();
691 void SGTerraSync::update(double)
693 static SGBucket bucket;
694 if (_svnThread->isDirty())
696 if (!_svnThread->_active)
698 if (_svnThread->_stalled)
700 SG_LOG(SG_TERRAIN,SG_ALERT,
701 "Automatic scenery download/synchronization stalled. Too many errors.");
705 // not really an alert - just always show this message
706 SG_LOG(SG_TERRAIN,SG_ALERT,
707 "Automatic scenery download/synchronization has stopped.");
709 _stalled_node->setBoolValue(_svnThread->_stalled);
712 if (!_refresh_display->getBoolValue())
715 while (_svnThread->hasNewTiles())
717 WaitingTile next = _svnThread->getNewTile();
718 if (next._refreshScenery)
720 refreshScenery(_svnThread->getLocalDir(),next._dir);
726 void SGTerraSync::refreshScenery(SGPath path,const string& relativeDir)
728 // find tiles to be refreshed
731 path.append(relativeDir);
734 simgear::Dir dir(path);
735 //TODO need to be smarter here. only update tiles which actually
736 // changed recently. May also be possible to use information from the
737 // built-in SVN client directly (instead of checking directory contents).
738 PathList tileList = dir.children(simgear::Dir::TYPE_FILE, ".stg");
739 for (unsigned int i=0; i<tileList.size(); ++i)
741 // reload scenery tile
742 long index = atoi(tileList[i].file().c_str());
743 _tile_cache->refresh_tile(index);
749 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
751 void SGTerraSync::setTileCache(TileCache* tile_cache)
753 _tile_cache = tile_cache;
756 void SGTerraSync::syncAirportsModels()
759 for ( synced_other = 'K'; synced_other <= 'Z'; synced_other++ )
762 snprintf( dir, 512, "Airports/%c", synced_other );
763 WaitingTile w(dir,false);
764 _svnThread->request( w );
766 for ( synced_other = 'A'; synced_other <= 'J'; synced_other++ )
769 snprintf( dir, 512, "Airports/%c", synced_other );
770 WaitingTile w(dir,false);
771 _svnThread->request( w );
773 WaitingTile w("Models",false);
774 _svnThread->request( w );
778 void SGTerraSync::syncArea( int lat, int lon )
780 if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
783 int baselat, baselon;
786 int base = (int)(lat / 10);
787 if ( lat == base * 10 ) {
790 baselat = (base - 1) * 10;
794 baselat = (int)(lat / 10) * 10;
798 int base = (int)(lon / 10);
799 if ( lon == base * 10 ) {
802 baselon = (base - 1) * 10;
806 baselon = (int)(lon / 10) * 10;
810 const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
812 for (const char** tree = &terrainobjects[0]; *tree; tree++)
815 snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
817 EW, abs(baselon), NS, abs(baselat),
818 EW, abs(lon), NS, abs(lat) );
819 WaitingTile w(dir,refresh);
820 _svnThread->request( w );
826 void SGTerraSync::syncAreas( int lat, int lon, int lat_dir, int lon_dir )
828 if ( lat_dir == 0 && lon_dir == 0 ) {
829 // do surrounding 8 1x1 degree areas.
830 for ( int i = lat - 1; i <= lat + 1; ++i ) {
831 for ( int j = lon - 1; j <= lon + 1; ++j ) {
832 if ( i != lat || j != lon ) {
838 if ( lat_dir != 0 ) {
839 syncArea( lat + lat_dir, lon - 1 );
840 syncArea( lat + lat_dir, lon + 1 );
841 syncArea( lat + lat_dir, lon );
843 if ( lon_dir != 0 ) {
844 syncArea( lat - 1, lon + lon_dir );
845 syncArea( lat + 1, lon + lon_dir );
846 syncArea( lat, lon + lon_dir );
850 // do current 1x1 degree area first
851 syncArea( lat, lon );
855 bool SGTerraSync::schedulePosition(int lat, int lon)
857 // Ignore messages where the location does not change
858 if ( lat != last_lat || lon != last_lon )
860 SG_LOG(SG_TERRAIN,SG_DEBUG, "Requesting scenery update for position " <<
862 int lat_dir, lon_dir, dist;
863 if ( last_lat == NOWHERE || last_lon == NOWHERE )
865 lat_dir = lon_dir = 0;
868 dist = lat - last_lat;
871 lat_dir = dist / abs(dist);
877 dist = lon - last_lon;
880 lon_dir = dist / abs(dist);
887 SG_LOG(SG_TERRAIN,SG_DEBUG, "Scenery update for " <<
888 "lat = " << lat << ", lon = " << lon <<
889 ", lat_dir = " << lat_dir << ", " <<
890 "lon_dir = " << lon_dir);
892 syncAreas( lat, lon, lat_dir, lon_dir );