-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfurry.py
executable file
·163 lines (140 loc) · 6.38 KB
/
furry.py
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
#!/usr/bin/env python2
import os
import sys
import logging
import datetime
import subprocess
import psycopg2
import shutil
if len(sys.argv) < 3:
print """
Furry Sansa osm database updater.
Usage:
%s [config] [action]
""" % sys.argv[0]
exit()
execfile(sys.argv[1])
logger = logging.getLogger('furry-sansa')
hdlr = logging.FileHandler(instance['log'])
formatter = logging.Formatter('[%(process)s] %(asctime)s %(levelname)5s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
logger.debug('started with options: '+ ' '.join(sys.argv))
def execute(commandline, need_output = False):
"""
A method that calls the commandline, logs properly and measures exectution time.
"""
time = datetime.datetime.now()
logger.info('starting "%s"'% commandline)
if need_output:
process = subprocess.Popen(commandline, bufsize=1, stdout=subprocess.PIPE, shell=True)
else:
process = subprocess.Popen(commandline, bufsize=1, shell=True)
process.wait()
if process.returncode:
logger.error('[%s] failed "%s" in %s'%(process.returncode, commandline, str(datetime.datetime.now() - time)))
else:
logger.info('[%s] completed "%s" in %s'%(process.returncode, commandline, str(datetime.datetime.now() - time)))
if need_output:
return process.stdout.read()
return process.returncode
def sql(query):
"""
A wrapper that measures query execution time.
"""
database_connection = psycopg2.connect(pg_database)
database_connection.set_isolation_level(0) # now we don't have to COMMIT everything
database_cursor = database_connection.cursor()
time = datetime.datetime.now()
logger.info('executing query [%s]'% query)
res = database_cursor.execute(query)
logger.info('[%s] completed in %s, result %s'%(query, str(datetime.datetime.now() - time), str(res)))
action = sys.argv[2]
if not os.path.exists(instance['tmpdir']):
logger.info('creating temp directory %s'%instance['tmpdir'])
os.makedirs(instance['tmpdir'])
if action == 'import':
logger.debug('starting osm2pgsql import')
if 0 == execute('osm2pgsql ' +osm2pgsql_actions['create']):
if os.path.exists(instance['pg_timestamp']):
os.remove(instance['pg_timestamp'])
execute("osmconvert --out-timestamp %s > %s "%(instance['dump'],instance['pg_timestamp']))
if "(" in open(instance['pg_timestamp']).read():
# recalculating timestamp
os.remove(instance['pg_timestamp'])
timestamp = execute('osmconvert --out-statistics %s | grep "timestamp max"'%(instance['dump']), need_output = True)
open(instance['pg_timestamp'], 'w').write(timestamp.strip()[:11]+"00:00:00Z")
elif action == "index":
logger.debug('starting database index')
logger.debug('preparing queries from %s' % instance['index_template'])
queries = [line.split('-- ')[0].strip().replace('%prefix%', instance['pg_table_prefix']) for line in open(instance['index_template']) if line.split('-- ')[0].strip()]
logger.debug('loaded %s queries, connecting to %s' % (len(queries), pg_database))
for query in queries:
sql(query)
elif action == 'synthdump':
logger.debug('starting dump synthesis')
logger.info('downloading dumps')
local_filenames = ""
if 'poly' in instance:
filter_poly = '--complex-ways -B='+os.path.abspath(instance['poly'])
else:
filter_poly = ''
os.chdir(instance['tmpdir'])
if len(instance['external_dumps']) > 1:
for name, url in instance['external_dumps']:
if 0 == execute('wget -c -O "%s" "%s"'%(name, url)): # downloading file finished well
if not os.path.exists(name+'.o5m'):
execute('osmconvert --out-o5m "%s" |gzip > "%s"'%( name, name+'.o5m.gz'))
local_filenames += ' "%s.o5m.gz"'%name
logger.info('merging final dump')
execute('osmconvert --out-o5m %s | gzip > %s'%( local_filenames, 'merged.o5m.gz' ))
logger.info('updating dump')
if not filter_poly:
execute('osmupdate %s %s'%( 'merged.o5m.gz', instance['dump'] ))
else:
execute('osmupdate %s %s'%( 'merged.o5m.gz', 'merged2.o5m' ))
else:
name, url = instance['external_dumps'][0]
if 0 == execute('wget -c -O "%s" "%s"'%(name, url)): # downloading file finished well
logger.info('updating dump')
if not filter_poly:
execute('osmupdate --out-o5m %s %s'%(name, instance['dump'] ))
else:
execute('osmupdate --out-o5m %s %s'%(name, 'merged2.o5m' ))
if filter_poly:
logger.info('cutting dump')
execute('osmconvert --out-o5m %s %s > %s'%('merged2.o5m', filter_poly, instance['dump'] ))
elif action == 'updatedump':
logger.info('updating dump')
if 'poly' in instance:
filter_poly = '--complex-ways -B='+instance['poly']
else:
filter_poly = ''
tmpfile = os.path.join(instance['tmpdir'], 'temp'+os.path.basename(instance['dump']))
if 0 == execute('osmupdate %s %s %s'%( instance['dump'], filter_poly, tmpfile)):
os.remove(instance['dump'])
shutil.move(tmpfile, instance['dump'])
elif action == 'getdiff':
logger.debug('getting diffs')
try:
timestamp = open(instance['pg_timestamp']).read().strip()
except:
logger.error('can not read timestamp file %s, please fill it!'%instance['pg_timestamp'])
exit(1)
if os.path.exists(instance['current_diff']):
timestamp_diff = execute('osmconvert --out-timestamp "%s"'%instance['current_diff'] , need_output = True).strip()
if timestamp_diff == timestamp:
os.remove(instance['current_diff'])
if not os.path.exists(instance['current_diff']):
logger.debug('getting new diffs')
execute('osmupdate --fake-lonlat %s %s'%(timestamp, instance['current_diff']))
timestamp_diff = execute('osmconvert --out-timestamp "%s"'%instance['current_diff'] , need_output = True).strip()
logger.debug('got new diffs, old timestamp %s, new %s'%(timestamp, timestamp_diff))
elif action == 'diff2db':
logger.debug('applying diffs to db')
if 0 == execute('osm2pgsql ' +osm2pgsql_actions['append']):
execute("osmconvert --out-timestamp %s > %s "%(instance['current_diff'],instance['pg_timestamp']))
else:
logger.error('unknown action %s'%action)
exit(10)