]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tsync/terrasync.cxx
Repository name preferred
[simgear.git] / simgear / scene / tsync / terrasync.cxx
1 // terrasync.cxx -- scenery fetcher
2 //
3 // Started by Curtis Olson, November 2002.
4 //
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>
8 //
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.
13 //
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.
18 //
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.
22 //
23 // $Id$
24
25 #ifdef HAVE_CONFIG_H
26 #  include <simgear_config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #ifdef HAVE_WINDOWS_H
32 #include <windows.h>
33 #endif
34
35 #ifdef __MINGW32__
36 #  include <time.h>
37 #  include <unistd.h>
38 #elif defined(_MSC_VER)
39 #   include <io.h>
40 #   include <time.h>
41 #   include <process.h>
42 #endif
43
44 #include <stdlib.h>             // atoi() atof() abs() system()
45 #include <signal.h>             // signal()
46 #include <string.h>
47
48 #include <iostream>
49 #include <fstream>
50 #include <string>
51 #include <map>
52
53 #include <simgear/compiler.h>
54
55 #include "terrasync.hxx"
56
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/misc/sg_dir.hxx>
62 #include <simgear/debug/BufferedLogCallback.hxx>
63 #include <simgear/props/props_io.hxx>
64 #include <simgear/io/HTTPClient.hxx>
65 #include <simgear/io/SVNRepository.hxx>
66 #include <simgear/structure/exception.hxx>
67
68 static const bool svn_built_in_available = true;
69
70 using namespace simgear;
71 using namespace std;
72
73 const char* rsync_cmd = 
74         "rsync --verbose --archive --delete --perms --owner --group";
75
76 const char* svn_options =
77         "checkout -q";
78
79 namespace UpdateInterval
80 {
81     // interval in seconds to allow an update to repeat after a successful update (=daily)
82     static const double SuccessfulAttempt = 24*60*60;
83     // interval in seconds to allow another update after a failed attempt (10 minutes)
84     static const double FailedAttempt     = 10*60;
85 }
86
87 typedef map<string,time_t> CompletedTiles;
88
89 ///////////////////////////////////////////////////////////////////////////////
90 // helper functions ///////////////////////////////////////////////////////////
91 ///////////////////////////////////////////////////////////////////////////////
92 string stripPath(string path)
93 {
94     // svn doesn't like trailing white-spaces or path separators - strip them!
95     path = simgear::strutils::strip(path);
96     size_t slen = path.length();
97     while ((slen>0)&&
98             ((path[slen-1]=='/')||(path[slen-1]=='\\')))
99     {
100         slen--;
101     }
102     return path.substr(0,slen);
103 }
104
105 bool hasWhitespace(string path)
106 {
107     return path.find(' ')!=string::npos;
108 }
109
110 ///////////////////////////////////////////////////////////////////////////////
111 // SyncItem ////////////////////////////////////////////////////////////
112 ///////////////////////////////////////////////////////////////////////////////
113 class SyncItem
114 {
115 public:
116     enum Type
117     {
118         Stop = 0,   ///< special item indicating to stop the SVNThread
119         Tile,
120         AirportData,
121         SharedModels,
122         AIData
123     };
124     
125     enum Status
126     {
127         Invalid = 0,
128         Waiting,
129         Cached, ///< using already cached result
130         Updated,
131         NotFound, 
132         Failed
133     };
134     
135     SyncItem() :
136         _dir(),
137         _type(Stop),
138         _status(Invalid)
139     {
140     }
141     
142     SyncItem(string dir, Type ty) :
143         _dir(dir),
144         _type(ty),
145         _status(Waiting)
146     {}
147         
148     string _dir;
149     Type _type;
150     Status _status;
151 };
152
153 ///////////////////////////////////////////////////////////////////////////////
154
155 /**
156  * @brief SyncSlot encapsulates a queue of sync items we will fetch
157  * serially. Multiple slots exist to sync different types of item in
158  * parallel.
159  */
160 class SyncSlot
161 {
162 public:
163     SyncSlot() :
164         isNewDirectory(false),
165         busy(false)
166     {}
167     
168     SyncItem currentItem;
169     bool isNewDirectory;
170     std::queue<SyncItem> queue;
171     std::auto_ptr<SVNRepository> repository;
172     SGTimeStamp stamp;
173     bool busy; ///< is the slot working or idle
174     
175     unsigned int nextWarnTimeout;
176 };
177
178 static const int SYNC_SLOT_TILES = 0; ///< Terrain and Objects sync
179 static const int SYNC_SLOT_SHARED_DATA = 1; /// shared Models and Airport data
180 static const int SYNC_SLOT_AI_DATA = 2; /// AI traffic and models
181 static const unsigned int NUM_SYNC_SLOTS = 3;
182
183 /**
184  * @brief translate a sync item type into one of the available slots.
185  * This provides the scheduling / balancing / prioritising between slots.
186  */
187 static unsigned int syncSlotForType(SyncItem::Type ty)
188 {
189     switch (ty) {
190     case SyncItem::Tile: return SYNC_SLOT_TILES;
191     case SyncItem::SharedModels:
192     case SyncItem::AirportData:
193         return SYNC_SLOT_SHARED_DATA;
194     case SyncItem::AIData:
195         return SYNC_SLOT_AI_DATA;
196         
197     default:
198         return SYNC_SLOT_SHARED_DATA;
199     }
200 }
201
202
203 ///////////////////////////////////////////////////////////////////////////////
204 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
205 ///////////////////////////////////////////////////////////////////////////////
206 class SGTerraSync::SvnThread : public SGThread
207 {
208 public:
209    SvnThread();
210    virtual ~SvnThread( ) { stop(); }
211
212    void stop();
213    bool start();
214
215     bool isIdle() {return !_busy; }
216    void request(const SyncItem& dir) {waitingTiles.push_front(dir);}
217    bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
218    bool hasNewTiles() { return !_freshTiles.empty();}
219    SyncItem getNewTile() { return _freshTiles.pop_front();}
220
221    void   setSvnServer(string server)       { _svn_server   = stripPath(server);}
222    void   setSvnDataServer(string server)   { _svn_data_server   = stripPath(server);}
223     
224    void   setExtSvnUtility(string svn_util) { _svn_command  = simgear::strutils::strip(svn_util);}
225    void   setRsyncServer(string server)     { _rsync_server = simgear::strutils::strip(server);}
226    void   setLocalDir(string dir)           { _local_dir    = stripPath(dir);}
227    string getLocalDir()                     { return _local_dir;}
228    void   setUseSvn(bool use_svn)           { _use_svn = use_svn;}
229    void   setAllowedErrorCount(int errors)  {_allowed_errors = errors;}
230
231    void   setCachePath(const SGPath& p)     {_persistentCachePath = p;}
232    void   setCacheHits(unsigned int hits)   {_cache_hits = hits;}
233    void   setUseBuiltin(bool built_in) { _use_built_in = built_in;}
234
235    volatile bool _active;
236    volatile bool _running;
237    volatile bool _busy;
238    volatile bool _stalled;
239    volatile int  _fail_count;
240    volatile int  _updated_tile_count;
241    volatile int  _success_count;
242    volatile int  _consecutive_errors;
243    volatile int  _allowed_errors;
244    volatile int  _cache_hits;
245    volatile int _transfer_rate;
246    // kbytes, not bytes, because bytes might overflow 2^31
247    volatile int _total_kb_downloaded;
248    
249 private:
250    virtual void run();
251     
252     // external model run and helpers
253     void runExternal();
254     void syncPathExternal(const SyncItem& next);
255     bool runExternalSyncCommand(const char* dir);
256
257     // internal mode run and helpers
258     void runInternal();
259     void updateSyncSlot(SyncSlot& slot);
260
261     // commond helpers between both internal and external models
262     
263     bool isPathCached(const SyncItem& next) const;
264     void initCompletedTilesPersistentCache();
265     void writeCompletedTilesPersistentCache() const;
266     void updated(SyncItem item, bool isNewDirectory);
267     void fail(SyncItem failedItem);
268     
269     bool _use_built_in;
270     HTTP::Client _http;
271     SyncSlot _syncSlots[NUM_SYNC_SLOTS];
272
273    volatile bool _is_dirty;
274    volatile bool _stop;
275    SGBlockingDeque <SyncItem> waitingTiles;
276    CompletedTiles _completedTiles;
277    SGBlockingDeque <SyncItem> _freshTiles;
278    bool _use_svn;
279    string _svn_server;
280    string _svn_data_server;
281    string _svn_command;
282    string _rsync_server;
283    string _local_dir;
284    SGPath _persistentCachePath;
285 };
286
287 SGTerraSync::SvnThread::SvnThread() :
288     _active(false),
289     _running(false),
290     _busy(false),
291     _stalled(false),
292     _fail_count(0),
293     _updated_tile_count(0),
294     _success_count(0),
295     _consecutive_errors(0),
296     _allowed_errors(6),
297     _cache_hits(0),
298     _transfer_rate(0),
299     _total_kb_downloaded(0),
300     _use_built_in(true),
301     _is_dirty(false),
302     _stop(false),
303     _use_svn(true)
304 {
305     _http.setUserAgent("terrascenery-" SG_STRINGIZE(SG_VERSION));
306 }
307
308 void SGTerraSync::SvnThread::stop()
309 {
310     // drop any pending requests
311     waitingTiles.clear();
312
313     if (!_running)
314         return;
315
316     // set stop flag and wake up the thread with an empty request
317     _stop = true;
318     SyncItem w(string(), SyncItem::Stop);
319     request(w);
320     join();
321     _running = false;
322 }
323
324 bool SGTerraSync::SvnThread::start()
325 {
326     if (_running)
327         return false;
328
329     if (_local_dir=="")
330     {
331         SG_LOG(SG_TERRAIN,SG_ALERT,
332                "Cannot start scenery download. Local cache directory is undefined.");
333         _fail_count++;
334         _stalled = true;
335         return false;
336     }
337
338     SGPath path(_local_dir);
339     if (!path.exists())
340     {
341         SG_LOG(SG_TERRAIN,SG_ALERT,
342                "Cannot start scenery download. Directory '" << _local_dir <<
343                "' does not exist. Set correct directory path or create directory folder.");
344         _fail_count++;
345         _stalled = true;
346         return false;
347     }
348
349     path.append("version");
350     if (path.exists())
351     {
352         SG_LOG(SG_TERRAIN,SG_ALERT,
353                "Cannot start scenery download. Directory '" << _local_dir <<
354                "' contains the base package. Use a separate directory.");
355         _fail_count++;
356         _stalled = true;
357         return false;
358     }
359
360     _use_svn |= _use_built_in;
361
362     if ((_use_svn)&&(_svn_server==""))
363     {
364         SG_LOG(SG_TERRAIN,SG_ALERT,
365                "Cannot start scenery download. Subversion scenery server is undefined.");
366         _fail_count++;
367         _stalled = true;
368         return false;
369     }
370     if ((!_use_svn)&&(_rsync_server==""))
371     {
372         SG_LOG(SG_TERRAIN,SG_ALERT,
373                "Cannot start scenery download. Rsync scenery server is undefined.");
374         _fail_count++;
375         _stalled = true;
376         return false;
377     }
378
379     _fail_count = 0;
380     _updated_tile_count = 0;
381     _success_count = 0;
382     _consecutive_errors = 0;
383     _stop = false;
384     _stalled = false;
385     _running = true;
386
387     string status;
388
389     if (_use_svn && _use_built_in)
390         status = "Using built-in SVN support. ";
391     else if (_use_svn)
392     {
393         status = "Using external SVN utility '";
394         status += _svn_command;
395         status += "'. ";
396     }
397     else
398     {
399         status = "Using RSYNC. ";
400     }
401
402     // not really an alert - but we want to (always) see this message, so user is
403     // aware we're downloading scenery (and using bandwidth).
404     SG_LOG(SG_TERRAIN,SG_ALERT,
405            "Starting automatic scenery download/synchronization. "
406            << status
407            << "Directory: '" << _local_dir << "'.");
408
409     SGThread::start();
410     return true;
411 }
412
413 bool SGTerraSync::SvnThread::runExternalSyncCommand(const char* dir)
414 {
415     ostringstream buf;
416     SGPath localPath( _local_dir );
417     localPath.append( dir );
418
419     if (_use_svn)
420     {
421         buf << "\"" << _svn_command << "\" "
422             << svn_options << " "
423             << "\"" << _svn_server << "/" << dir << "\" "
424             << "\"" << localPath.str_native() << "\"";
425     } else {
426         buf << rsync_cmd << " "
427             << "\"" << _rsync_server << "/" << dir << "/\" "
428             << "\"" << localPath.str_native() << "/\"";
429     }
430
431     string command;
432 #ifdef SG_WINDOWS
433         // windows command line parsing is just lovely...
434         // to allow white spaces, the system call needs this:
435         // ""C:\Program Files\something.exe" somearg "some other arg""
436         // Note: whitespace strings quoted by a pair of "" _and_ the 
437         //       entire string needs to be wrapped by "" too.
438         // The svn url needs forward slashes (/) as a path separator while
439         // the local path needs windows-native backslash as a path separator.
440     command = "\"" + buf.str() + "\"";
441 #else
442     command = buf.str();
443 #endif
444     SG_LOG(SG_TERRAIN,SG_DEBUG, "sync command '" << command << "'");
445
446 #ifdef SG_WINDOWS
447     // tbd: does Windows support "popen"?
448     int rc = system( command.c_str() );
449 #else
450     FILE* pipe = popen( command.c_str(), "r");
451     int rc=-1;
452     // wait for external process to finish
453     if (pipe)
454         rc = pclose(pipe);
455 #endif
456
457     if (rc)
458     {
459         SG_LOG(SG_TERRAIN,SG_ALERT,
460                "Failed to synchronize directory '" << dir << "', " <<
461                "error code= " << rc);
462         return false;
463     }
464     return true;
465 }
466
467 void SGTerraSync::SvnThread::run()
468 {
469     _active = true;
470     initCompletedTilesPersistentCache();
471
472     
473     if (_use_built_in) {
474         runInternal();
475     } else {
476         runExternal();
477     }
478     
479     _active = false;
480     _running = false;
481     _is_dirty = true;
482 }
483
484 void SGTerraSync::SvnThread::runExternal()
485 {
486     while (!_stop)
487     {
488         SyncItem next = waitingTiles.pop_front();
489         if (_stop)
490            break;
491
492         if (isPathCached(next)) {
493             _cache_hits++;
494             SG_LOG(SG_TERRAIN, SG_DEBUG,
495                    "Cache hit for: '" << next._dir << "'");
496             next._status = SyncItem::Cached;
497             _freshTiles.push_back(next);
498             _is_dirty = true;
499             continue;
500         }
501         
502         syncPathExternal(next);
503
504         if ((_allowed_errors >= 0)&&
505             (_consecutive_errors >= _allowed_errors))
506         {
507             _stalled = true;
508             _stop = true;
509         }
510     } // of thread running loop
511 }
512
513 void SGTerraSync::SvnThread::syncPathExternal(const SyncItem& next)
514 {
515     _busy = true;
516     SGPath path( _local_dir );
517     path.append( next._dir );
518     bool isNewDirectory = !path.exists();
519     
520     try {
521         if (isNewDirectory) {
522             int rc = path.create_dir( 0755 );
523             if (rc) {
524                 SG_LOG(SG_TERRAIN,SG_ALERT,
525                        "Cannot create directory '" << path << "', return code = " << rc );
526                 throw sg_exception("Cannot create directory for terrasync", path.str());
527             }
528         }
529         
530         if (!runExternalSyncCommand(next._dir.c_str())) {
531             throw sg_exception("Running external sync command failed");
532         }
533     } catch (sg_exception& e) {
534         fail(next);
535         _busy = false;
536         return;
537     }
538     
539     updated(next, isNewDirectory);
540     _busy = false;
541 }
542
543 void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
544 {
545     if (slot.repository.get()) {
546         if (slot.repository->isDoingSync()) {
547 #if 0
548             if (slot.stamp.elapsedMSec() > slot.nextWarnTimeout) {
549                 SG_LOG(SG_TERRAIN, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec());
550                 SG_LOG(SG_TERRAIN, SG_INFO, "HTTP status:" << _http.hasActiveRequests());
551                 slot.nextWarnTimeout += 10000;
552             }
553 #endif
554             return; // easy, still working
555         }
556         
557         // check result
558         SVNRepository::ResultCode res = slot.repository->failure();
559         if (res == SVNRepository::SVN_ERROR_NOT_FOUND) {
560             // this is fine, but maybe we should use a different return code
561             // in the future to higher layers can distinguish this case
562             slot.currentItem._status = SyncItem::NotFound;
563             _freshTiles.push_back(slot.currentItem);
564             _is_dirty = true;
565         } else if (res != SVNRepository::SVN_NO_ERROR) {
566             fail(slot.currentItem);
567         } else {
568             updated(slot.currentItem, slot.isNewDirectory);
569             SG_LOG(SG_TERRAIN, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " finished ("
570                    << slot.stamp.elapsedMSec() << " msec");
571         }
572
573         // whatever happened, we're done with this repository instance
574         slot.busy = false;
575         slot.repository.reset();
576     }
577     
578     // init and start sync of the next repository
579     if (!slot.queue.empty()) {
580         slot.currentItem = slot.queue.front();
581         slot.queue.pop();
582         
583         SGPath path(_local_dir);
584         path.append(slot.currentItem._dir);
585         slot.isNewDirectory = !path.exists();
586         if (slot.isNewDirectory) {
587             int rc = path.create_dir( 0755 );
588             if (rc) {
589                 SG_LOG(SG_TERRAIN,SG_ALERT,
590                        "Cannot create directory '" << path << "', return code = " << rc );
591                 fail(slot.currentItem);
592                 return;
593             }
594         } // of creating directory step
595         
596         string serverUrl(_svn_server);
597         if (slot.currentItem._type == SyncItem::AIData) {
598             serverUrl = _svn_data_server;
599         }
600         
601         slot.repository.reset(new SVNRepository(path, &_http));
602         slot.repository->setBaseUrl(serverUrl + "/" + slot.currentItem._dir);
603         slot.repository->update();
604         
605         slot.nextWarnTimeout = 20000;
606         slot.stamp.stamp();
607         slot.busy = true;
608         SG_LOG(SG_TERRAIN, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size());
609     }
610 }
611
612 void SGTerraSync::SvnThread::runInternal()
613 {
614     while (!_stop) {
615         _http.update(100);
616         _transfer_rate = _http.transferRateBytesPerSec();
617         // convert from bytes to kbytes
618         _total_kb_downloaded = static_cast<int>(_http.totalBytesDownloaded() / 1024);
619         
620         if (_stop)
621             break;
622  
623         // drain the waiting tiles queue into the sync slot queues.
624         while (!waitingTiles.empty()) {
625             SyncItem next = waitingTiles.pop_front();
626             if (isPathCached(next)) {
627                 _cache_hits++;
628                 SG_LOG(SG_TERRAIN, SG_DEBUG, "TerraSync Cache hit for: '" << next._dir << "'");
629                 next._status = SyncItem::Cached;
630                 _freshTiles.push_back(next);
631                 _is_dirty = true;
632                 continue;
633             }
634
635             unsigned int slot = syncSlotForType(next._type);
636             _syncSlots[slot].queue.push(next);
637         }
638        
639         bool anySlotBusy = false;
640         // update each sync slot in turn
641         for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) {
642             updateSyncSlot(_syncSlots[slot]);
643             anySlotBusy |= _syncSlots[slot].busy;
644         }
645
646         _busy = anySlotBusy;
647         if (!anySlotBusy) {
648             // wait on the blocking deque here, otherwise we spin
649             // the loop very fast, since _http::update with no connections
650             // active returns immediately.
651             waitingTiles.waitOnNotEmpty();
652         }
653     } // of thread running loop
654 }
655
656 bool SGTerraSync::SvnThread::isPathCached(const SyncItem& next) const
657 {
658     CompletedTiles::const_iterator ii = _completedTiles.find( next._dir );
659     if (ii == _completedTiles.end()) {
660         return false;
661     }
662     
663     // check if the path still physically exists
664     SGPath p(_local_dir);
665     p.append(next._dir);
666     if (!p.exists()) {
667         return false;
668     }
669     
670     time_t now = time(0);
671     return (ii->second > now);
672 }
673
674 void SGTerraSync::SvnThread::fail(SyncItem failedItem)
675 {
676     time_t now = time(0);
677     _consecutive_errors++;
678     _fail_count++;
679     failedItem._status = SyncItem::Failed;
680     _freshTiles.push_back(failedItem);
681     _completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt;
682     _is_dirty = true;
683 }
684
685 void SGTerraSync::SvnThread::updated(SyncItem item, bool isNewDirectory)
686 {
687     time_t now = time(0);
688     _consecutive_errors = 0;
689     _success_count++;
690     SG_LOG(SG_TERRAIN,SG_INFO,
691            "Successfully synchronized directory '" << item._dir << "'");
692     
693     item._status = SyncItem::Updated;
694     if (item._type == SyncItem::Tile) {
695         _updated_tile_count++;
696     }
697
698     _freshTiles.push_back(item);
699     _completedTiles[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
700     _is_dirty = true;
701     writeCompletedTilesPersistentCache();
702 }
703
704 void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
705 {
706     if (!_persistentCachePath.exists()) {
707         return;
708     }
709     
710     SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
711     time_t now = time(0);
712     
713     try {
714         readProperties(_persistentCachePath.str(), cacheRoot);
715     } catch (sg_exception& e) {
716         SG_LOG(SG_TERRAIN, SG_INFO, "corrupted persistent cache, discarding");
717         return;
718     }
719     
720     for (int i=0; i<cacheRoot->nChildren(); ++i) {
721         SGPropertyNode* entry = cacheRoot->getChild(i);
722         string tileName = entry->getStringValue("path");
723         time_t stamp = entry->getIntValue("stamp");
724         if (stamp < now) {
725             continue;
726         }
727         
728         _completedTiles[tileName] = stamp;
729     }
730 }
731
732 void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
733 {
734     // cache is disabled
735     if (_persistentCachePath.isNull()) {
736         return;
737     }
738     
739     std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
740     if (!f.is_open()) {
741         return;
742     }
743     
744     SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
745     CompletedTiles::const_iterator it = _completedTiles.begin();
746     for (; it != _completedTiles.end(); ++it) {
747         SGPropertyNode* entry = cacheRoot->addChild("entry");
748         entry->setStringValue("path", it->first);
749         entry->setIntValue("stamp", it->second);
750     }
751     
752     writeProperties(f, cacheRoot, true /* write_all */);
753     f.close();
754 }
755
756 ///////////////////////////////////////////////////////////////////////////////
757 // SGTerraSync ////////////////////////////////////////////////////////////////
758 ///////////////////////////////////////////////////////////////////////////////
759 SGTerraSync::SGTerraSync() :
760     _svnThread(NULL),
761     last_lat(NOWHERE),
762     last_lon(NOWHERE),
763     _bound(false),
764     _inited(false)
765 {
766     _svnThread = new SvnThread();
767     _log = new BufferedLogCallback(SG_TERRAIN, SG_INFO);
768     _log->truncateAt(255);
769     
770     sglog().addCallback(_log);
771 }
772
773 SGTerraSync::~SGTerraSync()
774 {
775     delete _svnThread;
776     _svnThread = NULL;
777     sglog().removeCallback(_log);
778     delete _log;
779      _tiedProperties.Untie();
780 }
781
782 void SGTerraSync::setRoot(SGPropertyNode_ptr root)
783 {
784     _terraRoot = root->getNode("/sim/terrasync",true);
785 }
786
787 void SGTerraSync::init()
788 {
789     if (_inited) {
790         return;
791     }
792     
793     _inited = true;
794     
795     assert(_terraRoot);
796     _terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available);
797         
798     reinit();
799 }
800
801 void SGTerraSync::shutdown()
802 {
803      _svnThread->stop();
804 }
805
806 void SGTerraSync::reinit()
807 {
808     // do not reinit when enabled and we're already up and running
809     if ((_terraRoot->getBoolValue("enabled",false))&&
810          (_svnThread->_active && _svnThread->_running))
811     {
812         return;
813     }
814     
815     _svnThread->stop();
816
817     if (_terraRoot->getBoolValue("enabled",false))
818     {
819         _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
820         _svnThread->setSvnDataServer(_terraRoot->getStringValue("svn-data-server",""));
821         _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
822         _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
823         _svnThread->setAllowedErrorCount(_terraRoot->getIntValue("max-errors",5));
824         _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
825         _svnThread->setCachePath(SGPath(_terraRoot->getStringValue("cache-path","")));
826         _svnThread->setCacheHits(_terraRoot->getIntValue("cache-hit", 0));
827         _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
828         _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
829
830         if (_svnThread->start())
831         {
832             syncAirportsModels();
833             if (last_lat != NOWHERE && last_lon != NOWHERE)
834             {
835                 // reschedule most recent position
836                 int lat = last_lat;
837                 int lon = last_lon;
838                 last_lat = NOWHERE;
839                 last_lon = NOWHERE;
840                 schedulePosition(lat, lon);
841             }
842         }
843     }
844
845     _stalledNode->setBoolValue(_svnThread->_stalled);
846 }
847
848 void SGTerraSync::bind()
849 {
850     if (_bound) {
851         return;
852     }
853     
854     _bound = true;
855     _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
856     _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
857     _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
858     _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
859     _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
860     _tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits );
861     _tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate );
862     
863     // use kbytes here because propety doesn't support 64-bit and we might conceivably
864     // download more than 2G in a single session
865     _tiedProperties.Tie( _terraRoot->getNode("downloaded-kbytes", true), (int*) &_svnThread->_total_kb_downloaded );
866     
867     _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
868     _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
869     _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
870     _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
871     _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
872     _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
873     _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
874     // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
875     _stalledNode = _terraRoot->getNode("stalled", true);
876     _stalledNode->setBoolValue(_svnThread->_stalled);
877     _stalledNode->setAttribute(SGPropertyNode::PRESERVE,true);
878 }
879
880 void SGTerraSync::unbind()
881 {
882     _svnThread->stop();
883     _tiedProperties.Untie();
884     _bound = false;
885     _inited = false;
886 }
887
888 void SGTerraSync::update(double)
889 {
890     static SGBucket bucket;
891     if (_svnThread->isDirty())
892     {
893         if (!_svnThread->_active)
894         {
895             if (_svnThread->_stalled)
896             {
897                 SG_LOG(SG_TERRAIN,SG_ALERT,
898                        "Automatic scenery download/synchronization stalled. Too many errors.");
899             }
900             else
901             {
902                 // not really an alert - just always show this message
903                 SG_LOG(SG_TERRAIN,SG_ALERT,
904                         "Automatic scenery download/synchronization has stopped.");
905             }
906             _stalledNode->setBoolValue(_svnThread->_stalled);
907         }
908
909         while (_svnThread->hasNewTiles())
910         {
911             SyncItem next = _svnThread->getNewTile();
912             
913             if ((next._type == SyncItem::Tile) || (next._type == SyncItem::AIData)) {
914                 _activeTileDirs.erase(next._dir);
915             }
916         } // of freshly synced items
917     }
918 }
919
920 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
921
922 void SGTerraSync::syncAirportsModels()
923 {
924     static const char* bounds = "MZAJKL"; // airport sync order: K-L, A-J, M-Z
925     // note "request" method uses LIFO order, i.e. processes most recent request first
926     for( unsigned i = 0; i < strlen(bounds)/2; i++ )
927     {
928         for ( char synced_other = bounds[2*i]; synced_other <= bounds[2*i+1]; synced_other++ )
929         {
930             ostringstream dir;
931             dir << "Airports/" << synced_other;
932             SyncItem w(dir.str(), SyncItem::AirportData);
933             _svnThread->request( w );
934         }
935     }
936     
937     SyncItem w("Models", SyncItem::SharedModels);
938     _svnThread->request( w );
939 }
940
941
942 void SGTerraSync::syncArea( int lat, int lon )
943 {
944     if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
945         return;
946     char NS, EW;
947     int baselat, baselon;
948
949     if ( lat < 0 ) {
950         int base = (int)(lat / 10);
951         if ( lat == base * 10 ) {
952             baselat = base * 10;
953         } else {
954             baselat = (base - 1) * 10;
955         }
956         NS = 's';
957     } else {
958         baselat = (int)(lat / 10) * 10;
959         NS = 'n';
960     }
961     if ( lon < 0 ) {
962         int base = (int)(lon / 10);
963         if ( lon == base * 10 ) {
964             baselon = base * 10;
965         } else {
966             baselon = (base - 1) * 10;
967         }
968         EW = 'w';
969     } else {
970         baselon = (int)(lon / 10) * 10;
971         EW = 'e';
972     }
973
974     ostringstream dir;
975     dir << setfill('0')
976     << EW << setw(3) << abs(baselon) << NS << setw(2) << abs(baselat) << "/"
977     << EW << setw(3) << abs(lon)     << NS << setw(2) << abs(lat);
978     
979     syncAreaByPath(dir.str());
980 }
981
982 void SGTerraSync::syncAreaByPath(const std::string& aPath)
983 {
984     const char* terrainobjects[3] = { "Terrain/", "Objects/",  0 };
985     for (const char** tree = &terrainobjects[0]; *tree; tree++)
986     {
987         std::string dir = string(*tree) + aPath;
988         if (_activeTileDirs.find(dir) != _activeTileDirs.end()) {
989             continue;
990         }
991                 
992         _activeTileDirs.insert(dir);
993         SyncItem w(dir, SyncItem::Tile);
994         _svnThread->request( w );
995     }
996 }
997
998
999 void SGTerraSync::syncAreas( int lat, int lon, int lat_dir, int lon_dir )
1000 {
1001     if ( lat_dir == 0 && lon_dir == 0 ) {
1002         
1003         // do surrounding 8 1x1 degree areas.
1004         for ( int i = lat - 1; i <= lat + 1; ++i ) {
1005             for ( int j = lon - 1; j <= lon + 1; ++j ) {
1006                 if ( i != lat || j != lon ) {
1007                     syncArea( i, j );
1008                 }
1009             }
1010         }
1011     } else {
1012         if ( lat_dir != 0 ) {
1013             syncArea( lat + lat_dir, lon - 1 );
1014             syncArea( lat + lat_dir, lon + 1 );
1015             syncArea( lat + lat_dir, lon );
1016         }
1017         if ( lon_dir != 0 ) {
1018             syncArea( lat - 1, lon + lon_dir );
1019             syncArea( lat + 1, lon + lon_dir );
1020             syncArea( lat, lon + lon_dir );
1021         }
1022     }
1023
1024     // do current 1x1 degree area first
1025     syncArea( lat, lon );
1026 }
1027
1028 bool SGTerraSync::scheduleTile(const SGBucket& bucket)
1029 {
1030     std::string basePath = bucket.gen_base_path();
1031     syncAreaByPath(basePath);
1032     return true;
1033 }
1034
1035 bool SGTerraSync::schedulePosition(int lat, int lon)
1036 {
1037     bool Ok = false;
1038
1039     // Ignore messages where the location does not change
1040     if ( lat != last_lat || lon != last_lon )
1041     {
1042         if (_svnThread->_running)
1043         {
1044             int lat_dir=0;
1045             int lon_dir=0;
1046             if ( last_lat != NOWHERE && last_lon != NOWHERE )
1047             {
1048                 int dist = lat - last_lat;
1049                 if ( dist != 0 )
1050                 {
1051                     lat_dir = dist / abs(dist);
1052                 }
1053                 else
1054                 {
1055                     lat_dir = 0;
1056                 }
1057                 dist = lon - last_lon;
1058                 if ( dist != 0 )
1059                 {
1060                     lon_dir = dist / abs(dist);
1061                 } else
1062                 {
1063                     lon_dir = 0;
1064                 }
1065             }
1066
1067             SG_LOG(SG_TERRAIN,SG_DEBUG, "Scenery update for " <<
1068                    "lat = " << lat << ", lon = " << lon <<
1069                    ", lat_dir = " << lat_dir << ",  " <<
1070                    "lon_dir = " << lon_dir);
1071
1072             syncAreas( lat, lon, lat_dir, lon_dir );
1073             Ok = true;
1074         }
1075         last_lat = lat;
1076         last_lon = lon;
1077     }
1078
1079     return Ok;
1080 }
1081
1082 void SGTerraSync::reposition()
1083 {
1084     last_lat = last_lon = NOWHERE;
1085 }
1086
1087 bool SGTerraSync::isTileDirPending(const std::string& sceneryDir) const
1088 {
1089     if (!_svnThread->_running) {
1090         return false;
1091     }
1092     
1093     const char* terrainobjects[3] = { "Terrain/", "Objects/",  0 };
1094     for (const char** tree = &terrainobjects[0]; *tree; tree++) {
1095         string s = *tree + sceneryDir;
1096         if (_activeTileDirs.find(s) != _activeTileDirs.end()) {
1097             return true;
1098         }
1099     }
1100
1101     return false;
1102 }
1103
1104 void SGTerraSync::scheduleDataDir(const std::string& dataDir)
1105 {
1106     if (_activeTileDirs.find(dataDir) != _activeTileDirs.end()) {
1107         return;
1108     }
1109     
1110     _activeTileDirs.insert(dataDir);
1111     SyncItem w(dataDir, SyncItem::AIData);
1112     _svnThread->request( w );
1113
1114 }
1115
1116 bool SGTerraSync::isDataDirPending(const std::string& dataDir) const
1117 {
1118     if (!_svnThread->_running) {
1119         return false;
1120     }
1121     
1122     return (_activeTileDirs.find(dataDir) != _activeTileDirs.end());
1123 }