]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tsync/terrasync.cxx
Remove unneeded local scope
[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 #include <simgear_config.h>
26 #include <simgear/compiler.h>
27
28 #ifdef HAVE_WINDOWS_H
29 #include <windows.h>
30 #endif
31
32 #ifdef __MINGW32__
33 #  include <time.h>
34 #  include <unistd.h>
35 #elif defined(_MSC_VER)
36 #   include <io.h>
37 #   include <time.h>
38 #   include <process.h>
39 #endif
40
41 #include <stdlib.h>             // atoi() atof() abs() system()
42 #include <signal.h>             // signal()
43 #include <string.h>
44
45 #include <iostream>
46 #include <fstream>
47 #include <string>
48 #include <map>
49
50 #include <simgear/version.h>
51
52 #include "terrasync.hxx"
53
54 #include <simgear/bucket/newbucket.hxx>
55 #include <simgear/misc/sg_path.hxx>
56 #include <simgear/misc/strutils.hxx>
57 #include <simgear/threads/SGQueue.hxx>
58 #include <simgear/misc/sg_dir.hxx>
59 #include <simgear/debug/BufferedLogCallback.hxx>
60 #include <simgear/props/props_io.hxx>
61 #include <simgear/io/HTTPClient.hxx>
62 #include <simgear/io/SVNRepository.hxx>
63 #include <simgear/io/HTTPRepository.hxx>
64 #include <simgear/io/DNSClient.hxx>
65 #include <simgear/structure/exception.hxx>
66 #include <simgear/math/sg_random.h>
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> TileAgeCache;
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<AbstractRepository> 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 // Base server query
204 ///////////////////////////////////////////////////////////////////////////////
205
206 class ServerSelectQuery : public HTTP::Request
207 {
208 public:
209     ServerSelectQuery() :
210         HTTP::Request("http://scenery.flightgear.org/svn-server", "GET")
211     {
212     }
213
214     std::string svnUrl() const
215     {
216         std::string s = simgear::strutils::strip(m_url);
217         if (s.at(s.length() - 1) == '/') {
218             s = s.substr(0, s.length() - 1);
219         }
220
221         return s;
222     }
223 protected:
224     virtual void gotBodyData(const char* s, int n)
225     {
226         m_url.append(std::string(s, n));
227     }
228
229     virtual void onFail()
230     {
231         SG_LOG(SG_TERRASYNC, SG_ALERT, "Failed to query TerraSync SVN server");
232         HTTP::Request::onFail();
233     }
234
235 private:
236     std::string m_url;
237 };
238
239
240 ///////////////////////////////////////////////////////////////////////////////
241 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
242 ///////////////////////////////////////////////////////////////////////////////
243 class SGTerraSync::SvnThread : public SGThread
244 {
245 public:
246    SvnThread();
247    virtual ~SvnThread( ) { stop(); }
248
249    void stop();
250    bool start();
251
252     bool isIdle() {return !_busy; }
253    void request(const SyncItem& dir) {waitingTiles.push_front(dir);}
254    bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
255    bool hasNewTiles() { return !_freshTiles.empty();}
256    SyncItem getNewTile() { return _freshTiles.pop_front();}
257
258    void   setSvnServer(string server)       { _svn_server   = stripPath(server);}
259    void   setSvnDataServer(string server)   { _svn_data_server   = stripPath(server);}
260    void   setHTTPServer(const std::string& server)
261    {
262       _httpServer = stripPath(server);
263    }
264
265    void   setExtSvnUtility(string svn_util) { _svn_command  = simgear::strutils::strip(svn_util);}
266    void   setRsyncServer(string server)     { _rsync_server = simgear::strutils::strip(server);}
267    void   setLocalDir(string dir)           { _local_dir    = stripPath(dir);}
268    string getLocalDir()                     { return _local_dir;}
269    void   setUseSvn(bool use_svn)           { _use_svn = use_svn;}
270    void   setAllowedErrorCount(int errors)  {_allowed_errors = errors;}
271
272    void   setCachePath(const SGPath& p)     {_persistentCachePath = p;}
273    void   setCacheHits(unsigned int hits)   {_cache_hits = hits;}
274    void   setUseBuiltin(bool built_in) { _use_built_in = built_in;}
275
276    volatile bool _active;
277    volatile bool _running;
278    volatile bool _busy;
279    volatile bool _stalled;
280    volatile int  _fail_count;
281    volatile int  _updated_tile_count;
282    volatile int  _success_count;
283    volatile int  _consecutive_errors;
284    volatile int  _allowed_errors;
285    volatile int  _cache_hits;
286    volatile int _transfer_rate;
287    // kbytes, not bytes, because bytes might overflow 2^31
288    volatile int _total_kb_downloaded;
289
290 private:
291    virtual void run();
292
293     // external model run and helpers
294     void runExternal();
295     void syncPathExternal(const SyncItem& next);
296     bool runExternalSyncCommand(const char* dir);
297
298     // internal mode run and helpers
299     void runInternal();
300     void updateSyncSlot(SyncSlot& slot);
301
302     // commond helpers between both internal and external models
303
304     SyncItem::Status isPathCached(const SyncItem& next) const;
305     void initCompletedTilesPersistentCache();
306     void writeCompletedTilesPersistentCache() const;
307     void updated(SyncItem item, bool isNewDirectory);
308     void fail(SyncItem failedItem);
309     void notFound(SyncItem notFoundItem);
310
311     bool _use_built_in;
312     HTTP::Client _http;
313     SyncSlot _syncSlots[NUM_SYNC_SLOTS];
314
315    volatile bool _is_dirty;
316    volatile bool _stop;
317    SGBlockingDeque <SyncItem> waitingTiles;
318
319    TileAgeCache _completedTiles;
320    TileAgeCache _notFoundItems;
321
322    SGBlockingDeque <SyncItem> _freshTiles;
323    bool _use_svn;
324    string _svn_server;
325    string _svn_data_server;
326    string _svn_command;
327    string _rsync_server;
328    string _local_dir;
329    SGPath _persistentCachePath;
330    string _httpServer;
331 };
332
333 SGTerraSync::SvnThread::SvnThread() :
334     _active(false),
335     _running(false),
336     _busy(false),
337     _stalled(false),
338     _fail_count(0),
339     _updated_tile_count(0),
340     _success_count(0),
341     _consecutive_errors(0),
342     _allowed_errors(6),
343     _cache_hits(0),
344     _transfer_rate(0),
345     _total_kb_downloaded(0),
346     _use_built_in(true),
347     _is_dirty(false),
348     _stop(false),
349     _use_svn(true)
350 {
351     _http.setUserAgent("terrascenery-" SG_STRINGIZE(SIMGEAR_VERSION));
352 }
353
354 void SGTerraSync::SvnThread::stop()
355 {
356     // drop any pending requests
357     waitingTiles.clear();
358
359     if (!_running)
360         return;
361
362     // set stop flag and wake up the thread with an empty request
363     _stop = true;
364     SyncItem w(string(), SyncItem::Stop);
365     request(w);
366     join();
367     _running = false;
368 }
369
370 bool SGTerraSync::SvnThread::start()
371 {
372     if (_running)
373         return false;
374
375     if (_local_dir=="")
376     {
377         SG_LOG(SG_TERRASYNC,SG_ALERT,
378                "Cannot start scenery download. Local cache directory is undefined.");
379         _fail_count++;
380         _stalled = true;
381         return false;
382     }
383
384     SGPath path(_local_dir);
385     if (!path.exists())
386     {
387         SG_LOG(SG_TERRASYNC,SG_ALERT,
388                "Cannot start scenery download. Directory '" << _local_dir <<
389                "' does not exist. Set correct directory path or create directory folder.");
390         _fail_count++;
391         _stalled = true;
392         return false;
393     }
394
395     path.append("version");
396     if (path.exists())
397     {
398         SG_LOG(SG_TERRASYNC,SG_ALERT,
399                "Cannot start scenery download. Directory '" << _local_dir <<
400                "' contains the base package. Use a separate directory.");
401         _fail_count++;
402         _stalled = true;
403         return false;
404     }
405
406     _use_svn |= _use_built_in;
407
408
409     if ((!_use_svn)&&(_rsync_server==""))
410     {
411         SG_LOG(SG_TERRASYNC,SG_ALERT,
412                "Cannot start scenery download. Rsync scenery server is undefined.");
413         _fail_count++;
414         _stalled = true;
415         return false;
416     }
417
418     _fail_count = 0;
419     _updated_tile_count = 0;
420     _success_count = 0;
421     _consecutive_errors = 0;
422     _stop = false;
423     _stalled = false;
424     _running = true;
425
426     string status;
427
428     if (_use_svn && _use_built_in)
429         status = "Using built-in SVN support. ";
430     else if (_use_svn)
431     {
432         status = "Using external SVN utility '";
433         status += _svn_command;
434         status += "'. ";
435     }
436     else
437     {
438         status = "Using RSYNC. ";
439     }
440
441     // not really an alert - but we want to (always) see this message, so user is
442     // aware we're downloading scenery (and using bandwidth).
443     SG_LOG(SG_TERRASYNC,SG_ALERT,
444            "Starting automatic scenery download/synchronization. "
445            << status
446            << "Directory: '" << _local_dir << "'.");
447
448     SGThread::start();
449     return true;
450 }
451
452 bool SGTerraSync::SvnThread::runExternalSyncCommand(const char* dir)
453 {
454     ostringstream buf;
455     SGPath localPath( _local_dir );
456     localPath.append( dir );
457
458     if (_use_svn)
459     {
460         buf << "\"" << _svn_command << "\" "
461             << svn_options << " "
462             << "\"" << _svn_server << "/" << dir << "\" "
463             << "\"" << localPath.str_native() << "\"";
464     } else {
465         buf << rsync_cmd << " "
466             << "\"" << _rsync_server << "/" << dir << "/\" "
467             << "\"" << localPath.str_native() << "/\"";
468     }
469
470     string command;
471 #ifdef SG_WINDOWS
472         // windows command line parsing is just lovely...
473         // to allow white spaces, the system call needs this:
474         // ""C:\Program Files\something.exe" somearg "some other arg""
475         // Note: whitespace strings quoted by a pair of "" _and_ the
476         //       entire string needs to be wrapped by "" too.
477         // The svn url needs forward slashes (/) as a path separator while
478         // the local path needs windows-native backslash as a path separator.
479     command = "\"" + buf.str() + "\"";
480 #else
481     command = buf.str();
482 #endif
483     SG_LOG(SG_TERRASYNC,SG_DEBUG, "sync command '" << command << "'");
484
485 #ifdef SG_WINDOWS
486     // tbd: does Windows support "popen"?
487     int rc = system( command.c_str() );
488 #else
489     FILE* pipe = popen( command.c_str(), "r");
490     int rc=-1;
491     // wait for external process to finish
492     if (pipe)
493         rc = pclose(pipe);
494 #endif
495
496     if (rc)
497     {
498         SG_LOG(SG_TERRASYNC,SG_ALERT,
499                "Failed to synchronize directory '" << dir << "', " <<
500                "error code= " << rc);
501         return false;
502     }
503     return true;
504 }
505
506 void SGTerraSync::SvnThread::run()
507 {
508     _active = true;
509     initCompletedTilesPersistentCache();
510
511     if (_httpServer == "automatic" ) {
512
513         //TODO: make DN and service settable from properties
514         DNS::NAPTRRequest * naptrRequest = new DNS::NAPTRRequest("terrasync.flightgear.org");
515         naptrRequest->qservice = "ws20";
516
517         naptrRequest->qflags = "U";
518         DNS::Request_ptr r(naptrRequest);
519
520         DNS::Client dnsClient;
521         dnsClient.makeRequest(r);
522         while( !r->isComplete() && !r->isTimeout() )
523           dnsClient.update(0);
524
525         if( naptrRequest->entries.empty() ) {
526             SG_LOG(SG_TERRASYNC, SG_ALERT, "ERROR: automatic terrasync http-server requested, but no DNS entry found.");
527             _httpServer = "";
528         } else {
529             // walk through responses, they are ordered by 1. order and 2. preference
530             // For now, only take entries with lowest order
531             // TODO: try all available servers in the order given by preferenc and order
532             int order = naptrRequest->entries[0]->order;
533
534             // get all servers with this order and the same (for now only lowest preference)
535             DNS::NAPTRRequest::NAPTR_list availableServers;
536                 for( DNS::NAPTRRequest::NAPTR_list::const_iterator it = naptrRequest->entries.begin();
537                   it != naptrRequest->entries.end();
538                   ++it ) {
539
540                 if( (*it)->order != order )
541                     continue;
542
543                 string regex = (*it)->regexp;
544                 if( false == simgear::strutils::starts_with( (*it)->regexp, "!^.*$!" ) ) {
545                     SG_LOG(SG_TERRASYNC,SG_WARN, "ignoring unsupported regexp: " << (*it)->regexp );
546                     continue;
547                 }
548
549                 if( false == simgear::strutils::ends_with( (*it)->regexp, "!" ) ) {
550                     SG_LOG(SG_TERRASYNC,SG_WARN, "ignoring unsupported regexp: " << (*it)->regexp );
551                     continue;
552                 }
553
554                 // always use first entry
555                 if( availableServers.empty() || (*it)->preference == availableServers[0]->preference) {
556                     SG_LOG(SG_TERRASYNC,SG_DEBUG, "available server regexp: " << (*it)->regexp );
557                     availableServers.push_back( *it );
558                 }
559           }
560
561           // now pick a random entry from the available servers
562           DNS::NAPTRRequest::NAPTR_list::size_type idx = sg_random() * availableServers.size();
563           _httpServer = availableServers[idx]->regexp;
564           _httpServer = _httpServer.substr( 6, _httpServer.length()-7 ); // strip search pattern and separators
565
566           SG_LOG(SG_TERRASYNC,SG_INFO, "picking entry # " << idx << ", server is " << _httpServer );
567         }
568     }
569     if( _httpServer.empty() ) { // don't resolve SVN server is HTTP server is set
570         if ( _svn_server.empty()) {
571             SG_LOG(SG_TERRASYNC,SG_INFO, "Querying closest TerraSync server");
572             ServerSelectQuery* ssq = new ServerSelectQuery;
573             HTTP::Request_ptr req = ssq;
574             _http.makeRequest(req);
575             while (!req->isComplete()) {
576                 _http.update(20);
577             }
578
579             if (req->readyState() == HTTP::Request::DONE) {
580                 _svn_server = ssq->svnUrl();
581                 SG_LOG(SG_TERRASYNC,SG_INFO, "Closest TerraSync server:" << _svn_server);
582             } else {
583                 SG_LOG(SG_TERRASYNC,SG_WARN, "Failed to query closest TerraSync server");
584             }
585         } else {
586             SG_LOG(SG_TERRASYNC,SG_INFO, "Explicit: TerraSync server:" << _svn_server);
587         }
588
589         if (_svn_server.empty()) {
590 #if WE_HAVE_A_DEFAULT_SERVER_BUT_WE_DONT_THIS_URL_IS_NO_LONGER_VALID
591             // default value
592             _svn_server = "http://foxtrot.mgras.net:8080/terrascenery/trunk/data/Scenery";
593 #endif
594         }
595     }
596
597     if (_use_built_in) {
598         runInternal();
599     } else {
600         runExternal();
601     }
602
603     _active = false;
604     _running = false;
605     _is_dirty = true;
606 }
607
608 void SGTerraSync::SvnThread::runExternal()
609 {
610     while (!_stop)
611     {
612         SyncItem next = waitingTiles.pop_front();
613         if (_stop)
614            break;
615
616         SyncItem::Status cacheStatus = isPathCached(next);
617         if (cacheStatus != SyncItem::Invalid) {
618             _cache_hits++;
619             SG_LOG(SG_TERRASYNC, SG_DEBUG,
620                    "Cache hit for: '" << next._dir << "'");
621             next._status = cacheStatus;
622             _freshTiles.push_back(next);
623             _is_dirty = true;
624             continue;
625         }
626
627         syncPathExternal(next);
628
629         if ((_allowed_errors >= 0)&&
630             (_consecutive_errors >= _allowed_errors))
631         {
632             _stalled = true;
633             _stop = true;
634         }
635     } // of thread running loop
636 }
637
638 void SGTerraSync::SvnThread::syncPathExternal(const SyncItem& next)
639 {
640     _busy = true;
641     SGPath path( _local_dir );
642     path.append( next._dir );
643     bool isNewDirectory = !path.exists();
644
645     try {
646         if (isNewDirectory) {
647             int rc = path.create_dir( 0755 );
648             if (rc) {
649                 SG_LOG(SG_TERRASYNC,SG_ALERT,
650                        "Cannot create directory '" << path << "', return code = " << rc );
651                 throw sg_exception("Cannot create directory for terrasync", path.str());
652             }
653         }
654
655         if (!runExternalSyncCommand(next._dir.c_str())) {
656             throw sg_exception("Running external sync command failed");
657         }
658     } catch (sg_exception& e) {
659         fail(next);
660         _busy = false;
661         return;
662     }
663
664     updated(next, isNewDirectory);
665     _busy = false;
666 }
667
668 void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
669 {
670     if (slot.repository.get()) {
671         if (slot.repository->isDoingSync()) {
672 #if 1
673             if (slot.stamp.elapsedMSec() > (int)slot.nextWarnTimeout) {
674                 SG_LOG(SG_TERRASYNC, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec());
675                 SG_LOG(SG_TERRASYNC, SG_INFO, "HTTP request count:" << _http.hasActiveRequests());
676                 slot.nextWarnTimeout += 10000;
677             }
678 #endif
679             return; // easy, still working
680         }
681
682         // check result
683         SVNRepository::ResultCode res = slot.repository->failure();
684         if (res == AbstractRepository::REPO_ERROR_NOT_FOUND) {
685             notFound(slot.currentItem);
686         } else if (res != AbstractRepository::REPO_NO_ERROR) {
687             fail(slot.currentItem);
688         } else {
689             updated(slot.currentItem, slot.isNewDirectory);
690             SG_LOG(SG_TERRASYNC, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " finished ("
691                    << slot.stamp.elapsedMSec() << " msec");
692         }
693
694         // whatever happened, we're done with this repository instance
695         slot.busy = false;
696         slot.repository.reset();
697     }
698
699     // init and start sync of the next repository
700     if (!slot.queue.empty()) {
701         slot.currentItem = slot.queue.front();
702         slot.queue.pop();
703
704         SGPath path(_local_dir);
705         path.append(slot.currentItem._dir);
706         slot.isNewDirectory = !path.exists();
707         if (slot.isNewDirectory) {
708             int rc = path.create_dir( 0755 );
709             if (rc) {
710                 SG_LOG(SG_TERRASYNC,SG_ALERT,
711                        "Cannot create directory '" << path << "', return code = " << rc );
712                 fail(slot.currentItem);
713                 return;
714             }
715         } // of creating directory step
716
717         string serverUrl(_svn_server);
718         if (!_httpServer.empty()) {
719           slot.repository.reset(new HTTPRepository(path, &_http));
720           serverUrl = _httpServer;
721         } else {
722           if (slot.currentItem._type == SyncItem::AIData) {
723               serverUrl = _svn_data_server;
724           }
725           slot.repository.reset(new SVNRepository(path, &_http));
726         }
727
728         slot.repository->setBaseUrl(serverUrl + "/" + slot.currentItem._dir);
729         try {
730             slot.repository->update();
731         } catch (sg_exception& e) {
732             SG_LOG(SG_TERRASYNC, SG_INFO, "sync of " << slot.repository->baseUrl() << " failed to start with error:"
733                    << e.getFormattedMessage());
734             fail(slot.currentItem);
735             slot.busy = false;
736             slot.repository.reset();
737             return;
738         }
739
740         slot.nextWarnTimeout = 20000;
741         slot.stamp.stamp();
742         slot.busy = true;
743         SG_LOG(SG_TERRASYNC, SG_INFO, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size());
744     }
745 }
746
747 void SGTerraSync::SvnThread::runInternal()
748 {
749     while (!_stop) {
750         try {
751             _http.update(100);
752         } catch (sg_exception& e) {
753             SG_LOG(SG_TERRASYNC, SG_WARN, "failure doing HTTP update" << e.getFormattedMessage());
754         }
755
756         _transfer_rate = _http.transferRateBytesPerSec();
757         // convert from bytes to kbytes
758         _total_kb_downloaded = static_cast<int>(_http.totalBytesDownloaded() / 1024);
759
760         if (_stop)
761             break;
762
763         // drain the waiting tiles queue into the sync slot queues.
764         while (!waitingTiles.empty()) {
765             SyncItem next = waitingTiles.pop_front();
766             SyncItem::Status cacheStatus = isPathCached(next);
767             if (cacheStatus != SyncItem::Invalid) {
768                 _cache_hits++;
769                 SG_LOG(SG_TERRASYNC, SG_DEBUG, "\nTerraSync Cache hit for: '" << next._dir << "'");
770                 next._status = cacheStatus;
771                 _freshTiles.push_back(next);
772                 _is_dirty = true;
773                 continue;
774             }
775
776             unsigned int slot = syncSlotForType(next._type);
777             _syncSlots[slot].queue.push(next);
778         }
779
780         bool anySlotBusy = false;
781         // update each sync slot in turn
782         for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) {
783             updateSyncSlot(_syncSlots[slot]);
784             anySlotBusy |= _syncSlots[slot].busy;
785         }
786
787         _busy = anySlotBusy;
788         if (!anySlotBusy) {
789             // wait on the blocking deque here, otherwise we spin
790             // the loop very fast, since _http::update with no connections
791             // active returns immediately.
792             waitingTiles.waitOnNotEmpty();
793         }
794     } // of thread running loop
795 }
796
797 SyncItem::Status SGTerraSync::SvnThread::isPathCached(const SyncItem& next) const
798 {
799     TileAgeCache::const_iterator ii = _completedTiles.find( next._dir );
800     if (ii == _completedTiles.end()) {
801         ii = _notFoundItems.find( next._dir );
802         // Invalid means 'not cached', otherwise we want to return to
803         // higher levels the cache status
804         return (ii == _notFoundItems.end()) ? SyncItem::Invalid : SyncItem::NotFound;
805     }
806
807     // check if the path still physically exists. This is needed to
808     // cope with the user manipulating our cache dir
809     SGPath p(_local_dir);
810     p.append(next._dir);
811     if (!p.exists()) {
812         return SyncItem::Invalid;
813     }
814
815     time_t now = time(0);
816     return (ii->second > now) ? SyncItem::Cached : SyncItem::Invalid;
817 }
818
819 void SGTerraSync::SvnThread::fail(SyncItem failedItem)
820 {
821     time_t now = time(0);
822     _consecutive_errors++;
823     _fail_count++;
824     failedItem._status = SyncItem::Failed;
825     _freshTiles.push_back(failedItem);
826     SG_LOG(SG_TERRASYNC,SG_INFO,
827            "Failed to sync'" << failedItem._dir << "'");
828     _completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt;
829     _is_dirty = true;
830 }
831
832 void SGTerraSync::SvnThread::notFound(SyncItem item)
833 {
834     // treat not found as authorative, so use the same cache expiry
835     // as succesful download. Important for MP models and similar so
836     // we don't spam the server with lookups for models that don't
837     // exist
838
839     time_t now = time(0);
840     item._status = SyncItem::NotFound;
841     _freshTiles.push_back(item);
842     _is_dirty = true;
843     _notFoundItems[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
844     writeCompletedTilesPersistentCache();
845 }
846
847 void SGTerraSync::SvnThread::updated(SyncItem item, bool isNewDirectory)
848 {
849     time_t now = time(0);
850     _consecutive_errors = 0;
851     _success_count++;
852     SG_LOG(SG_TERRASYNC,SG_INFO,
853            "Successfully synchronized directory '" << item._dir << "'");
854
855     item._status = SyncItem::Updated;
856     if (item._type == SyncItem::Tile) {
857         _updated_tile_count++;
858     }
859
860     _freshTiles.push_back(item);
861     _completedTiles[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
862     _is_dirty = true;
863     writeCompletedTilesPersistentCache();
864 }
865
866 void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
867 {
868     if (!_persistentCachePath.exists()) {
869         return;
870     }
871
872     SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
873     time_t now = time(0);
874
875     try {
876         readProperties(_persistentCachePath.str(), cacheRoot);
877     } catch (sg_exception& e) {
878         SG_LOG(SG_TERRASYNC, SG_INFO, "corrupted persistent cache, discarding");
879         return;
880     }
881
882     for (int i=0; i<cacheRoot->nChildren(); ++i) {
883         SGPropertyNode* entry = cacheRoot->getChild(i);
884         bool isNotFound = (strcmp(entry->getName(), "not-found") == 0);
885         string tileName = entry->getStringValue("path");
886         time_t stamp = entry->getIntValue("stamp");
887         if (stamp < now) {
888             continue;
889         }
890
891         if (isNotFound) {
892             _completedTiles[tileName] = stamp;
893         } else {
894             _notFoundItems[tileName] = stamp;
895         }
896     }
897 }
898
899 void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
900 {
901     // cache is disabled
902     if (_persistentCachePath.isNull()) {
903         return;
904     }
905
906     std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
907     if (!f.is_open()) {
908         return;
909     }
910
911     SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
912     TileAgeCache::const_iterator it = _completedTiles.begin();
913     for (; it != _completedTiles.end(); ++it) {
914         SGPropertyNode* entry = cacheRoot->addChild("entry");
915         entry->setStringValue("path", it->first);
916         entry->setIntValue("stamp", it->second);
917     }
918
919     it = _notFoundItems.begin();
920     for (; it != _notFoundItems.end(); ++it) {
921         SGPropertyNode* entry = cacheRoot->addChild("not-found");
922         entry->setStringValue("path", it->first);
923         entry->setIntValue("stamp", it->second);
924     }
925
926     writeProperties(f, cacheRoot, true /* write_all */);
927     f.close();
928 }
929
930 ///////////////////////////////////////////////////////////////////////////////
931 // SGTerraSync ////////////////////////////////////////////////////////////////
932 ///////////////////////////////////////////////////////////////////////////////
933 SGTerraSync::SGTerraSync() :
934     _svnThread(NULL),
935     _bound(false),
936     _inited(false)
937 {
938     _svnThread = new SvnThread();
939     _log = new BufferedLogCallback(SG_TERRASYNC, SG_INFO);
940     _log->truncateAt(255);
941
942     sglog().addCallback(_log);
943 }
944
945 SGTerraSync::~SGTerraSync()
946 {
947     delete _svnThread;
948     _svnThread = NULL;
949     sglog().removeCallback(_log);
950     delete _log;
951      _tiedProperties.Untie();
952 }
953
954 void SGTerraSync::setRoot(SGPropertyNode_ptr root)
955 {
956     _terraRoot = root->getNode("/sim/terrasync",true);
957 }
958
959 void SGTerraSync::init()
960 {
961     if (_inited) {
962         return;
963     }
964
965     _inited = true;
966
967     assert(_terraRoot);
968     _terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available);
969
970     reinit();
971 }
972
973 void SGTerraSync::shutdown()
974 {
975      _svnThread->stop();
976 }
977
978 void SGTerraSync::reinit()
979 {
980     // do not reinit when enabled and we're already up and running
981     if ((_terraRoot->getBoolValue("enabled",false))&&
982          (_svnThread->_active && _svnThread->_running))
983     {
984         return;
985     }
986
987     _svnThread->stop();
988
989     if (_terraRoot->getBoolValue("enabled",false))
990     {
991         _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
992         std::string httpServer(_terraRoot->getStringValue("http-server",""));
993         _svnThread->setHTTPServer(httpServer);
994         _svnThread->setSvnDataServer(_terraRoot->getStringValue("svn-data-server",""));
995         _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
996         _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
997         _svnThread->setAllowedErrorCount(_terraRoot->getIntValue("max-errors",5));
998         _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
999
1000         if (httpServer.empty()) {
1001             // HTTP doesn't benefit from using the persistent cache
1002             _svnThread->setCachePath(SGPath(_terraRoot->getStringValue("cache-path","")));
1003         } else {
1004             SG_LOG(SG_TERRASYNC, SG_INFO, "HTTP repository selected, disabling persistent cache");
1005         }
1006
1007         _svnThread->setCacheHits(_terraRoot->getIntValue("cache-hit", 0));
1008         _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
1009         _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
1010
1011         if (_svnThread->start())
1012         {
1013             syncAirportsModels();
1014         }
1015     }
1016
1017     _stalledNode->setBoolValue(_svnThread->_stalled);
1018 }
1019
1020 void SGTerraSync::bind()
1021 {
1022     if (_bound) {
1023         return;
1024     }
1025
1026     _bound = true;
1027     _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
1028     _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
1029     _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
1030     _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
1031     _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
1032     _tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits );
1033     _tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate );
1034
1035     // use kbytes here because propety doesn't support 64-bit and we might conceivably
1036     // download more than 2G in a single session
1037     _tiedProperties.Tie( _terraRoot->getNode("downloaded-kbytes", true), (int*) &_svnThread->_total_kb_downloaded );
1038
1039     _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
1040     _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
1041     _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
1042     _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
1043     _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
1044     _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
1045     _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
1046     // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
1047     _stalledNode = _terraRoot->getNode("stalled", true);
1048     _stalledNode->setBoolValue(_svnThread->_stalled);
1049     _stalledNode->setAttribute(SGPropertyNode::PRESERVE,true);
1050 }
1051
1052 void SGTerraSync::unbind()
1053 {
1054     _svnThread->stop();
1055     _tiedProperties.Untie();
1056     _bound = false;
1057     _inited = false;
1058
1059     _terraRoot.clear();
1060     _stalledNode.clear();
1061     _cacheHits.clear();
1062 }
1063
1064 void SGTerraSync::update(double)
1065 {
1066     static SGBucket bucket;
1067     if (_svnThread->isDirty())
1068     {
1069         if (!_svnThread->_active)
1070         {
1071             if (_svnThread->_stalled)
1072             {
1073                 SG_LOG(SG_TERRASYNC,SG_ALERT,
1074                        "Automatic scenery download/synchronization stalled. Too many errors.");
1075             }
1076             else
1077             {
1078                 // not really an alert - just always show this message
1079                 SG_LOG(SG_TERRASYNC,SG_ALERT,
1080                         "Automatic scenery download/synchronization has stopped.");
1081             }
1082             _stalledNode->setBoolValue(_svnThread->_stalled);
1083         }
1084
1085         while (_svnThread->hasNewTiles())
1086         {
1087             SyncItem next = _svnThread->getNewTile();
1088
1089             if ((next._type == SyncItem::Tile) || (next._type == SyncItem::AIData)) {
1090                 _activeTileDirs.erase(next._dir);
1091             }
1092         } // of freshly synced items
1093     }
1094 }
1095
1096 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
1097
1098 void SGTerraSync::syncAirportsModels()
1099 {
1100     static const char* bounds = "MZAJKL"; // airport sync order: K-L, A-J, M-Z
1101     // note "request" method uses LIFO order, i.e. processes most recent request first
1102     for( unsigned i = 0; i < strlen(bounds)/2; i++ )
1103     {
1104         for ( char synced_other = bounds[2*i]; synced_other <= bounds[2*i+1]; synced_other++ )
1105         {
1106             ostringstream dir;
1107             dir << "Airports/" << synced_other;
1108             SyncItem w(dir.str(), SyncItem::AirportData);
1109             _svnThread->request( w );
1110         }
1111     }
1112
1113     SyncItem w("Models", SyncItem::SharedModels);
1114     _svnThread->request( w );
1115 }
1116
1117 void SGTerraSync::syncAreaByPath(const std::string& aPath)
1118 {
1119     const char* terrainobjects[3] = { "Terrain/", "Objects/",  0 };
1120     for (const char** tree = &terrainobjects[0]; *tree; tree++)
1121     {
1122         std::string dir = string(*tree) + aPath;
1123         if (_activeTileDirs.find(dir) != _activeTileDirs.end()) {
1124             continue;
1125         }
1126
1127         _activeTileDirs.insert(dir);
1128         SyncItem w(dir, SyncItem::Tile);
1129         _svnThread->request( w );
1130     }
1131 }
1132
1133 bool SGTerraSync::scheduleTile(const SGBucket& bucket)
1134 {
1135     std::string basePath = bucket.gen_base_path();
1136     syncAreaByPath(basePath);
1137     return true;
1138 }
1139
1140 bool SGTerraSync::isTileDirPending(const std::string& sceneryDir) const
1141 {
1142     if (!_svnThread->_running) {
1143         return false;
1144     }
1145
1146     const char* terrainobjects[3] = { "Terrain/", "Objects/",  0 };
1147     for (const char** tree = &terrainobjects[0]; *tree; tree++) {
1148         string s = *tree + sceneryDir;
1149         if (_activeTileDirs.find(s) != _activeTileDirs.end()) {
1150             return true;
1151         }
1152     }
1153
1154     return false;
1155 }
1156
1157 void SGTerraSync::scheduleDataDir(const std::string& dataDir)
1158 {
1159     if (_activeTileDirs.find(dataDir) != _activeTileDirs.end()) {
1160         return;
1161     }
1162
1163     _activeTileDirs.insert(dataDir);
1164     SyncItem w(dataDir, SyncItem::AIData);
1165     _svnThread->request( w );
1166
1167 }
1168
1169 bool SGTerraSync::isDataDirPending(const std::string& dataDir) const
1170 {
1171     if (!_svnThread->_running) {
1172         return false;
1173     }
1174
1175     return (_activeTileDirs.find(dataDir) != _activeTileDirs.end());
1176 }
1177
1178 void SGTerraSync::reposition()
1179 {
1180     // stub, remove
1181 }