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 // helper functions ///////////////////////////////////////////////////////////
100 ///////////////////////////////////////////////////////////////////////////////
101 string stripPath(string path)
103 // svn doesn't like trailing white-spaces or path separators - strip them!
104 path = simgear::strutils::strip(path);
105 int slen = path.length();
107 (path[slen-1]=='/')||(path[slen-1]=='\\'))
111 return path.substr(0,slen);
114 ///////////////////////////////////////////////////////////////////////////////
115 // WaitingTile ////////////////////////////////////////////////////////////////
116 ///////////////////////////////////////////////////////////////////////////////
120 WaitingTile(string dir,bool refresh) :
121 _dir(dir), _refreshScenery(refresh) {}
123 bool _refreshScenery;
126 ///////////////////////////////////////////////////////////////////////////////
127 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
128 ///////////////////////////////////////////////////////////////////////////////
129 class SGTerraSync::SvnThread : public OpenThreads::Thread
133 virtual ~SvnThread( ) { stop(); }
138 bool isIdle() {return waitingTiles.empty();}
139 void request(const WaitingTile& dir) {waitingTiles.push_front(dir);}
140 bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
141 bool hasNewTiles() { return !_freshTiles.empty();}
142 WaitingTile getNewTile() { return _freshTiles.pop_front();}
144 void setSvnServer(string server) { _svn_server = stripPath(server);}
145 void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);}
146 void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);}
147 void setLocalDir(string dir) { _local_dir = stripPath(dir);}
148 string getLocalDir() { return _local_dir;}
149 void setUseSvn(bool use_svn) { _use_svn = use_svn;}
151 #ifdef HAVE_SVN_CLIENT_H
152 void setUseBuiltin(bool built_in) { _use_built_in = built_in;}
155 volatile bool _active;
156 volatile bool _running;
158 volatile bool _stalled;
159 volatile int _fail_count;
160 volatile int _updated_tile_count;
161 volatile int _success_count;
162 volatile int _consecutive_errors;
166 bool syncTree(const char* dir, bool& isNewDirectory);
167 bool syncTreeExternal(const char* dir);
169 #ifdef HAVE_SVN_CLIENT_H
170 static int svnClientSetup(void);
171 bool syncTreeInternal(const char* dir);
175 // Things we need for doing subversion checkout - often
176 static apr_pool_t *_svn_pool;
177 static svn_client_ctx_t *_svn_ctx;
178 static svn_opt_revision_t *_svn_rev;
179 static svn_opt_revision_t *_svn_rev_peg;
182 volatile bool _is_dirty;
184 SGBlockingDeque <WaitingTile> waitingTiles;
185 CompletedTiles _completedTiles;
186 SGBlockingDeque <WaitingTile> _freshTiles;
190 string _rsync_server;
194 #ifdef HAVE_SVN_CLIENT_H
195 apr_pool_t* SGTerraSync::SvnThread::_svn_pool = NULL;
196 svn_client_ctx_t* SGTerraSync::SvnThread::_svn_ctx = NULL;
197 svn_opt_revision_t* SGTerraSync::SvnThread::_svn_rev = NULL;
198 svn_opt_revision_t* SGTerraSync::SvnThread::_svn_rev_peg = NULL;
201 SGTerraSync::SvnThread::SvnThread() :
207 _updated_tile_count(0),
209 _consecutive_errors(0),
210 #ifdef HAVE_SVN_CLIENT_H
217 #ifdef HAVE_SVN_CLIENT_H
218 int errCode = SGTerraSync::SvnThread::svnClientSetup();
219 if (errCode != EXIT_SUCCESS)
221 SG_LOG(SG_TERRAIN,SG_ALERT,
222 "Failed to initialize built-in SVN client, error = " << errCode);
227 void SGTerraSync::SvnThread::stop()
229 // drop any pending requests
230 waitingTiles.clear();
235 // set stop flag and wake up the thread with an empty request
237 WaitingTile w("",false);
243 bool SGTerraSync::SvnThread::start()
250 SG_LOG(SG_TERRAIN,SG_ALERT,
251 "Cannot start scenery download. Local cache directory is undefined.");
257 SGPath path(_local_dir);
260 SG_LOG(SG_TERRAIN,SG_ALERT,
261 "Cannot start scenery download. Directory '" << _local_dir <<
262 "' does not exist. Set correct directory path or create directory folder.");
268 path.append("version");
271 SG_LOG(SG_TERRAIN,SG_ALERT,
272 "Cannot start scenery download. Directory '" << _local_dir <<
273 "' contains the base package. Use a separate directory.");
278 #ifdef HAVE_SVN_CLIENT_H
279 _use_svn |= _use_built_in;
282 if ((_use_svn)&&(_svn_server==""))
284 SG_LOG(SG_TERRAIN,SG_ALERT,
285 "Cannot start scenery download. Subversion scenery server is undefined.");
291 if ((!_use_svn)&&(_rsync_server==""))
293 SG_LOG(SG_TERRAIN,SG_ALERT,
294 "Cannot start scenery download. Rsync scenery server is undefined.");
301 _updated_tile_count = 0;
303 _consecutive_errors = 0;
309 #ifdef HAVE_SVN_CLIENT_H
310 if (_use_svn && _use_built_in)
311 status = "Using built-in SVN support. ";
316 status = "Using external SVN utility '";
317 status += _svn_command;
322 status = "Using RSYNC. ";
325 // not really an alert - but we want to (always) see this message, so user is
326 // aware we're downloading scenery (and using bandwidth).
327 SG_LOG(SG_TERRAIN,SG_ALERT,
328 "Starting automatic scenery download/synchronization. "
330 << "Directory: '" << _local_dir << "'.");
332 OpenThreads::Thread::start();
336 // sync one directory tree
337 bool SGTerraSync::SvnThread::syncTree(const char* dir, bool& isNewDirectory)
340 SGPath path( _local_dir );
343 isNewDirectory = !path.exists();
346 rc = path.create_dir( 0755 );
349 SG_LOG(SG_TERRAIN,SG_ALERT,
350 "Cannot create directory '" << dir << "', return code = " << rc );
355 #ifdef HAVE_SVN_CLIENT_H
357 return syncTreeInternal(dir);
361 return syncTreeExternal(dir);
366 #ifdef HAVE_SVN_CLIENT_H
367 bool SGTerraSync::SvnThread::syncTreeInternal(const char* dir)
369 SG_LOG(SG_TERRAIN,SG_DEBUG, "Synchronizing scenery directory " << dir);
372 SG_LOG(SG_TERRAIN,SG_ALERT,
373 "Built-in SVN client failed to initialize.");
378 char dest_base_dir[512];
379 snprintf( command, 512,
380 "%s/%s", _svn_server.c_str(), dir);
381 snprintf( dest_base_dir, 512,
382 "%s/%s", _local_dir.c_str(), dir);
384 apr_pool_t *subpool = svn_pool_create(_svn_pool);
386 svn_error_t *err = NULL;
387 #if (SVN_VER_MINOR >= 5)
388 err = svn_client_checkout3(NULL,
394 0, // ignore-externals = false
395 0, // allow unver obstructions = false
400 err = svn_client_checkout2(NULL,
405 1, // recurse=true - same as svn_depth_infinity for checkout3 above
406 0, // ignore externals = false
411 bool ReturnValue = true;
414 // Report errors from the checkout attempt
415 if (err->apr_err == SVN_ERR_RA_ILLEGAL_URL)
417 // ignore errors when remote path doesn't exist (no scenery data for ocean areas)
421 SG_LOG(SG_TERRAIN,SG_ALERT,
422 "Failed to synchronize directory '" << dir << "', " <<
423 err->message << " (code " << err->apr_err << ").");
424 svn_error_clear(err);
426 err = svn_client_cleanup(dest_base_dir,
430 SG_LOG(SG_TERRAIN,SG_ALERT,
431 "SVN repository cleanup successful for '" << dir << "'.");
437 SG_LOG(SG_TERRAIN,SG_DEBUG, "Done with scenery directory " << dir);
439 svn_pool_destroy(subpool);
444 bool SGTerraSync::SvnThread::syncTreeExternal(const char* dir)
450 snprintf( command, 512,
451 "\"%s\" %s %s/%s \"%s/%s\"", _svn_command.c_str(), svn_options,
452 _svn_server.c_str(), dir,
453 _local_dir.c_str(), dir );
455 snprintf( command, 512,
456 "%s %s/%s/ \"%s/%s/\"", rsync_cmd,
457 _rsync_server.c_str(), dir,
458 _local_dir.c_str(), dir );
460 SG_LOG(SG_TERRAIN,SG_DEBUG, "sync command '" << command << "'");
461 rc = system( command );
464 SG_LOG(SG_TERRAIN,SG_ALERT,
465 "Failed to synchronize directory '" << dir << "', " <<
466 "error code= " << rc);
472 void SGTerraSync::SvnThread::run()
477 WaitingTile next = waitingTiles.pop_front();
481 CompletedTiles::iterator ii =
482 _completedTiles.find( next._dir );
483 time_t now = time(0);
484 if ((ii == _completedTiles.end())||
485 ((ii->second + 60*60*24) < now ))
487 bool isNewDirectory = false;
490 if (!syncTree(next._dir.c_str(),isNewDirectory))
492 _consecutive_errors++;
497 _consecutive_errors = 0;
499 SG_LOG(SG_TERRAIN,SG_INFO,
500 "Successfully synchronized directory '" << next._dir << "'");
501 if (next._refreshScenery)
504 _updated_tile_count++;
507 // for now only report new directories to refresh display
508 // (i.e. only when ocean needs to be replaced with actual data)
509 _freshTiles.push_back(next);
515 _completedTiles[ next._dir ] = now;
518 if (_consecutive_errors >= 5)
530 #ifdef HAVE_SVN_CLIENT_H
531 // Configure our subversion session
532 int SGTerraSync::SvnThread::svnClientSetup(void)
534 // Are we already prepared?
535 if (_svn_pool) return EXIT_SUCCESS;
536 // No, so initialize svn internals generally
539 // there is a segfault when providing an error stream.
540 // Apparently, calling setvbuf with a nul buffer is
541 // not supported under msvc 7.1 ( code inside svn_cmdline_init )
542 if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
545 if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
548 /* Oh no! svn_cmdline_init configures the locale - affecting numeric output
549 * formats (i.e. sprintf("%f", ...)). fgfs relies on "C" locale in many places
550 * (including assumptions on required sprintf buffer sizes). Things go horribly
551 * wrong when the locale is changed to anything else but "C". Might be enough to
552 * revert LC_NUMERIC locale - but we'll do a complete revert for now...*/
553 setlocale(LC_ALL,"C");
556 apr_pool_create(&pool, NULL);
557 svn_error_t *err = NULL;
558 SVN_VERSION_DEFINE(_svn_version);
559 err = svn_ver_check_list(&_svn_version, mysvn_checklist);
561 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
562 err = svn_ra_initialize(pool);
564 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
565 char *config_dir = NULL;
566 err = svn_config_ensure(config_dir, pool);
568 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
569 err = svn_client_create_context(&_svn_ctx, pool);
571 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
572 err = svn_config_get_config(&(_svn_ctx->config),
575 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
577 cfg = ( svn_config_t*) apr_hash_get(
579 SVN_CONFIG_CATEGORY_CONFIG,
580 APR_HASH_KEY_STRING);
582 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
584 svn_auth_baton_t *ab=NULL;
586 #if (SVN_VER_MINOR >= 6)
587 err = svn_cmdline_create_auth_baton (&ab,
588 TRUE, NULL, NULL, config_dir, TRUE, FALSE, cfg,
589 _svn_ctx->cancel_func, _svn_ctx->cancel_baton, pool);
591 err = svn_cmdline_setup_auth_baton(&ab,
592 TRUE, NULL, NULL, config_dir, TRUE, cfg,
593 _svn_ctx->cancel_func, _svn_ctx->cancel_baton, pool);
597 return svn_cmdline_handle_exit_error(err, pool, "fgfs: ");
599 _svn_ctx->auth_baton = ab;
600 #if (SVN_VER_MINOR >= 5)
601 _svn_ctx->conflict_func = NULL;
602 _svn_ctx->conflict_baton = NULL;
605 // Now our magic revisions
606 _svn_rev = (svn_opt_revision_t*) apr_palloc(pool,
607 sizeof(svn_opt_revision_t));
610 _svn_rev_peg = (svn_opt_revision_t*) apr_palloc(pool,
611 sizeof(svn_opt_revision_t));
614 _svn_rev->kind = svn_opt_revision_head;
615 _svn_rev_peg->kind = svn_opt_revision_unspecified;
616 // Success if we got this far
622 ///////////////////////////////////////////////////////////////////////////////
623 // SGTerraSync ////////////////////////////////////////////////////////////////
624 ///////////////////////////////////////////////////////////////////////////////
625 SGTerraSync::SGTerraSync(SGPropertyNode_ptr root) :
629 _terraRoot(root->getNode("/sim/terrasync",true)),
632 _svnThread = new SvnThread();
635 SGTerraSync::~SGTerraSync()
637 _tiedProperties.Untie();
642 void SGTerraSync::init()
644 _refresh_display = _terraRoot->getNode("refresh-display",true);
645 _terraRoot->getNode("built-in-svn-available",true)->setBoolValue(svn_built_in_available);
649 void SGTerraSync::reinit()
651 // do not reinit when enabled and we're already up and running
652 if ((_terraRoot->getBoolValue("enabled",false))&&
653 (_svnThread->_active && _svnThread->_running))
658 if (_terraRoot->getBoolValue("enabled",false))
660 _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
661 _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
662 _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
664 #ifdef HAVE_SVN_CLIENT_H
665 _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
667 _terraRoot->getNode("use-built-in-svn",true)->setBoolValue(false);
669 _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
670 _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
672 if (_svnThread->start())
673 syncAirportsModels();
676 _stalled_node->setBoolValue(_svnThread->_stalled);
681 void SGTerraSync::bind()
683 _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
684 _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
685 _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
686 _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
687 _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
688 _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
689 _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
690 _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
691 _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
692 _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
693 _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
694 _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
695 // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
696 _stalled_node = _terraRoot->getNode("stalled", true);
697 _stalled_node->setBoolValue(_svnThread->_stalled);
698 _stalled_node->setAttribute(SGPropertyNode::PRESERVE,true);
701 void SGTerraSync::unbind()
704 _tiedProperties.Untie();
707 void SGTerraSync::update(double)
709 static SGBucket bucket;
710 if (_svnThread->isDirty())
712 if (!_svnThread->_active)
714 if (_svnThread->_stalled)
716 SG_LOG(SG_TERRAIN,SG_ALERT,
717 "Automatic scenery download/synchronization stalled. Too many errors.");
721 // not really an alert - just always show this message
722 SG_LOG(SG_TERRAIN,SG_ALERT,
723 "Automatic scenery download/synchronization has stopped.");
725 _stalled_node->setBoolValue(_svnThread->_stalled);
728 if (!_refresh_display->getBoolValue())
731 while (_svnThread->hasNewTiles())
733 WaitingTile next = _svnThread->getNewTile();
734 if (next._refreshScenery)
736 refreshScenery(_svnThread->getLocalDir(),next._dir);
742 void SGTerraSync::refreshScenery(SGPath path,const string& relativeDir)
744 // find tiles to be refreshed
747 path.append(relativeDir);
750 simgear::Dir dir(path);
751 //TODO need to be smarter here. only update tiles which actually
752 // changed recently. May also be possible to use information from the
753 // built-in SVN client directly (instead of checking directory contents).
754 PathList tileList = dir.children(simgear::Dir::TYPE_FILE, ".stg");
755 for (unsigned int i=0; i<tileList.size(); ++i)
757 // reload scenery tile
758 long index = atoi(tileList[i].file().c_str());
759 _tile_cache->refresh_tile(index);
765 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
767 void SGTerraSync::setTileCache(TileCache* tile_cache)
769 _tile_cache = tile_cache;
772 void SGTerraSync::syncAirportsModels()
775 for ( synced_other = 'K'; synced_other <= 'Z'; synced_other++ )
778 snprintf( dir, 512, "Airports/%c", synced_other );
779 WaitingTile w(dir,false);
780 _svnThread->request( w );
782 for ( synced_other = 'A'; synced_other <= 'J'; synced_other++ )
785 snprintf( dir, 512, "Airports/%c", synced_other );
786 WaitingTile w(dir,false);
787 _svnThread->request( w );
789 WaitingTile w("Models",false);
790 _svnThread->request( w );
794 void SGTerraSync::syncArea( int lat, int lon )
796 if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
799 int baselat, baselon;
802 int base = (int)(lat / 10);
803 if ( lat == base * 10 ) {
806 baselat = (base - 1) * 10;
810 baselat = (int)(lat / 10) * 10;
814 int base = (int)(lon / 10);
815 if ( lon == base * 10 ) {
818 baselon = (base - 1) * 10;
822 baselon = (int)(lon / 10) * 10;
826 const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
828 for (const char** tree = &terrainobjects[0]; *tree; tree++)
831 snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
833 EW, abs(baselon), NS, abs(baselat),
834 EW, abs(lon), NS, abs(lat) );
835 WaitingTile w(dir,refresh);
836 _svnThread->request( w );
842 void SGTerraSync::syncAreas( int lat, int lon, int lat_dir, int lon_dir )
844 if ( lat_dir == 0 && lon_dir == 0 ) {
845 // do surrounding 8 1x1 degree areas.
846 for ( int i = lat - 1; i <= lat + 1; ++i ) {
847 for ( int j = lon - 1; j <= lon + 1; ++j ) {
848 if ( i != lat || j != lon ) {
854 if ( lat_dir != 0 ) {
855 syncArea( lat + lat_dir, lon - 1 );
856 syncArea( lat + lat_dir, lon + 1 );
857 syncArea( lat + lat_dir, lon );
859 if ( lon_dir != 0 ) {
860 syncArea( lat - 1, lon + lon_dir );
861 syncArea( lat + 1, lon + lon_dir );
862 syncArea( lat, lon + lon_dir );
866 // do current 1x1 degree area first
867 syncArea( lat, lon );
871 bool SGTerraSync::schedulePosition(int lat, int lon)
873 // Ignore messages where the location does not change
874 if ( lat != last_lat || lon != last_lon )
876 SG_LOG(SG_TERRAIN,SG_DEBUG, "Requesting scenery update for position " <<
878 int lat_dir, lon_dir, dist;
879 if ( last_lat == NOWHERE || last_lon == NOWHERE )
881 lat_dir = lon_dir = 0;
884 dist = lat - last_lat;
887 lat_dir = dist / abs(dist);
893 dist = lon - last_lon;
896 lon_dir = dist / abs(dist);
903 SG_LOG(SG_TERRAIN,SG_DEBUG, "Scenery update for " <<
904 "lat = " << lat << ", lon = " << lon <<
905 ", lat_dir = " << lat_dir << ", " <<
906 "lon_dir = " << lon_dir);
908 syncAreas( lat, lon, lat_dir, lon_dir );