]> git.mxchange.org Git - flightgear.git/blob - utils/TerraSync/terrasync.cxx
John Denker:
[flightgear.git] / utils / TerraSync / terrasync.cxx
1 // terrasync.cxx -- "JIT" scenery fetcher
2 //
3 // Written by Curtis Olson, started 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 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #ifdef HAVE_WINDOWS_H
29 #include <windows.h>
30 #endif
31
32
33 #include <stdlib.h>             // atoi() atof() abs() system()
34
35 #include <simgear/compiler.h>
36
37 #include <iostream>
38 #include <fstream>
39 #include <string>
40 #include <deque>
41 #include <map>
42
43 #include <plib/netSocket.h>
44 #include <plib/ul.h>
45
46 #include <simgear/bucket/newbucket.hxx>
47 #include <simgear/misc/sg_path.hxx>
48
49 #ifdef HAVE_SVN_CLIENT_H
50 #  ifdef HAVE_LIBSVN_CLIENT_1
51 #    include <svn_auth.h>
52 #    include <svn_client.h>
53 #    include <svn_cmdline.h>
54 #    include <svn_pools.h>
55 #  else
56 #    undef HAVE_SVN_CLIENT_H
57 #  endif
58 #endif
59
60 using namespace std;
61
62 const char* source_base = NULL;
63 const char* svn_base =
64   "http://terrascenery.googlecode.com/svn/trunk/data/Scenery";
65 const char* rsync_base = "scenery.flightgear.org::Scenery";
66 const char* dest_base = "terrasyncdir";
67 const char* rsync_cmd = 
68     "rsync --verbose --archive --delete --perms --owner --group";
69
70 #ifdef HAVE_SVN_CLIENT_H
71 bool use_svn = true;
72 #else
73 bool use_svn = false;
74 const char* svn_cmd = "svn checkout";
75 #endif
76
77 // display usage
78 static void usage( const string& prog ) {
79     cout << 
80 "Usage:  terrasync [options]\n"
81 "Options:  \n"
82 " -d <dest>       destination directory [required]\n"
83 " -R              transport using pipe to rsync\n"
84 " -S              transport using built-in svn\n"
85 " -p <port>       listen on UDP port [default: 5501]\n"
86 " -s <source>     source base [default: '']\n"
87 " -pid <pidfile>  write PID to file\n"
88 " -v              be more verbose\n"
89 ;
90
91 #ifdef HAVE_SVN_CLIENT_H
92     cout << "    (defaults to the built in subversion)" << endl;
93 #else
94     cout << "    (defaults to rsync, using external commands)" << endl;
95 #endif
96
97   cout << "\nExample:\n"
98 "pid=$(cat $pidfile 2>/dev/null)\n"
99 "if test -n \"$pid\" && kill -0 $pid ; then\n"
100 "    echo \"terrasync already running: $pid\"\n"
101 "else\n"
102 "    nice /games/sport/fgs/utils/TerraSync/terrasync         \\\n"
103 "      -v -pid $pidfile -S -p 5500 -d /games/orig/terrasync &\n"
104 "fi" << endl;
105
106 }
107
108 std::deque<std::string> waitingTiles;
109 typedef std::map<std::string,time_t> CompletedTiles;
110 CompletedTiles completedTiles;
111
112 #ifdef HAVE_SVN_CLIENT_H
113
114 // Things we need for doing subversion checkout - often
115 apr_pool_t *mysvn_pool = NULL;
116 svn_client_ctx_t *mysvn_ctx = NULL;
117 svn_opt_revision_t *mysvn_rev = NULL;
118 svn_opt_revision_t *mysvn_rev_peg = NULL;
119
120 static const svn_version_checklist_t mysvn_checklist[] = {
121     { "svn_subr",   svn_subr_version },
122     { "svn_client", svn_client_version },
123     { "svn_wc",     svn_wc_version },
124     { "svn_ra",     svn_ra_version },
125     { "svn_delta",  svn_delta_version },
126     { "svn_diff",   svn_diff_version },
127     { NULL, NULL }
128 };
129
130 // Configure our subversion session
131 int mysvn_setup(void) {
132     // Are we already prepared?
133     if (mysvn_pool) return EXIT_SUCCESS;
134     // No, so initialize svn internals generally
135 #ifdef _MSC_VER
136     // there is a segfault when providing an error stream.
137     //  Apparently, calling setvbuf with a nul buffer is
138     //  not supported under msvc 7.1 ( code inside svn_cmdline_init )
139     if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
140         return EXIT_FAILURE;
141 #else
142     if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
143         return EXIT_FAILURE;
144 #endif
145     apr_pool_t *pool;
146     apr_pool_create(&pool, NULL);
147     svn_error_t *err = NULL;
148     SVN_VERSION_DEFINE(mysvn_version);
149     err = svn_ver_check_list(&mysvn_version, mysvn_checklist);
150     if (err)
151         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
152     err = svn_ra_initialize(pool);
153     if (err)
154         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
155     char *config_dir = NULL;
156     err = svn_config_ensure(config_dir, pool);
157     if (err)
158         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
159     err = svn_client_create_context(&mysvn_ctx, pool);
160     if (err)
161         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
162     err = svn_config_get_config(&(mysvn_ctx->config),
163         config_dir, pool);
164     if (err)
165         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
166     svn_config_t *cfg;
167     cfg = ( svn_config_t*) apr_hash_get(
168         mysvn_ctx->config,
169         SVN_CONFIG_CATEGORY_CONFIG,
170         APR_HASH_KEY_STRING);
171     if (err)
172         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
173     svn_auth_baton_t *ab;
174     err = svn_cmdline_setup_auth_baton(&ab,
175         TRUE, NULL, NULL, config_dir, TRUE, cfg,
176         mysvn_ctx->cancel_func, mysvn_ctx->cancel_baton, pool);
177     if (err)
178         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
179     mysvn_ctx->auth_baton = ab;
180     mysvn_ctx->conflict_func = NULL;
181     mysvn_ctx->conflict_baton = NULL;
182     // Now our magic revisions
183     mysvn_rev = (svn_opt_revision_t*) apr_palloc(pool, 
184         sizeof(svn_opt_revision_t));
185     if (!mysvn_rev)
186         return EXIT_FAILURE;
187     mysvn_rev_peg = (svn_opt_revision_t*) apr_palloc(pool, 
188         sizeof(svn_opt_revision_t));
189     if (!mysvn_rev_peg)
190         return EXIT_FAILURE;
191     mysvn_rev->kind = svn_opt_revision_head;
192     mysvn_rev_peg->kind = svn_opt_revision_unspecified;
193     // Success if we got this far
194     mysvn_pool = pool;
195     return EXIT_SUCCESS;
196 }
197
198 #endif
199
200 // sync one directory tree
201 void sync_tree(const char* dir) {
202     int rc;
203     char command[512];
204     SGPath path( dest_base );
205
206     path.append( dir );
207     rc = path.create_dir( 0755 );
208     if (rc) {
209         cout << "Return code = " << rc << endl;
210         exit(1);
211     }
212
213     if (use_svn) {
214 #ifdef HAVE_SVN_CLIENT_H
215         cout << dir << " ... ";
216         cout.flush();
217         char dest_base_dir[512];
218         snprintf( command, 512,
219             "%s/%s", source_base, dir);
220         snprintf( dest_base_dir, 512,
221             "%s/%s", dest_base, dir);
222         svn_error_t *err = NULL;
223         if (mysvn_setup() != EXIT_SUCCESS)
224             exit(1);
225         apr_pool_t *subpool = svn_pool_create(mysvn_pool);
226         err = svn_client_checkout3(NULL,
227             command,
228             dest_base_dir,
229             mysvn_rev_peg,
230             mysvn_rev,
231             svn_depth_infinity,
232             0,
233             0,
234             mysvn_ctx,
235             subpool);
236         if (err) {
237             // Report errors from the checkout attempt
238             cout << "failed: " << endl
239                  << err->message << endl;
240             svn_error_clear(err);
241             return;
242         } else {
243             cout << "done" << endl;
244         }
245         svn_pool_destroy(subpool);
246         return;
247 #else
248
249         snprintf( command, 512,
250             "%s %s/%s %s/%s", svn_cmd,
251             source_base, dir,
252             dest_base, dir );
253 #endif
254     } else {
255         snprintf( command, 512,
256             "%s %s/%s/ %s/%s/", rsync_cmd,
257             source_base, dir,
258             dest_base, dir );
259     }
260     cout << command << endl;
261     rc = system( command );
262     if (rc) {
263         cout << "Return code = " << rc << endl;
264         if (rc == 5120) exit(1);
265     }
266 }
267
268
269 const int nowhere = -9999;
270
271 // parse message
272 static void parse_message( const string &msg, int *lat, int *lon ) {
273     double dlat, dlon;
274     string text = msg;
275
276     // find GGA string and advance to start of lat
277     string::size_type pos = text.find( "$GPGGA" );
278     if ( pos == string::npos )
279     {
280         *lat = -9999.0;
281         *lon = -9999.0;
282         return;
283     }
284     string tmp = text.substr( pos + 7 );
285     pos = tmp.find( "," );
286     tmp = tmp.substr( pos + 1 );
287     // cout << "-> " << tmp << endl;
288
289     // find lat then advance to start of hemisphere
290     pos = tmp.find( "," );
291     string lats = tmp.substr( 0, pos );
292     dlat = atof( lats.c_str() ) / 100.0;
293     tmp = tmp.substr( pos + 1 );
294
295     // find N/S hemisphere and advance to start of lon
296     if ( tmp.substr( 0, 1 ) == "S" ) {
297         dlat = -dlat;
298     }
299     pos = tmp.find( "," );
300     tmp = tmp.substr( pos + 1 );
301
302     // find lon
303     pos = tmp.find( "," );
304     string lons = tmp.substr( 0, pos );
305     dlon = atof( lons.c_str() ) / 100.0;
306     tmp = tmp.substr( pos + 1 );
307
308     // find E/W hemisphere and advance to start of lon
309     if ( tmp.substr( 0, 1 ) == "W" ) {
310         dlon = -dlon;
311     }
312
313     if ( dlat < 0 ) {
314         *lat = (int)dlat - 1;
315     } else {
316         *lat = (int)dlat;
317     }
318
319     if ( dlon < 0 ) {
320         *lon = (int)dlon - 1;
321     } else {
322         *lon = (int)dlon;
323     }
324
325     if ((dlon == 0) && (dlat == 0)) {
326       *lon = nowhere;
327       *lat = nowhere;
328     }
329 }
330
331
332 // sync area
333 static void sync_area( int lat, int lon ) {
334     if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
335         return;
336     char NS, EW;
337     int baselat, baselon;
338
339     if ( lat < 0 ) {
340         int base = (int)(lat / 10);
341         if ( lat == base * 10 ) {
342             baselat = base * 10;
343         } else {
344             baselat = (base - 1) * 10;
345         }
346         NS = 's';
347     } else {
348         baselat = (int)(lat / 10) * 10;
349         NS = 'n';
350     }
351     if ( lon < 0 ) {
352         int base = (int)(lon / 10);
353         if ( lon == base * 10 ) {
354             baselon = base * 10;
355         } else {
356             baselon = (base - 1) * 10;
357         }
358         EW = 'w';
359     } else {
360         baselon = (int)(lon / 10) * 10;
361         EW = 'e';
362     }
363
364     const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
365     
366     for (const char** tree = &terrainobjects[0]; *tree; tree++) {
367         char dir[512];
368         snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
369                 *tree,
370                 EW, abs(baselon), NS, abs(baselat),
371                 EW, abs(lon), NS, abs(lat) );
372         waitingTiles.push_back( dir );
373     }
374 }
375
376
377 // sync areas
378 static void sync_areas( int lat, int lon, int lat_dir, int lon_dir ) {
379     // do current 1x1 degree area first
380     sync_area( lat, lon );
381
382     if ( lat_dir == 0 && lon_dir == 0 ) {
383         // now do surrounding 8 1x1 degree areas.
384         for ( int i = lat - 1; i <= lat + 1; ++i ) {
385             for ( int j = lon - 1; j <= lon + 1; ++j ) {
386                 if ( i != lat || j != lon ) {
387                     sync_area( i, j );
388                 }
389             }
390         }
391     } else {
392         if ( lat_dir != 0 ) {
393             sync_area( lat + lat_dir, lon );
394             sync_area( lat + lat_dir, lon - 1 );
395             sync_area( lat + lat_dir, lon + 1 );
396         }
397         if ( lon_dir != 0 ) {
398             sync_area( lat, lon + lon_dir );
399             sync_area( lat - 1, lon + lon_dir );
400             sync_area( lat + 1, lon + lon_dir );
401         }
402     }
403 }
404
405 void getWaitingTile() {
406     while ( !waitingTiles.empty() ) {
407         CompletedTiles::iterator ii = completedTiles.find( waitingTiles.front() );
408         time_t now = time(0);
409         if ( ii == completedTiles.end() || ii->second + 600 < now ) {
410             sync_tree(waitingTiles.front().c_str());
411             completedTiles[ waitingTiles.front() ] = now;
412             waitingTiles.pop_front();
413             break;
414         }
415         waitingTiles.pop_front();
416     }
417 }
418
419 int main( int argc, char **argv ) {
420     int port = 5501;
421     char host[256] = "";        // accept messages from anyone
422     bool testing = false;
423     bool do_checkout(true);
424     int verbose(0);
425     const char* pidfn = "";
426
427     // parse arguments
428     int i = 1;
429     while ( i < argc ) {
430         if ( (string)argv[i] == "-p" ) {
431             ++i;
432             port = atoi( argv[i] );
433         } else if ( string(argv[i]).find("-pid") == 0 ) {
434             ++i;
435             pidfn = argv[i];
436             cout << "pidfn: " << pidfn << endl;
437         } else if ( (string)argv[i] == "-s" ) {
438             ++i;
439             source_base = argv[i];
440         } else if ( (string)argv[i] == "-d" ) {
441             ++i;
442             dest_base = argv[i];
443         } else if ( (string)argv[i] == "-R" ) {
444             use_svn = false;
445         } else if ( (string)argv[i] == "-S" ) {
446             use_svn = true;
447         } else if ( (string)argv[i] == "-v" ) {
448             verbose++;
449         } else if ( (string)argv[i] == "-T" ) {
450             testing = true;
451         } else if ( (string)argv[i] == "-h" ) {
452             usage( argv[0] );
453             exit(0);
454         } else {
455             cerr << "Unrecognized verbiage '" << argv[i] << "'" << endl;
456             usage( argv[0] );
457             exit(-1);        
458         }
459         ++i;
460     }
461
462     if (*pidfn) {
463       ofstream pidstream;
464       pidstream.open(pidfn);
465       if (!pidstream.good()) {
466         cerr << "Cannot open pid file '" << pidfn << "': ";
467         perror(0);
468         exit(2);
469       }
470       pidstream << getpid() << endl;
471       pidstream.close();
472     }
473
474     // Use the appropriate default for the "-s" flag
475     if (source_base == NULL) {
476         if (use_svn)
477             source_base = svn_base;
478         else
479             source_base = rsync_base;
480     }
481     
482     // Must call this before any other net stuff
483     netInit( &argc,argv );
484
485     netSocket s;
486
487     if ( ! s.open( false ) ) {  // open a UDP socket
488         printf("error opening socket\n");
489         return -1;
490     }
491
492     if ( s.bind( host, port ) == -1 ) {
493         printf("error binding to port %d\n", port);
494         return -1;
495     }
496
497     char msg[256];
498     int maxlen = 256;
499     int len;
500     int lat, lon;
501     int last_lat = nowhere;
502     int last_lon = nowhere;
503     bool recv_msg = false;
504
505     char synced_other;
506     if (do_checkout) {
507         for ( synced_other = 'K'; synced_other <= 'Z'; synced_other++ ) {
508             char dir[512];
509             snprintf( dir, 512, "Airports/%c", synced_other );
510             waitingTiles.push_back( dir );
511         }
512         for ( synced_other = 'A'; synced_other <= 'J'; synced_other++ ) {
513             char dir[512];
514             snprintf( dir, 512, "Airports/%c", synced_other );
515             waitingTiles.push_back( dir );
516         }
517         if ( use_svn ) {
518             waitingTiles.push_back( "Models" );
519         }
520     }
521
522
523     while ( true ) {                    // main loop
524         recv_msg = false;
525         if ( testing ) {
526             // No FGFS communications
527             lat = 37;
528             lon = -123;
529             recv_msg = (lat != last_lat) || (lon != last_lon);
530         } else {
531             s.setBlocking(waitingTiles.empty());
532             len = s.recv(msg, maxlen, 0);
533             if (len >= 0) {
534                 msg[len] = '\0';
535                 recv_msg = true;
536                 if (verbose) cout << "recv length: " << len << endl;
537                 parse_message( msg, &lat, &lon );
538             }
539         }
540
541         if ( recv_msg ) {
542              // Ignore messages where the location does not change
543              if ( lat != last_lat || lon != last_lon ) {
544                 cout << "pos in msg = " << lat << "," << lon << endl;
545                 std::deque<std::string> oldRequests;
546                 oldRequests.swap( waitingTiles );
547                 int lat_dir, lon_dir, dist;
548                 if ( last_lat == nowhere || last_lon == nowhere ) {
549                     lat_dir = lon_dir = 0;
550                 } else {
551                     dist = lat - last_lat;
552                     if ( dist != 0 ) {
553                         lat_dir = dist / abs(dist);
554                     } else {
555                         lat_dir = 0;
556                     }
557                     dist = lon - last_lon;
558                     if ( dist != 0 ) {
559                         lon_dir = dist / abs(dist);
560                     } else {
561                         lon_dir = 0;
562                     }
563                 }
564                 cout << "lat = " << lat << " lon = " << lon << endl;
565                 cout << "lat_dir = " << lat_dir << "  "
566                      << "lon_dir = " << lon_dir << endl;
567                 sync_areas( lat, lon, lat_dir, lon_dir );
568                 while ( !oldRequests.empty() ) {
569                     waitingTiles.push_back( oldRequests.front() );
570                     oldRequests.pop_front();
571                 }
572                 last_lat = lat;
573                 last_lon = lon;
574             }
575         }
576
577         // No messages inbound, so process some pending work
578         else if ( !waitingTiles.empty() ) {
579             getWaitingTile();
580         }
581
582         else if ( testing ) {
583             exit( 0 );
584         } else
585
586         ulSleep( 1 );
587     } // while true
588         
589     return 0;
590 }