forked from FreemapSlovakia/FreemapDiSK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tahlib.pm
373 lines (325 loc) · 11.1 KB
/
tahlib.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use English '-no_match_vars';
use strict;
# =====================================================================
# The following is duplicated from tilesGen.pl
# =====================================================================
my %Config = ReadConfig("freemapdiskclient.conf", "general.conf", "authentication.conf", "layers.conf", "freemapdisk.conf");
my $lastmsglen = 0;
my $idleFor = 0;
my $idleSeconds = 0;
my %faults; #variable to track non transient errors
# hash for MagicMkdir
my %madeDir;
#-----------------------------------------------------------------------------
# Prints status message without newline, overwrites previous message
# (if $newline set, starts new line after message)
#-----------------------------------------------------------------------------
sub statusMessage
{
my ($msg, $Verbose, $currentSubTask, $progressJobs, $progressPercent, $newline) = @_;
if ($Verbose)
{
print STDERR "$msg\n";
return;
}
my $toprint = sprintf("[#%d %3d%% %s] %s%s ", $progressJobs, $progressPercent+.5, $currentSubTask, $msg, ($newline) ? "" : "...");
my $curmsglen = length($toprint);
print STDERR "\r$toprint";
print STDERR " " x ($lastmsglen-$curmsglen);
if ($newline)
{
$lastmsglen = 0;
print STDERR "\n";
}
else
{
$lastmsglen = $curmsglen;
}
}
#-----------------------------------------------------------------------------
# Used to display task completion. Only for verbose mode.
#-----------------------------------------------------------------------------
sub doneMessage
{
my ($msg,$Verbose) = @_;
$msg = "done" if ($msg eq "");
if ($Verbose)
{
print STDERR "$msg\n";
return;
}
}
#-----------------------------------------------------------------------------
# A sleep function with visible countdown
#-----------------------------------------------------------------------------
sub talkInSleep
{
my ($message, $duration,$progstart,$Verbose) = @_;
if ($Verbose)
{
print STDERR "$message: sleeping $duration seconds\n";
sleep $duration;
return;
}
for (my $i = 0; $i< $duration; $i++)
{
my $totalseconds = time() - $progstart;
statusMessage(sprintf("%s. Idle for %d:%02d (%d%% idle) ",
$message,
$idleFor/60, $idleFor%60,
$totalseconds ? $idleSeconds * 100 / $totalseconds : 100));
sleep 1;
$idleFor++;
$idleSeconds++;
}
}
sub setIdle
{
my ($idle,$setTotal) = @_;
if ($setTotal)
{
$idleSeconds = $idle;
}
else
{
$idleFor = $idle;
}
}
sub getIdle
{
my $getTotal = @_;
if ($getTotal)
{
return $idleSeconds;
}
else
{
return $idleFor;
}
}
#-----------------------------------------------------------------------------
# fault handling
#-----------------------------------------------------------------------------
sub addFault
{
my ($faulttype,$diff) = @_;
$diff = 1 if (not $diff);
$faults{$faulttype} += $diff;
return $faults{$faulttype};
}
sub getFault
{
my ($faulttype) = @_;
return $faults{$faulttype};
}
sub resetFault
{
my ($faulttype) = @_;
$faults{$faulttype} = 0;
return "0 but true";
}
#-----------------------------------------------------------------------------
# Run a shell command. Suppress command's stderr output unless it terminates
# with an error code.
#
# Return 1 if ok, 0 on error.
#-----------------------------------------------------------------------------
sub runCommand
{
my ($cmd,$mainPID) = @_;
# $message is deprecated, issue statusmessage prior to exec.
# statusMessage($message, $Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent,0);
if ($Config{Verbose})
{
my $retval = system($cmd);
return ($retval<0) ? 0 : ($retval>>8) ? 0 : 1;
}
my $ErrorFile = $Config{WorkingDirectory}.$mainPID.".stderr";
my $retval = system("$cmd 2> $ErrorFile");
my $ok = 0;
my $ExtraInfo = "\nAdditional info about the Error(s):\n";
# <0 means that the process could not start
if ($retval < 0)
{
print STDERR "ERROR:\n";
print STDERR " Could not run the following command:\n";
print STDERR " $cmd\n";
print STDERR " Please check your installation.\n";
}
else
{
$retval = $retval >> 8;
if ($retval)
{
print STDERR "ERROR\n";
print STDERR " The following command produced an error message:\n";
print STDERR " $cmd\n";
print STDERR " Debug output follows:\n";
open(ERR, $ErrorFile);
while(<ERR>)
{
print STDERR " | $_";
if (grep(/preferences.xml/,$_))
{
$ExtraInfo=$ExtraInfo."\n * Inkscape preference file corrupt. Delete ~/.inkscape/preferences.xml to continue";
addFault("fatal",1); ## this error is fatal because it needs human intervention before processing can continue
}
if (grep(/infinite template recursion/,$_))
{
$ExtraInfo=$ExtraInfo."\n * Tile too complex for Xmlstarlet, possibly an excessively long way, or too many maplint errors";
}
}
close(ERR);
print STDERR $ExtraInfo."\n\n";
}
else
{
$ok = 1;
}
}
killafile($ErrorFile);
return $ok;
}
#-----------------------------------------------------------------------------
# Delete a file if it exists
#-----------------------------------------------------------------------------
sub killafile($){
my $file = shift();
unlink $file if(-f $file);
}
#-----------------------------------------------------------------------------
# Create a directory and all its parent directories
# (equivalent to a "mkdir -p" on Unix, but stores already-created dirs
# in a hash to avoid unnecessary system calls)
#-----------------------------------------------------------------------------
sub MagicMkdir {
my $file = shift;
my @paths = split(/\\/, $file);
pop(@paths);
my $dir = "";
foreach my $path(@paths) {
if ($dir eq "") {
$dir .= $path; # how are paths with leading "/" handled now?
} else {
$dir .= $Config{Slash}.$path;
}
if (!defined($madeDir{$dir})) {
mkdir $dir;
$madeDir{$dir}=1;
}
}
}
#-----------------------------------------------------------------------------
# GET a URL and save contents to file
#-----------------------------------------------------------------------------
sub DownloadFile {
my ($URL, $File, $UseExisting) = @_;
my $ua = LWP::UserAgent->new(keep_alive => 1, timeout => 1800);
$ua->agent("FreemapDiSK/2011.05.11");
$ua->env_proxy();
if(!$UseExisting) {
killafile($File);
}
# Note: mirror sets the time on the file to match the server time. This
# is important for the handling of JobTime later.
my $r=$ua->mirror($URL, $File);
if ($r->is_success) {
doneMessage(sprintf("done, %d bytes", -s $File));
} else {
printf("\n\nerror: %s\r\n", $r->message);
}
}
#-----------------------------------------------------------------------------
# Merge multiple OSM files into one, making sure that elements are present in
# the destination file only once even if present in more than one of the input
# files.
#
# This has become necessary in the course of supporting maplint, which would
# get upset about duplicate objects created by combining downloaded stripes.
#-----------------------------------------------------------------------------
sub mergeOsmFiles {
my ($destFile, $sourceFiles) = @_;
my $existing = {};
# If there's only one file, just copy the input to the output
if( scalar(@$sourceFiles) == 1 ) {
copy $sourceFiles->[0], $destFile;
killafile ($sourceFiles->[0]) if (!$Config{Debug});
return;
}
open (DEST, "> $destFile");
print DEST qq(<?xml version="1.0" encoding="UTF-8"?>\n);
my $header = 0;
foreach my $sourceFile(@{$sourceFiles}) {
open(SOURCE, $sourceFile);
while(<SOURCE>) {
next if /^\s*<\?xml/;
# We want to copy the version number, but only the first time (obviously)
# Handle where the input doesn't have a version
if (/^\s*<osm.*(?:version=([\d.'"]+))?/) {
if( not $header ) {
my $version = $1 || "'".$Config{"OSMVersion"}."'";
print DEST qq(<osm version=$version generator="tilesGen mergeOsmFiles">\n);
$header = 1;
}
next;
}
last if (/^\s*<\/osm>/);
if (/^\s*<(node|segment|way|relation) id="(\d+)".*(.)>/) {
my ($what, $id, $slash) = ($1, $2, $3);
my $key = substr($what, 0, 1) . $id;
if (defined($existing->{$key})) {
# object exists already. skip!
next if ($slash eq "/");
while(<SOURCE>) {
last if (/^\s*<\/$what>/);
}
next;
} else {
# object didn't exist, note
$existing->{$key} = 1;
}
}
print DEST;
}
close(SOURCE);
killafile ($sourceFile) if (!$Config{Debug});
}
print DEST "</osm>\n";
close(DEST);
}
#-----------------------------------------------------------------------------
# UnzipFile downloaded file from FreemapDiSK data storage
#-----------------------------------------------------------------------------
sub UnzipFile {
my ($Zip, $File) = @_;
my $stdOut = $Config{WorkingDirectory}.$PID.".stdout";
my $Command = sprintf("%s %s %s >%s",
"$Config{Zip}",
"e $Zip",
"-y",
$stdOut);
runCommand("$Command",$PID);
killafile($stdOut);
}
#-----------------------------------------------------------------------------
# Clean up temporary files before exit, then exit or return with error
# depending on mode (loop, xy, ...)
#-----------------------------------------------------------------------------
sub cleanUpAndDie {
my ($Reason,$Mode,$Severity,$mainPID) = @_;
## TODO: clean up *.tempdir too
print STDERR "\n$Reason\n" if ($Config{"Verbose"});
if (! $Config{"Debug"}) {
opendir (TEMPDIR, $Config{"WorkingDirectory"});
my @files = grep { /$mainPID/ } readdir(TEMPDIR); # FIXME: this will get files from other processes using the same tempdir for low pids
closedir (TEMPDIR);
while (my $file = shift @files) {
print STDERR "deleting ".$Config{"WorkingDirectory"}."/".$file."\n" if ($Config{"Verbose"});
killafile($Config{"WorkingDirectory"}."/".$file);
}
}
return 0 if ($Mode eq "loop");
print STDERR "\n$Reason\n" if (! $Config{"Verbose"}); #print error only once, and only if fatal.
exit($Severity);
}
1;