-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathci_datasetintegration.py
More file actions
1711 lines (1492 loc) · 82 KB
/
Copy pathci_datasetintegration.py
File metadata and controls
1711 lines (1492 loc) · 82 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# python 3.5
import sys
import re
import json
from pprint import pprint
import os.path
import git
from git import Repo
from datetime import date, datetime, timedelta
import osgeo.ogr
import traceback
import logging
import subprocess
import csv
from ci_secrets.secrets import DB_password, DB_database, DB_host, DB_port, DB_user, GIT_base_path, GEO_base_path, \
GEO_number_of_pyarmid_levels, GEO_user, GEO_password, GEO_url, GEO_port, GEO_workspace, GEO_db_store, TAIGA_token, GIT_token, SERVER, DEBUG
from db import db_helper
import validate_datapackage
from db.db_helper import str_with_quotes, str_with_single_quotes
import requests
import gitlab
from gitlab import GitlabError, GitlabAuthenticationError, GitlabConnectionError, GitlabHttpError
import logging
from time import time, strftime, gmtime
from taiga import TaigaAPI
from taiga.exceptions import TaigaException
from config import STAT_SCHEMA, GEO_SCHEMA, LAU_TABLE, LAU_TABLE_NAME, NUTS_TABLE, NUTS_TABLE_NAME, VECTOR_SRID, RASTER_SRID, TIME_TABLE, TIME_TABLE_NAME
log_start_time = time()
log_previous_time = log_start_time
print(strftime("Execution start time: %Y-%m-%d %H:%M:%S +0000", gmtime(log_start_time)))
try:
taiga_api = TaigaAPI(token=TAIGA_token)
taiga_project = taiga_api.projects.get_by_slug('widmont-hotmaps')
except:
print("Could not connect to Taiga. Token might be outdated")
taiga_api = None
taiga_project = None
logging.basicConfig(level=logging.INFO)
# current path
base_path = os.path.dirname(os.path.abspath(__file__))
# git repositories path
repositories_base_path = GIT_base_path
def log_print_step(text):
print(text)
log_end_time = time()
global log_previous_time
prev_time = log_previous_time
print(strftime("%Y-%m-%d %H:%M:%S +0000", gmtime(log_end_time)))
hours, rem = divmod(log_end_time-prev_time, 3600)
minutes, seconds = divmod(rem, 60)
print("Current step time: {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
hours, rem = divmod(log_end_time-log_start_time, 3600)
minutes, seconds = divmod(rem, 60)
print("Ellapsed time: {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
log_previous_time = log_end_time
def post_issue(name, description, issue_type='Dataset integration', tags=[]):
if DEBUG:
print(name, description, issue_type, tags.append(SERVER))
return
tags.append(SERVER)
if taiga_project is not None:
issue = taiga_project.add_issue(
name,
taiga_project.priorities.get(name='Workaround possible - Low').id,
taiga_project.issue_statuses.get(name='New').id,
taiga_project.issue_types.get(name=issue_type).id,
taiga_project.severities.get(name='Minor').id,
description=description,
tags=tags
)
def post_issue_repo(project, name, description):
issue = project.issues.create({'title': name, 'description': description})
def get_property_datapackage(obj, property_name, repo_name, resource_name):
try:
vector = obj[property_name]
except:
post_issue(name='Integration of resource failed - repository ' + repo_name,
description='No vector attribute provided for resource "' + resource_name + '". The resource has been skipped.'
+ 'Make sure that "' + property_name + '" attribute is correctly declared in the "datapackage.json" file',
issue_type='Dataset Provider improvement needed')
def parse_date(str):
for format in ('%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M:%S', '%d/%m/%Y %H:%M:%S', '%d.%m.%Y %H:%M:%S',
'%Y/%m/%d %H:%M', '%Y-%m-%d %H:%M', '%d/%m/%Y %H:%M', '%d.%m.%Y %H:%M',
'%Y/%m/%d', '%Y-%m-%d', '%d/%m/%Y', '%d.%m.%Y',
'%Y/%m', '%Y-%m', '%m/%Y', '%m.%Y',
'%Y'):
try:
return datetime.strptime(str, format)
except:
pass
raise ValueError('date format not supported! excpecting: ',
'%Y/%m/%d %H:%M:%S', ' or ', '%Y-%m-%d %H:%M:%S', ' or ', '%d.%m.%Y %H:%M:%S', ' or ',
'%d/%m/%Y %H:%M:%S', ' or ', '%Y/%m/%d %H:%M', ' or ', '%d.%m.%Y %H:%M', ' or ',
'%Y-%m-%d %H:%M', ' or ', '%d/%m/%Y %H:%M', ' or ',
'%Y/%m/%d', ' or ', '%Y-%m-%d', ' or ', '%d/%m/%Y', '%d.%m.%Y', ' or ',
'%Y/%m', ' or ', '%Y-%m', ' or ', '%m/%Y', ' or ', '%m.%Y', ' or ',
'%Y')
def get_or_create_time_id(timestamp, granularity):
t = timestamp
d = None
try:
d = parse_date(timestamp)
except ValueError:
raise
if d is not None:
t = datetime.strftime(d, '%Y/%m/%d %H:%M:%S')
fk_time_id = db.query(commit=True,
query="SELECT id FROM stat.time WHERE timestamp = '" + t + "' AND granularity LIKE '" + granularity + "'")
if fk_time_id == None:
print("Error getting fk_time_id with psycopg2")
elif len(fk_time_id) == 0:
time_attributes = []
timestamp_att = parse_date(timestamp)
# timestamp
time_attributes.append(timestamp)
# year
year = timestamp_att.strftime('%Y')
time_attributes.append(year)
# month
time_attributes.append(timestamp_att.strftime('%m'))
# day
time_attributes.append(timestamp_att.strftime('%d'))
#[0][0] weekday
weekday_num = timestamp_att.strftime('%w')
if weekday_num != 0 and weekday_num != 6:
weekday = "Week"
else:
weekday = timestamp_att.strftime('%a')
time_attributes.append(weekday)
# season
year = int(year)
seasons = [('winter', (date(year, 1, 1), date(year, 3, 20))),
('spring', (date(year, 3, 21), date(year, 6, 20))),
('summer', (date(year, 6, 21), date(year, 9, 22))),
('autumn', (date(year, 9, 23), date(year, 12, 20))),
('winter', (date(year, 12, 21), date(year, 12, 31)))]
season = next(s for s, (start, end) in seasons if start <= timestamp_att.date() <= end)
time_attributes.append(season)
# hour
hour = timestamp_att.strftime('%H')
time_attributes.append(hour)
# hour of yearprint(
day_of_year = timestamp_att.strftime('%j')
hour_of_year = int(day_of_year) * int(hour)
time_attributes.append(hour_of_year)
# date
time_attributes.append(timestamp_att.strftime('%Y-%m-%d'))
# granularity
time_attributes.append(granularity)
fk_time_id = db.query(commit=True,
query='INSERT INTO ' + TIME_TABLE +
' (timestamp, year, month, day, weekday, season, hour_of_day, hour_of_year, date, granularity) ' +
'VALUES (' + ', '.join(map(str_with_single_quotes, time_attributes)) + ') RETURNING id')
if len(fk_time_id) > 0 and len(fk_time_id[0]) > 0:
fk_time_id = fk_time_id[0][0]
return fk_time_id
def update_or_create_repo(repo_name, git_id):
r = repo_name
d = datetime.now()
d_str = d.strftime('%Y-%m-%d')
repo_id = db.query( commit=True,
query="SELECT id FROM public.repo WHERE name LIKE '" + r + "' AND git_id = '" + str(git_id) + "'")
if repo_id == None:
print("Error getting repo_id with psycopg2")
elif len(repo_id) == 0:
repo_attributes = [repo_name, str(git_id)]
repo_attributes.append(d_str)
repo_attributes.append(d_str)
repo_id = db.query( commit=True,
query='INSERT INTO public.repo ' +
'(name, git_id, created, updated) ' +
'VALUES (' + ', '.join(map(str_with_single_quotes, repo_attributes)) + ') RETURNING id')
if len(repo_id) > 0 and len(repo_id[0]) > 0:
repo_id = repo_id[0][0]
db.query(commit=True,
query="UPDATE public.repo SET updated = '" + d_str + "' WHERE id = " + str(repo_id))
return repo_id
def import_shapefile(src_file, date, temporal_resolution, attributes_names):
# import shp
# src_file = os.path.join("git-repos", "HotmapsLAU", "data", "HotmapsLAU.shp")
shapefile = osgeo.ogr.Open(src_file)
layer = shapefile.GetLayer(0)
for i in range(layer.GetFeatureCount()):
feature = layer.GetFeature(i)
values = []
# get fields dynamically
for att in attributes_names:
values.append(feature.GetField(att))
geom = feature.GetGeometryRef()
# convert Polygon type to MultiPolygon
if geom.GetGeometryType() == osgeo.ogr.wkbPolygon:
geom = osgeo.ogr.ForceToMultiPolygon(geom)
# export as WKT
wkt = geom.ExportToWkt()
# add date from datapackage.json
values.append(date) # date col
values.append(date) # timestamp col
# add date foreign key
fk_time_id = get_or_create_time_id(timestamp=start_date, granularity=temporal_resolution)
print('fk_time_id=', fk_time_id)
values.append(fk_time_id)
db.query(commit=True,
query='INSERT INTO ' + GEO_SCHEMA + '.' + table_name
+ ' (' + ', '.join(
map(db_helper.str_with_quotes, [x.lower() for x in db_attributes_names])) + ')'
+ ' VALUES ('
+ ', '.join(map(db_helper.str_with_single_quotes, values))
+ ', ST_GeomFromText(\'' + wkt + '\', ' + str(proj) + ')'
+ ')'
)
# connect to databaselistOfRepositories
db = db_helper.DB(host=DB_host, port=str(DB_port), database=DB_database, user=DB_user, password=DB_password)
verbose = False
# create table repo (integration status)
db.create_table(table_name='public' + '.' + 'repo', col_names=['name', 'git_id', 'created', 'updated'],
col_types=['varchar(255)', 'bigint', 'timestamp', 'timestamp'], id_col_name='id')
# check repository on gitlab
repo_date = datetime.utcnow()-timedelta(days=1) # allows to retrieve the datasets from past 24h
#repo_date = datetime(2010, 1, 1, 0, 0, 0) # allows to retrieve datasets.
dateStr = repo_date.isoformat(sep='T')+'Z'
gl = gitlab.Gitlab('https://gitlab.com', private_token=GIT_token)
hotmapsGroups = []
listOfRepositories = []
listOfRepoIds = {}
if len(sys.argv) > 1:
log_print_step('Manual integration process')
# manual pull
for arg in sys.argv[1:]:
print(arg)
p = gl.projects.list(search=arg)
if len(p) > 0:
proj = gl.projects.get(p[0].id)
print(proj.name, proj.id)
repository_name = proj.name
repository_path = os.path.join(repositories_base_path, repository_name)
if os.path.exists(repository_path):
# git pull
print('update repository')
repo = Repo(repository_path)
repo.git.execute(["git", "fetch", "--all"])
repo.git.execute(["git", "reset", "--hard", "origin/master"])
repo.git.execute(["git", "lfs", "pull"]) # force pull lfs files
print('successfuly updated repository')
else:
# git clone
print('clone repository')
url = proj.http_url_to_repo
repo = Repo.clone_from(url, repository_path)
repo.git.execute(["git", "lfs", "pull"]) # force pull lfs files
print('successfuly cloned repository')
# add to list of repositories to process if clone/pull succeeds (only!)
listOfRepositories.append(proj.name)
listOfRepoIds[proj.name] = proj.id
else:
print('repository not found')
else :
log_print_step('Automatic integration process')
# automatic pull/clone
allGroups = gl.groups.list()
group = gl.groups.get('1354895')
hotmapsGroups.append(group)
#print('gitlab group #' + group.id)
subgroups = group.subgroups.list()
log_print_step("Clone/Update repositories")
# Add all subgroups in the groups list as groups
for subgroup in subgroups:
hotmapsGroups.append(gl.groups.get(subgroup.id, lazy=True))
for group in hotmapsGroups:
projects = group.projects.list(all=True)
print(projects)
for project in projects:
proj = gl.projects.get(id=project.id)
# check if repo is private or not
if proj.visibility != 'public':
print('Repository', proj.name, 'is not public. Skipping...')
post_issue(name='Visibility issue for ' + proj.name,
description='The repository is not public and has been skipped. Please set the repository to public in order to integrate it.',
issue_type='Integration script execution')
continue
commits = proj.commits.list(since=dateStr)
try:
if len(commits) == 0:
print('No recent commit for repository ' + proj.name)
else:
repository_name = proj.name
repository_path = os.path.join(repositories_base_path, repository_name)
print('New commit found for repository ' + repository_name)
if os.path.exists(repository_path):
# git pull
print('update repository')
repo = Repo(repository_path)
repo.git.execute(["sudo", "git", "fetch", "--all"])
repo.git.execute(["sudo", "git", "reset", "--hard", "origin/master"])
repo.git.execute(["sudo", "git", "lfs", "pull"]) # force pull lfs files
print('successfuly updated repository')
else:
# git clone
print('clone repository')
url = proj.http_url_to_repo
repo = Repo.clone_from(url, repository_path)
repo.git.execute(["sudo", "git", "lfs", "pull"]) # force pull lfs files
print('successfuly cloned repository')
# add to list of repositories to process if clone/pull succeeds (only!)
listOfRepositories.append(proj.name)
listOfRepoIds[proj.name] = proj.id
except (GitlabAuthenticationError, GitlabConnectionError, GitlabHttpError) as e:
print('Error while updating repository ' + proj.name + ' (#' + str(proj.id) + ')')
post_issue(name='Gitlab error for repository ' + repository_name,
description='The integration script encountered an error (' + type(e).__name__ + ') while updating/cloning repositories. More info: \n' + str(e),
issue_type='Integration script execution')
except Exception as e:
print('Error while updating repository ' + proj.name + ' (#' + str(proj.id) + ')')
post_issue(name='Script error for repository ' + repository_name,
description='The integration script encountered an error (' + type(e).__name__ + ') while updating/cloning repositories. More info: \n' + str(e),
issue_type='Integration script execution')
try:
listOfRepositories.remove('HotmapsLAU')
listOfRepositories.remove('lau2')
listOfRepositories.remove('NUTS')
listOfRepositories.remove('.git')
except:
pass
for repository_name in listOfRepositories:
if repository_name == 'HotmapsLAU' or repository_name == 'lau2' or repository_name == 'NUTS':
continue
"""
VALIDATION
"""
log_print_step("Validation of " + repository_name)
# check that repository path is correct
repo_path = os.path.join(repositories_base_path, repository_name)
print(repo_path)
if not os.path.isdir(repo_path):
print('repo_path is not a directory')
msg = 'repository path is not a directory'
post_issue(name='Validation error ' + repository_name,
description='The repository validation was not successful.\n' + msg,
issue_type='Dataset Provider improvement needed')
continue
content = os.listdir('.')
# check that datapackage file is not missing
dp_file_path = os.path.join(repo_path, 'datapackage.json')
if not os.path.isfile(dp_file_path):
print('datapackage.json file missing or not in correct directory')
msg = 'datapackage.json file missing or not in correct directory'
post_issue(name='Validation error ' + repository_name,
description='The repository validation was not successful.\n' + msg,
issue_type='Dataset Provider improvement needed')
continue
# check that data directory is present
data_dir_path = os.path.join(repo_path, 'data')
if not os.path.isdir(data_dir_path):
print('data directory missing')
msg = 'data directory missing'
post_issue(name='Validation error ' + repository_name,
description='The repository validation was not successful.\n' + msg,
issue_type='Dataset Provider improvement needed')
continue
# check properties
missing_properties = []
error_messages = []
# open file
# check if file construction is valid
try:
with open(dp_file_path) as f:
dp = json.load(f)
except json.decoder.JSONDecodeError as e:
msg = 'JSON decoding raised an exception.\n' + str(e)
print(msg)
post_issue(name='Validation error ' + repository_name,
description='The repository validation was not successful.\n' + msg,
issue_type='Dataset Provider improvement needed')
continue
# create tags from contributors (data providers)
try:
contributors = dp['contributors']
tags = []
for c in contributors:
print(c['title'])
tags.append(c['title'])
except KeyError as e:
tags = []
# profile
try:
dp_profile = dp['profile']
except:
missing_properties.append('profile')
# resources
try:
dp_resources = dp['resources']
except:
missing_properties.append('resources')
dp_resources = None
# check resources attributes
has_geom = None # variable used to detect geometries in datapacakge
if dp_resources:
if dp_profile == 'vector-data-resource':
for dp_r in dp_resources:
print('vector-data-resource')
props = ['name', 'path', 'format', 'unit', 'vector']
for p in props:
try:
a = dp_r[p]
if p == 'name':
if len(a) > 50:
error_messages.append('resource/name length is too long (max 50 char.)')
if a.endswith(('.csv', '.tif', '.tiff', '.shp', '.geojson', '.txt')):
error_messages.append('resource/name should not contain a file extension (extension is in resource/path)')
except KeyError as e:
missing_properties.append('resources/' + p)
try:
dp_path = dp_r['path']
if not os.path.isfile(os.join(repo_path, dp_path)):
error_messages.append('attribute path does not link to an existing file')
except:
pass
try:
dp_vector = dp_r['vector']
dp_epsg = dp_vector['epsg']
except:
missing_properties.append('vector/epsg')
try:
dp_vector = dp_r['vector']
dp_geometry_type = dp_vector['geometry_type']
if dp_geometry_type.lower() == 'polygon':
dp_geometry_type = 'MultiPolygon'
elif dp_geometry_type.lower() == 'multipolygon':
dp_geometry_type = 'MultiPolygon'
elif dp_geometry_type.lower() == 'point':
dp_geometry_type = 'Point'
elif dp_geometry_type.lower() == 'multipoint':
dp_geometry_type = 'MultiPoint'
elif dp_geometry_type.lower() == 'multilinestring':
dp_geometry_type = 'MultiLinestring'
elif dp_geometry_type.lower() == 'linestring':
dp_geometry_type = 'Linestring'
else:
error_messages.append('geometry_type is not set correctly (must be either (multi)point, (multi)linestring or (multi)polygon)')
except:
missing_properties.append('vector/geometry_type')
try:
dp_schema = dp_vector['schema']
except:
missing_properties.append('vector/schema')
try:
dp_schema = dp_vector['schema']
if len(dp_schema) > 0:
for f in dp_schema:
f_name = f['name']
f_unit = f['unit']
f_type = f['type']
except:
error_messages.append('errors in schema definition (schema: [{name, unit, type},...])')
elif dp_profile == 'raster-data-resource':
print('raster-data-resource')
for dp_r in dp_resources:
props = ['name', 'path', 'unit', 'format', 'raster']
for p in props:
try:
a = dp_r[p]
if p == 'name':
if len(a) > 50:
error_messages.append('resource/name length is too long (max 50 char.)')
if a.endswith(('.csv', '.tif', '.tiff', '.shp', '.geojson', '.txt')):
error_messages.append('resource/name should not contain a file extension (extension is in resource/path)')
except KeyError as e:
missing_properties.append('resources/' + p)
try:
dp_path = dp_r['path']
if not os.path.exists(os.join(repo_path, dp_path)):
error_messages.append('attribute path does not link to an existing file')
except:
pass
try:
dp_raster = dp_r['raster']
dp_epsg = dp_raster['epsg']
except:
missing_properties.append('raster/epsg')
elif dp_profile == 'tabular-data-resource':
print('tabular-data-resource')
for dp_r in dp_resources:
props = ['name', 'path', 'schema', 'encoding', 'format', 'dialect']
for p in props:
try:
a = dp_r[p]
if p == 'name':
if len(a) > 50:
error_messages.append('resource/name length is too long (max 50 char.)')
if a.endswith(('.csv', '.tif', '.tiff', '.shp', '.geojson', '.txt')):
error_messages.append('resource/name should not contain a file extension (extension is in resource/path)')
except KeyError as e:
missing_properties.append('resources/' + p)
# fields
has_geom = False
f_col_names = []
try:
dp_schema = dp_r['schema']
if 'fields' in dp_schema:
dp_fields = dp_schema['fields']
if len(dp_fields) > 0:
for f in dp_fields:
f_name = f['name']
f_unit = f['unit']
f_type = f['type']
if f_type == 'geometry':
has_geom = True
f_col_names.append(f_name)
else:
missing_properties.append('fields')
except:
error_messages.append('errors in schema definition (schema: fields: [{name, unit, type},...])')
# geoms
if 'spatial_resolution' in dp_r and 'spatial_key_field' in dp_r:
if dp_r['spatial_key_field'] not in f_col_names:
error_messages.append('spatial_key_field does not refer to an existing field name')
else:
if not has_geom:
error_messages.append('no geometry provided (nuts/lau reference [attribute spatial_key_field and spatial_resolution] or geometry field)\n'
+ '\tThe dataset will be integrated as is but make sure that no geometry is needed.')
else:
err_msg = '\'profile\' contains an unsupported value! Use only vector-data-resource, raster-data-resource or tabular-data-resource'
print(err_msg)
error_messages.append(err_msg)
number_of_errors = len(error_messages) + len(missing_properties)
print("number of errors found: ", number_of_errors)
if number_of_errors > 0:
str_error_messages = ''
if len(error_messages) > 0:
str_error_messages = 'Errors: \n' + '\n'.join(error_messages)
if len(missing_properties) > 0:
str_error_messages = str_error_messages + '\n'
if len(missing_properties) > 0:
str_error_messages = 'Missing properties: \n' + '\n'.join(missing_properties)
print('Validation error for repository ' + repository_name + '\n' + str_error_messages)
post_issue(name='Validation error ' + repository_name,
description='The repository validation was not successful.\n' + str_error_messages,
issue_type='Dataset Provider improvement needed',
tags=tags)
if has_geom is not None and number_of_errors == 1 and has_geom is False:
pass # allow datasets without geometry
print('Resource integration continuing despite geom error.')
else:
print('Resource integration aborted.')
continue # otherwise skip dataset
else:
print('Validation OK')
log_print_step("Start integration of " + repository_name)
log_start_repo_time = log_previous_time
repository_path = os.path.join(repositories_base_path, repository_name)
try:
# read datapackage.json (dp)
print(repository_path)
dp = json.load(open(repository_path + '/datapackage.json'))
gis_data_type = dp['profile']
gis_resources = dp['resources']
dataset_version = dp['version']
table_name = re.sub('[^A-Za-z0-9]+', '_', dp['name'].lower().replace("hotmaps", ""))
print(dp)
for r in gis_resources:
log_print_step("Start resource")
format = r['format']
name = r['name']
if name == 'agricultural_residues' or name == 'livestock_effluents' or name == 'space_heating_cooling_dhw_top-down':
print(name, ' ... skipping ...')
continue
path = r['path']
table_name = re.sub('[^A-Za-z0-9]+', '_', name.lower().replace("hotmaps", ""))
print('table_name =', table_name)
# date = r['date']
raster_table_name = table_name
precomputed_table_name_lau = raster_table_name + "_" + LAU_TABLE_NAME
precomputed_table_name_nuts = raster_table_name + "_" + NUTS_TABLE_NAME
if gis_data_type == 'vector-data-resource':
vector = r['vector']
proj = vector['epsg']
geom_type = vector['geometry_type']
schema = vector['schema']
# retrieve start and end date
start_date = '1970-01-01 00:00:00'
end_date = '1970-01-01 00:00:00'
try:
temp = r['temporal']
start_date = temp['start']
end_date = temp['end']
except:
# keep default data
pass
attributes_names = []
attributes_types = []
for att in schema:
# ignore timestamp col because it's used for temporal
if att['name'].lower() == 'timestamp':
continue
col_type = att['type']
if col_type == 'string':
col_type = 'varchar(255)'
elif col_type == 'integer':
col_type = 'bigint'
elif col_type == 'double':
col_type = 'numeric(20,2)'
elif col_type == 'number':
col_type = 'numeric(20,2)'
elif col_type == 'float':
col_type = 'numeric(20,2)'
elif col_type == 'boolean':
col_type = 'boolean'
elif col_type == 'date':
col_type = 'date'
elif col_type == 'datetime':
col_type = 'timestamp'
elif col_type == 'timestamp':
col_type = 'timestamp'
else:
print('Unhandled table type', col_type)
post_issue(name='Integration warning - repository ' + repository_name,
description=col_type + ' column type not supported.\n',
issue_type='Dataset Provider improvement needed', tags=tags)
continue
attributes_names.append(att['name'])
attributes_types.append(col_type)
# create a copy of lists (one for db[including date] one for shapefile)
db_attributes_names = list(attributes_names)
db_attributes_types = list(attributes_types)
# add date columns from datapackage.json
db_attributes_names.append('date')
db_attributes_types.append('date')
# temporal resolution
temporal_resolution = ''
try:
tr = r['temporal_resolution']
except:
print('Missing attribute temporal_resolution in datapackage.json. Using year as default')
tr = 'year'
if tr.lower().startswith('year'):
temporal_resolution = 'year'
elif tr.lower().startswith('month'):
temporal_resolution = 'month'
elif tr.lower().startswith('day'):
temporal_resolution = 'day'
elif tr.lower().startswith('hour'):
temporal_resolution = 'hour'
elif tr.lower().startswith('minute'):
temporal_resolution = 'minute'
elif tr.lower().startswith('second'):
temporal_resolution = 'second'
elif tr.lower().startswith('quarter'):
temporal_resolution = 'quarter'
elif tr.lower().startswith('week'):
temporal_resolution = 'week'
if temporal_resolution is not None and len(temporal_resolution) > 0:
# add temporal relationship in table
constraints = "DO $$ BEGIN IF NOT EXISTS (" \
+ "SELECT 1 FROM pg_constraint WHERE conname = \'" + table_name + "_" + TIME_TABLE_NAME + "_id_fkey\') THEN " \
+ "ALTER TABLE " + GEO_SCHEMA + '.' + table_name + " " \
+ "ADD CONSTRAINT " + table_name + "_" + TIME_TABLE_NAME + "_id_fkey " \
+ "FOREIGN KEY (fk_" + TIME_TABLE_NAME + "_id) " \
+ "REFERENCES " + TIME_TABLE + "(id) " \
+ "MATCH SIMPLE ON UPDATE NO ACTION ON DELETE SET NULL; " \
+ "END IF; END; $$; "
db_attributes_names.append('timestamp')
db_attributes_types.append('timestamp')
db_attributes_names.append('fk_' + TIME_TABLE_NAME + '_id')
db_attributes_types.append('bigint')
# add geometry from datapackage.json
# convert Polygon type to MultiPolygon
if geom_type.lower() == 'polygon':
geom_type = 'MultiPolygon'
elif geom_type.lower() == 'multipolygon':
geom_type = 'MultiPolygon'
elif geom_type.lower() == 'point':
geom_type = 'Point'
elif geom_type.lower() == 'multipoint':
geom_type = 'MultiPoint'
elif geom_type.lower() == 'multilinestring':
geom_type = 'MultiLinestring'
elif geom_type.lower() == 'linestring':
geom_type = 'Linestring'
else:
print('geometry_type is not set correctly')
db_attributes_names.append('geom')
db_attributes_types.append('geometry(' + geom_type + ', ' + proj + ')')
# drop table
db.drop_table(table_name=GEO_SCHEMA + '.' + table_name, cascade=True)
# create table if not exists
db.create_table(table_name=GEO_SCHEMA + '.' + table_name, col_names=db_attributes_names,
col_types=db_attributes_types, id_col_name='gid', constraints_str=constraints)
log_print_step("Start shapefile importation")
# import shapefile
import_shapefile(os.path.join(repository_path, path), start_date, temporal_resolution, attributes_names) # (base_path, 'git-repos', repository_name, path))
log_print_step("Start geoserver integration")
# add to geoserver
workspace = GEO_workspace
store = GEO_db_store
layer_name = table_name
# remove previous layer from geoserver
# remove layer
response = requests.delete(
GEO_url + ':' + GEO_port + '/geoserver/rest/layers/' + layer_name,
auth=(GEO_user, GEO_password),
)
print(response, response.content)
# remove feature type
response = requests.delete(
GEO_url + ':' + GEO_port + '/geoserver/rest/workspaces/' + workspace + '/datastores/' + store + '/featuretypes/' + layer_name,
auth=(GEO_user, GEO_password),
)
print(response, response.content)
# create layer
headers = {
'Content-type': 'text/xml',
}
data = '<featureType>' \
+ '<name>' + layer_name + '</name>' \
+ '<title>' + layer_name + '</title>' \
+ '<srs>EPSG:' + proj + '</srs>' \
+ '</featureType>'
response = requests.post(
GEO_url + ':' + GEO_port + '/geoserver/rest/workspaces/' + workspace + '/datastores/' + store + '/featuretypes/',
headers=headers,
data=data,
auth=(GEO_user, GEO_password),
)
print(data)
print(response, response.content)
elif gis_data_type == 'raster-data-resource':
raster = r['raster']
proj = raster['epsg']
# retrieve start and end date
start_date = '1970-01-01 00:00:00'
end_date = '1970-01-01 00:00:00'
try:
temp = r['temporal']
start_date = temp['start']
end_date = temp['end']
except:
# keep default data
start_date = '1970-01-01 00:00:00'
end_date = '1970-01-01 00:00:00'
pass
# temporal resolution
temporal_resolution = ''
try:
tr = r['temporal_resolution']
except:
print('Missing attribute temporal_resolution in datapackage.json. Using year as default')
tr = 'year'
if tr.lower().startswith('year'):
temporal_resolution = 'year'
elif tr.lower().startswith('month'):
temporal_resolution = 'month'
elif tr.lower().startswith('day'):
temporal_resolution = 'day'
elif tr.lower().startswith('hour'):
temporal_resolution = 'hour'
elif tr.lower().startswith('minute'):
temporal_resolution = 'minute'
elif tr.lower().startswith('second'):
temporal_resolution = 'second'
elif tr.lower().startswith('quarter'):
temporal_resolution = 'quarter'
elif tr.lower().startswith('week'):
temporal_resolution = 'week'
# number_of_bands = raster['number_of_bands']
# band0 = raster['band0']
raster_path = os.path.join(repository_path, path) # (base_path, 'git-repos', repository_name, path)
os.environ['PGHOST'] = DB_host
os.environ['PGPORT'] = DB_port
os.environ['PGUSER'] = DB_user
os.environ['PGPASSWORD'] = DB_password
os.environ['PGDATABASE'] = DB_database
rast_tbl = GEO_SCHEMA + '.' + raster_table_name
log_print_step("Start raster integration in database")
#cmds = 'cd ' + repository_path + '/data ; raster2pgsql -d -s ' + proj + ' -t "auto" -I -C -Y "' + name + '" ' + rast_tbl + ' | psql'
db.drop_table(table_name=rast_tbl, notices=verbose, cascade=True)
# create table
cmds = 'sudo raster2pgsql -p -s ' + proj + ' -t "auto" -I -C -Y "' + raster_path + '" ' + rast_tbl + ' | psql'
subprocess.call(cmds, shell=True)
# customize autovacuum settings
#db.query(commit=True, notices=verbose, query='ALTER TABLE ' + rast_tbl + ' SET (autovacuum_vacuum_scale_factor = 0.0); ALTER TABLE ' + rast_tbl + ' SET (autovacuum_vacuum_threshold = 5000); ALTER TABLE ' + rast_tbl + ' SET (autovacuum_analyze_scale_factor = 0.0); ALTER TABLE ' + rast_tbl + ' SET (autovacuum_analyze_threshold = 5000);')
#db.query(commit=True, notices=verbose, query='ALTER TABLE ' + rast_tbl + ' SET (autovacuum_enabled = false, toast.autovacuum_enabled = false);')
# add time column
constraints = "ALTER TABLE " + rast_tbl + " " \
+ "ADD COLUMN IF NOT EXISTS fk_" + TIME_TABLE_NAME + "_id bigint; "
constraints = constraints + "DO $$ BEGIN IF NOT EXISTS (" \
+ "SELECT 1 FROM pg_constraint WHERE conname = \'" + raster_table_name + "_" + TIME_TABLE_NAME + "_id_fkey\') THEN " \
+ "ALTER TABLE " + rast_tbl + " " \
+ "ADD CONSTRAINT " + raster_table_name + "_" + TIME_TABLE_NAME + "_id_fkey " \
+ "FOREIGN KEY (fk_" + TIME_TABLE_NAME + "_id) " \
+ "REFERENCES " + TIME_TABLE + "(id) " \
+ "MATCH SIMPLE ON UPDATE NO ACTION ON DELETE SET NULL; " \
+ "END IF; END; $$; "
db.query(commit=True, notices=verbose, query=constraints)
# insert data
cmds = 'sudo raster2pgsql -a -s ' + proj + ' -t "auto" -I -C -Y -e "' + raster_path + '" ' + rast_tbl + ' | psql'
print(cmds)
subprocess.call(cmds, shell=True)
# add time relationship in raster table
#constraints = "ALTER TABLE " + rast_tbl + " " \
# + "ADD COLUMN IF NOT EXISTS fk_" + TIME_TABLE_NAME + "_id bigint; "
#constraints = constraints + "DO $$ BEGIN IF NOT EXISTS (" \
# + "SELECT 1 FROM pg_constraint WHERE conname = \'" + raster_table_name + "_" + TIME_TABLE_NAME + "_id_fkey\') THEN " \
# + "ALTER TABLE " + rast_tbl + " " \
# + "ADD CONSTRAINT " + raster_table_name + "_" + TIME_TABLE_NAME + "_id_fkey " \
# + "FOREIGN KEY (fk_" + TIME_TABLE_NAME + "_id) " \
# + "REFERENCES " + TIME_TABLE + "(id) " \
# + "MATCH SIMPLE ON UPDATE NO ACTION ON DELETE SET NULL; " \
# + "END IF; END; $$; "
fk_time_id = get_or_create_time_id(timestamp=start_date, granularity=temporal_resolution)
print('fk_time_id=', fk_time_id)
query = "UPDATE " + rast_tbl + " AS r " \
+ "SET fk_" + TIME_TABLE_NAME + "_id = " + str(fk_time_id) + " " \
+ "WHERE fk_" + TIME_TABLE_NAME + "_id IS NULL;"
db.query(commit=True, notices=verbose, query=query)
# Precompute layers for nuts and lau
# LAU
log_print_step("Precompute LAU")
vect_tbl = LAU_TABLE
vect_tbl_name = LAU_TABLE_NAME
prec_tbl = STAT_SCHEMA + '.' + precomputed_table_name_lau
prec_tbl_name = precomputed_table_name_lau
db.drop_table(table_name=prec_tbl, notices=verbose, cascade=True)
attributes_names = (
'count', 'sum', 'mean', 'stddev', 'min', 'max',
'comm_id',
'fk_' + TIME_TABLE_NAME + '_id', 'fk_' + vect_tbl_name + '_gid')
attributes_types = (
'bigint', 'numeric(20,2)', 'numeric(20,2)', 'numeric(20,2)', 'numeric(20,2)', 'numeric(20,2)',
'varchar(255)',
'bigint', 'bigint')
constraints = "ALTER TABLE " + prec_tbl + " " \
+ "ADD CONSTRAINT " + prec_tbl_name + "fkey_" + vect_tbl_name + "_gid_fkey " \
+ "FOREIGN KEY (fk_" + vect_tbl_name + "_gid) " \
+ "REFERENCES " + vect_tbl + "(gid) " \
+ "MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION; "
constraints = constraints + "ALTER TABLE " + prec_tbl + " " \
+ "ADD CONSTRAINT " + prec_tbl_name + "_" + TIME_TABLE_NAME + "_id_fkey " \
+ "FOREIGN KEY (fk_" + TIME_TABLE_NAME + "_id) " \
+ "REFERENCES " + TIME_TABLE + "(id) " \
+ "MATCH SIMPLE ON UPDATE NO ACTION ON DELETE SET NULL "
db.create_table(table_name=prec_tbl,
col_names=attributes_names,
col_types=attributes_types,
constraints_str=constraints,
notices=verbose)
query = """
SELECT (
SELECT (ST_SummaryStatsAgg(ST_Clip(rast, 1, ST_Transform({vect_tbl}.geom, {RASTER_SRID}), true), 1, true))
FROM (
SELECT ST_Union(rast) as rast
FROM (
SELECT rast
FROM {rast_tbl}
WHERE ST_Intersects(
{rast_tbl}.rast, ST_Transform({vect_tbl}.geom, {RASTER_SRID})
)
AND fk_{TIME_TABLE_NAME}_id = {fk_time_id}
) as rast
) as rast
).*, {vect_tbl}.comm_id, {fk_time_id} AS fk_{TIME_TABLE_NAME}_id, {vect_tbl}.gid
FROM public.lau
""".format(
vect_tbl=vect_tbl,
rast_tbl=rast_tbl,
RASTER_SRID=str(RASTER_SRID),
TIME_TABLE_NAME=TIME_TABLE_NAME,
fk_time_id=str(fk_time_id)
)
db.query(commit=True, notices=verbose, query='INSERT INTO ' + prec_tbl
+ ' (' + ', '.join(
map(db_helper.str_with_quotes, [x.lower() for x in attributes_names])) + ') '
+ query + ' ;')
# NUTS
log_print_step("Precompute NUTS 3")
prec_lau_tbl = prec_tbl