/
ion_loader.py
executable file
·2020 lines (1722 loc) · 92.6 KB
/
ion_loader.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
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
#!/usr/bin/env python
"""Process that loads ION resources via service calls based on definitions in spreadsheets using loader functions.
@see https://confluence.oceanobservatories.org/display/CIDev/R2+System+Preload
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=load path=master scenario=R2_DEMO
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=load path=res/preload/r2_ioc/R2PreloadedResources.xlsx scenario=R2_DEMO
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=load path="https://docs.google.com/spreadsheet/pub?key=0AttCeOvLP6XMdG82NHZfSEJJOGdQTkgzb05aRjkzMEE&output=xls" scenario=R2_DEMO
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=load path=res/preload/r2_ioc scenario=R2_DEMO
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=loadui path=res/preload/r2_ioc
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=loadui path=https://userexperience.oceanobservatories.org/database-exports/
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=load path=master assets=res/preload/r2_ioc/ooi_assets scenario=R2_DEMO loadooi=True
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=load path=res/preload/r2_ioc scenario=R2_DEMO loadooi=True assets=res/preload/r2_ioc/ooi_assets
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=load path=res/preload/r2_ioc scenario=R2_DEMO loadui=True
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=parseooi assets=res/preload/r2_ioc/ooi_assets
bin/pycc -x ion.processes.bootstrap.ion_loader.IONLoader op=deleteooi
ui_path= override location to get UI preload files (default is path + '/ui_assets')
assets= override location to get OOI asset file (default is path + '/ooi_assets')
attachments= override location to get file attachments (default is path)
ooifilter= one or comma separated list of CE,CP,GA,GI,GP,GS,ES to limit ooi resource import
ooiexclude= one or more categories to NOT import in the OOI import
bulk= if True, uses RR bulk insert operations to load, not service calls
TODO: constraints defined in multiple tables as list of IDs, but not used
TODO: support attachments using HTTP URL
TODO: Owner, Events with bulk
Note: For quick debugging without restarting the services container:
- Once after starting r2deploy:
bin/pycc -x ion.processes.bootstrap.datastore_loader.DatastoreLoader op=dump path=res/preload/local/my_dump
- Before each test of the ion_loader:
bin/pycc -fc -x ion.processes.bootstrap.datastore_loader.DatastoreLoader op=load path=res/preload/local/my_dump
"""
__author__ = 'Michael Meisinger, Ian Katz, Thomas Lennan'
import ast
import calendar
import csv
import numpy as np
import re
import requests
import time
from pyon.core.bootstrap import get_service_registry
from pyon.core.exception import NotFound
from pyon.datastore.datastore import DatastoreManager
from pyon.ion.identifier import create_unique_resource_id, create_unique_association_id
from pyon.ion.resource import get_restype_lcsm
from pyon.public import log, ImmediateProcess, iex, IonObject, RT, PRED, OT
from pyon.util.containers import get_ion_ts, named_any
from ion.core.ooiref import OOIReferenceDesignator
from ion.processes.bootstrap.ooi_loader import OOILoader
from ion.processes.bootstrap.ui_loader import UILoader
from ion.services.dm.utility.granule_utils import time_series_domain
from ion.agents.port.port_agent_process import PortAgentProcessType, PortAgentType
from ion.util.parameter_loader import ParameterPlugin
from ion.util.xlsparser import XLSParser
from coverage_model.parameter import ParameterContext
from coverage_model.parameter_types import QuantityType, ArrayType, RecordType
from coverage_model.basic_types import AxisTypeEnum
from ion.util.parameter_loader import ParameterPlugin
from ion.agents.platform.oms.oms_client_factory import OmsClientFactory
from interface import objects
import logging
DEFAULT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
### this master URL has the latest changes, but if columns have changed, it may no longer work with this commit of the loader code
MASTER_DOC = "https://docs.google.com/spreadsheet/pub?key=0AttCeOvLP6XMdG82NHZfSEJJOGdQTkgzb05aRjkzMEE&output=xls"
### the URL below should point to a COPY of the master google spreadsheet that works with this version of the loader
TESTED_DOC = "https://docs.google.com/spreadsheet/pub?key=0AgkUKqO5m-ZidE01OXVvMnhraVZtM05rNkthQnVjU1E&output=xls"
#
### while working on changes to the google doc, use this to run test_loader.py against the master spreadsheet
TESTED_DOC=MASTER_DOC
# The preload spreadsheets (tabs) in the order they should be loaded
DEFAULT_CATEGORIES = [
'Constraint',
'Contact',
'User',
'Org',
'UserRole',
'CoordinateSystem',
'ParameterDefs',
'ParameterDictionary',
'StreamConfiguration',
'SensorModel',
'PlatformModel',
'InstrumentModel',
'Observatory',
'Subsite',
'PlatformSite',
'InstrumentSite',
'StreamDefinition',
'PlatformDevice',
'PlatformAgent',
'PlatformAgentInstance',
'InstrumentDevice',
'SensorDevice',
'InstrumentAgent',
'InstrumentAgentInstance',
'DataProduct',
'DataProcessDefinition',
'DataProcess',
'EventProcessDefinition',
'EventProcess',
'DataProductLink',
'Attachment',
'WorkflowDefinition',
'Workflow',
'Deployment',
]
class IONLoader(ImmediateProcess):
COL_SCENARIO = "Scenario"
COL_ID = "ID"
COL_OWNER = "owner_id"
COL_LCSTATE = "lcstate"
COL_ORGS = "org_ids"
ID_ORG_ION = "ORG_ION"
ID_SYSTEM_ACTOR = "USER_SYSTEM"
def on_start(self):
# Main operation to perform
op = self.CFG.get("op", None)
# Additional parameters
self.path = self.CFG.get("path", TESTED_DOC)
if self.path=='master':
self.path = MASTER_DOC
self.attachment_path = self.CFG.get("attachments", self.path + '/attachments')
self.asset_path = self.CFG.get("assets", self.path + "/ooi_assets")
default_ui_path = self.path if self.path.startswith('http') else self.path + "/ui_assets"
self.ui_path = self.CFG.get("ui_path", default_ui_path)
scenarios = self.CFG.get("scenario", None)
category_csv = self.CFG.get("categories", None)
self.categories = category_csv.split(",") if category_csv else DEFAULT_CATEGORIES
self.debug = self.CFG.get("debug", False) # Debug mode with certain shorthands
self.loadooi = self.CFG.get("loadooi", False) # Import OOI asset data
self.loadui = self.CFG.get("loadui", False) # Import UI asset data
self.exportui = self.CFG.get("exportui", False) # Save UI JSON file
self.update = self.CFG.get("update", False) # Support update to existing resources
self.bulk = self.CFG.get("bulk", False) # Use bulk insert where available
self.ooifilter = self.CFG.get("ooifilter", None) # Filter OOI import to RD prefixes (e.g. array "CE,GP")
self.ooiexclude = self.CFG.get("ooiexclude", '') # Don't import the listed categories
if self.ooiexclude:
self.ooiexclude = self.ooiexclude.split(',')
# External loader tools
self.ui_loader = UILoader(self)
self.ooi_loader = OOILoader(self, asset_path=self.asset_path)
self.resource_ds = DatastoreManager.get_datastore_instance("resources")
# Initialize variables used during subsequent load
self.obj_classes = {} # Cache of class for object types
self.resource_ids = {} # Holds a mapping of preload IDs to internal resource ids
self.resource_objs = {} # Holds a mapping of preload IDs to the actual resource objects
self.existing_resources = None
self.unknown_fields = {} # track unknown fields so we only warn once
self.constraint_defs = {} # alias -> value for refs, since not stored in DB
self.contact_defs = {} # alias -> value for refs, since not stored in DB
self.stream_config = {} # name -> obj for StreamConfiguration objects, used by *AgentInstance
# Loads internal bootstrapped resource ids that will be referenced during preload
self._load_system_ids()
log.info("IONLoader: {op=%s, path=%s, scenario=%s}" % (op, self.path, scenarios))
if not op:
raise iex.BadRequest("No operation specified")
# Perform operations
if op == "load":
if not scenarios:
raise iex.BadRequest("Must provide scenarios to load: scenario=sc1,sc2,...")
if self.loadooi:
self.ooi_loader.extract_ooi_assets()
if self.loadui:
specs_path = 'interface/ui_specs.json' if self.exportui else None
self.ui_loader.load_ui(self.ui_path, specs_path=specs_path)
# Load existing resources by preload ID
self._prepare_incremental()
scenarios = scenarios.split(',')
self.load_ion(scenarios)
elif op == "parseooi":
self.ooi_loader.extract_ooi_assets()
elif op == "loadui":
specs_path = 'interface/ui_specs.json' if self.exportui else None
self.ui_loader.load_ui(self.ui_path, specs_path=specs_path)
elif op == "deleteooi":
self.delete_ooi_assets()
elif op == "deleteui":
self.ui_loader.delete_ui()
else:
raise iex.BadRequest("Operation unknown")
def on_quit(self):
pass
def load_ion(self, scenarios):
"""
Loads resources for one scenario, by parsing input spreadsheets for all resource categories
in defined order, executing service calls for all entries in the scenario.
Can load the spreadsheets from http or file location.
Optionally imports OOI assets at the beginning of each category.
"""
log.info("Loading scenario from path: %s", self.path)
if self.bulk:
log.warn("WARNING: Bulk load is ENABLED. Making bulk RR calls to create resources/associations. No policy checks!")
# Fetch the spreadsheet directly from a URL (from a GoogleDocs published spreadsheet)
if self.path.startswith('http'):
preload_doc_str = requests.get(self.path).content
log.debug("Fetched URL contents, size=%s", len(preload_doc_str))
xls_parser = XLSParser()
self.csv_files = xls_parser.extract_csvs(preload_doc_str)
elif self.path.endswith(".xlsx"):
with open(self.path, "rb") as f:
preload_doc_str = f.read()
log.debug("Loaded xlsx file, size=%s", len(preload_doc_str))
xls_parser = XLSParser()
self.csv_files = xls_parser.extract_csvs(preload_doc_str)
else:
self.csv_files = None
for category in self.categories:
row_do, row_skip, num_bulk = 0, 0, 0
self.bulk_objects = {} # This keeps objects to be bulk inserted/updated at the end of a category
# First load all OOI assets for this category
if self.loadooi and category not in self.ooiexclude:
catfunc_ooi = getattr(self, "_load_%s_OOI" % category, None)
if catfunc_ooi:
log.debug('Loading OOI assets for %s', category)
catfunc_ooi()
# Now load entries from preload spreadsheet top to bottom where scenario matches
catfunc = getattr(self, "_load_%s" % category)
filename = "%s/%s.csv" % (self.path, category)
log.debug("Loading category %s", category)
try:
csvfile = None
if self.csv_files is not None:
csv_doc = self.csv_files[category]
# This is a hack to be able to read from string
csv_doc = csv_doc.splitlines()
reader = csv.DictReader(csv_doc, delimiter=',')
else:
csvfile = open(filename, "rb")
reader = csv.DictReader(csvfile, delimiter=',')
for row in reader:
# Check if scenario applies
if row[self.COL_SCENARIO] not in scenarios:
row_skip += 1
continue
row_do += 1
log.debug('handling %s row: %r', category, row)
try:
catfunc(row)
except:
log.error('error loading %s row: %r', category, row, exc_info=True)
raise
if self.bulk:
num_bulk = self._finalize_bulk(category)
# Update resource and associations views
self.container.resource_registry.find_resources(restype="X", id_only=True)
self.container.resource_registry.find_associations(predicate="X", id_only=True)
except IOError, ioe:
log.warn("Resource category file %s error: %s" % (filename, str(ioe)), exc_info=True)
finally:
if csvfile is not None:
csvfile.close()
csvfile = None
log.info("Loaded category %s: %d resources from scenario rows, %s bulk, %d rows skipped" % (category, row_do, num_bulk, row_skip))
def _load_system_ids(self):
"""Read some system objects for later reference"""
org_objs,_ = self.container.resource_registry.find_resources(name="ION", restype=RT.Org, id_only=False)
if not org_objs:
raise iex.BadRequest("ION org not found. Was system force_cleaned since bootstrap?")
ion_org_id = org_objs[0]._id
self._register_id(self.ID_ORG_ION, ion_org_id, org_objs[0])
system_actor, _ = self.container.resource_registry.find_resources(
RT.ActorIdentity, name=self.CFG.system.system_actor, id_only=False)
system_actor_id = system_actor[0]._id if system_actor else 'anonymous'
self._register_id(self.ID_SYSTEM_ACTOR, system_actor_id, system_actor[0] if system_actor else None)
def _prepare_incremental(self):
"""
Look in the resource registry for any resources that have a preload ID on them so that
they can be referenced under this preload ID during this load run.
"""
log.debug("Preparing for incremental preload. Loading prior preloaded resources for reference")
res_objs, res_keys = self.container.resource_registry.find_resources_ext(alt_id_ns="PRE", id_only=False)
res_preload_ids = [key['alt_id'] for key in res_keys]
res_ids = [obj._id for obj in res_objs]
log.debug("Found %s previously preloaded resources", len(res_objs))
self.existing_resources = dict(zip(res_preload_ids, res_objs))
if len(self.existing_resources) != len(res_objs):
raise iex.BadRequest("Stored preload IDs are NOT UNIQUE!!! Cannot link to old resources")
res_id_mapping = dict(zip(res_preload_ids, res_ids))
self.resource_ids.update(res_id_mapping)
res_obj_mapping = dict(zip(res_preload_ids, res_objs))
self.resource_objs.update(res_obj_mapping)
def _finalize_bulk(self, category):
res = self.resource_ds.create_mult(self.bulk_objects.values(), allow_ids=True)
log.debug("Bulk stored %d resource objects/associations into resource registry", len(res))
num_objects = len([1 for obj in self.bulk_objects.values() if obj._get_type() != "Association"])
self.bulk_objects.clear()
return num_objects
def _create_object_from_row(self, objtype, row, prefix='',
constraints=None, constraint_field='constraint_list',
contacts=None, contact_field='contacts',
existing_obj=None):
"""
Construct an IONObject of a determined type from given row dict with attributes.
Convert all attributes according to their schema target type. Supports nested objects.
Supports edit of objects of same type.
"""
log.trace("Create object type=%s, prefix=%s", objtype, prefix)
schema = self._get_object_class(objtype)._schema
obj_fields = {}
exclude_prefix = set()
for col,value in row.iteritems():
if col.startswith(prefix):
fieldname = col[len(prefix):]
if '/' in fieldname:
slidx = fieldname.find('/')
nested_obj_field = fieldname[:slidx]
if not nested_obj_field in exclude_prefix:
nested_obj_type = schema[nested_obj_field]['type']
nested_prefix = prefix + fieldname[:slidx+1]
log.trace("Get nested object field=%s type=%s, prefix=%s", nested_obj_field, nested_obj_type, nested_prefix)
nested_obj = self._create_object_from_row(nested_obj_type, row, nested_prefix)
obj_fields[nested_obj_field] = nested_obj
exclude_prefix.add(nested_obj_field)
elif fieldname in schema:
try:
if value:
fieldvalue = self._get_typed_value(value, schema[fieldname])
obj_fields[fieldname] = fieldvalue
except Exception:
log.warn("Object type=%s, prefix=%s, field=%s cannot be converted to type=%s. Value=%s",
objtype, prefix, fieldname, schema[fieldname]['type'], value, exc_info=True)
#fieldvalue = str(fieldvalue)
else:
# warn about unknown fields just once -- not on each row
if objtype not in self.unknown_fields:
self.unknown_fields[objtype] = []
if fieldname not in self.unknown_fields[objtype]:
log.warn("Skipping unknown field in %s: %s%s", objtype, prefix, fieldname)
self.unknown_fields[objtype].append(fieldname)
if constraints:
obj_fields[constraint_field] = constraints
if contacts:
obj_fields[contact_field] = contacts
if existing_obj:
# Edit attributes
if existing_obj._get_type() != objtype:
raise iex.Inconsistent("Cannot edit resource. Type mismatch old=%s, new=%s" % (existing_obj._get_type(), objtype))
# TODO: Don't edit empty nested attributes
for attr in list(obj_fields.keys()):
if not obj_fields[attr]:
del obj_fields[attr]
for attr in ('alt_ids','_id','_rev','type_'):
if attr in obj_fields:
del obj_fields[attr]
existing_obj.__dict__.update(obj_fields)
log.trace("Update object type %s using field names %s", objtype, obj_fields.keys())
obj = existing_obj
else:
if self.COL_ID in row and row[self.COL_ID] and 'alt_ids' in schema:
if 'alt_ids' in obj_fields:
obj_fields['alt_ids'].append("PRE:"+row[self.COL_ID])
else:
obj_fields['alt_ids'] = ["PRE:"+row[self.COL_ID]]
log.trace("Create object type %s from field names %s", objtype, obj_fields.keys())
obj = IonObject(objtype, **obj_fields)
return obj
def _get_object_class(self, objtype):
if objtype in self.obj_classes:
return self.obj_classes[objtype]
try:
obj_class = named_any("interface.objects.%s" % objtype)
self.obj_classes[objtype] = obj_class
return obj_class
except:
log.error('failed to find class for type %s' % objtype)
def _get_typed_value(self, value, schema_entry=None, targettype=None):
"""
Performs a value type conversion according to a schema specified target type.
"""
targettype = targettype or schema_entry["type"]
if schema_entry and 'enum_type' in schema_entry:
enum_clzz = getattr(objects, schema_entry['enum_type'])
return enum_clzz._value_map[value]
elif targettype is 'str':
return str(value)
elif targettype is 'bool':
lvalue = value.lower()
if lvalue == 'true' or lvalue == '1':
return True
elif lvalue == 'false' or lvalue == '' or lvalue == '0':
return False
else:
raise iex.BadRequest("Value %s is no bool" % value)
elif targettype is 'int':
try:
return int(value)
except Exception:
log.warn("Value %s is type %s not type %s" % (value, type(value), targettype))
return ast.literal_eval(value)
elif targettype is 'float':
try:
return float(value)
except Exception:
log.warn("Value %s is type %s not type %s" % (value, type(value), targettype))
return ast.literal_eval(value)
elif targettype is 'simplelist':
if value.startswith('[') and value.endswith(']'):
value = value[1:len(value)-1].strip()
return list(value.split(','))
else:
log.trace('parsing value as %s: %s', targettype, value)
return ast.literal_eval(value)
def _get_service_client(self, service):
return get_service_registry().services[service].client(process=self)
def _register_id(self, alias, resid, res_obj=None):
if alias in self.resource_ids:
raise iex.BadRequest("ID alias %s used twice" % alias)
self.resource_ids[alias] = resid
self.resource_objs[alias] = res_obj
log.trace("Added resource alias=%s to id=%s", alias, resid)
def _get_resource_obj(self, res_id):
"""Returns a resource object from one of the memory locations for given preload or internal ID"""
if self.bulk and res_id in self.bulk_objects:
return self.bulk_objects[res_id]
elif res_id in self.resource_objs:
return self.resource_objs[res_id]
else:
# Real ID not alias - reverse lookup
alias_ids = [alias_id for alias_id,int_id in self.resource_ids.iteritems() if int_id==res_id]
if alias_ids:
return self.resource_objs[alias_ids[0]]
return None
def _get_alt_id(self, res_obj, prefix):
alt_ids = getattr(res_obj, 'alt_ids', [])
for alt_id in alt_ids:
if alt_id.startswith(prefix+":"):
alt_id_str = alt_id[len(prefix)+1:]
return alt_id_str
def _get_op_headers(self, row, force_user=False):
headers = {}
owner_id = row.get(self.COL_OWNER, None)
if owner_id:
owner_id = self.resource_ids[owner_id]
headers['ion-actor-id'] = owner_id
headers['ion-actor-roles'] = {'ION': ['ION_MANAGER', 'ORG_MANAGER']}
headers['expiry'] = '0'
elif force_user:
return self._get_system_actor_headers()
return headers
def _basic_resource_create(self, row, restype, prefix, svcname, svcop,
constraints=None, constraint_field='constraint_list',
contacts=None, contact_field='contacts',
set_attributes=None, support_bulk=False,
**kwargs):
"""
Orchestration method doing the following:
- create an object from a row,
- add any defined constraints,
- make a service call to create resource for given object,
- share resource in a given Org
- store newly created resource id and obj for future reference
- (optional) support bulk create/update
"""
res_id_alias = row[self.COL_ID]
existing_obj = None
if res_id_alias in self.resource_ids:
# TODO: Catch case when ID used twice
existing_obj = self.resource_objs[res_id_alias]
res_obj = self._create_object_from_row(restype, row, prefix,
constraints=constraints, constraint_field=constraint_field,
contacts=contacts, contact_field=contact_field,
existing_obj=existing_obj)
if set_attributes:
for attr, attr_val in set_attributes.iteritems():
setattr(res_obj, attr, attr_val)
if existing_obj:
res_id = self.resource_ids[res_id_alias]
if self.bulk and support_bulk:
self.bulk_objects[res_id] = res_obj
else:
# TODO: Use the appropriate service call here
self.container.resource_registry.update(res_obj)
else:
if self.bulk and support_bulk:
res_id = self._create_bulk_resource(res_obj, res_id_alias)
headers = self._get_op_headers(row)
self._resource_assign_owner(headers, res_obj)
else:
svc_client = self._get_service_client(svcname)
headers = self._get_op_headers(row, force_user=True)
res_id = getattr(svc_client, svcop)(res_obj, headers=headers, **kwargs)
if res_id:
res_obj._id = res_id
self._register_id(res_id_alias, res_id, res_obj)
self._resource_assign_org(row, res_id)
return res_id
def _create_bulk_resource(self, res_obj, res_alias=None):
if not hasattr(res_obj, "_id"):
res_obj._id = create_unique_resource_id()
ts = get_ion_ts()
if hasattr(res_obj, "ts_created") and not res_obj.ts_created:
res_obj.ts_created = ts
if hasattr(res_obj, "ts_updated") and not res_obj.ts_updated:
res_obj.ts_updated = ts
res_id = res_obj._id
self.bulk_objects[res_id] = res_obj
if res_alias:
self._register_id(res_alias, res_id, res_obj)
return res_id
def _resource_advance_lcs(self, row, res_id, restype=None):
"""
Change lifecycle state of object to requested state. Supports bulk.
"""
lcsm = get_restype_lcsm(restype)
initial_lcstate = lcsm.initial_state if lcsm else "DEPLOYED_AVAILABLE"
lcstate = row.get(self.COL_LCSTATE, None)
if lcstate:
if self.bulk and res_id in self.bulk_objects:
self.bulk_objects[res_id].lcstate = lcstate
else:
imat, ivis = initial_lcstate.split("_")
mat, vis = lcstate.split("_")
if mat != imat:
self.container.resource_registry.set_lifecycle_state(res_id, "%s_PRIVATE" % mat)
if vis != ivis:
self.container.resource_registry.set_lifecycle_state(res_id, "%s_%s" % (mat, vis))
def _resource_assign_org(self, row, res_id):
"""
Shares the resource in the given orgs. Supports bulk.
"""
org_ids = row.get(self.COL_ORGS, None)
if org_ids:
org_ids = self._get_typed_value(org_ids, targettype="simplelist")
for org_id in org_ids:
org_res_id = self.resource_ids[org_id]
if self.bulk and res_id in self.bulk_objects:
# Note: org_id is alias, res_id is internal ID
org_obj = self._get_resource_obj(org_id)
res_obj = self._get_resource_obj(res_id)
# Create association to given Org
# Simulate OMS.assign_resource_to_observatory_org -> Org MS.share_resource
assoc_obj = self._create_association(org_obj, PRED.hasResource, res_obj)
else:
svc_client = self._get_service_client("observatory_management")
svc_client.assign_resource_to_observatory_org(res_id, self.resource_ids[org_id], headers=self._get_system_actor_headers())
def _resource_assign_owner(self, headers, res_obj):
if self.bulk and 'ion-actor-id' in headers:
owner_id = headers['ion-actor-id']
user_obj = self._get_resource_obj(owner_id)
if owner_id and owner_id != 'anonymous':
self._create_association(res_obj, PRED.hasOwner, user_obj)
def _get_contacts(self, row, field='contact_ids', type=None):
return self._get_members(self.contact_defs, row, field, type, 'contact')
def _get_constraints(self, row, field='constraint_ids', type=None):
return self._get_members(self.constraint_defs, row, field, type, 'constraint')
def _get_members(self, value_map, row, field, obj_type, member_type):
values = []
value = row[field]
if value:
names = self._get_typed_value(value, targettype="simplelist")
if names:
for name in names:
if name not in value_map:
msg = 'invalid ' + member_type + ': ' + name + ' (from value=' + value + ')'
if self.COL_ID in row:
msg = 'id ' + row[self.COL_ID] + ' refers to an ' + msg
if obj_type:
msg = obj_type + ' ' + msg
raise iex.BadRequest(msg)
value = value_map[name]
values.append(value)
return values
def _create_association(self, subject=None, predicate=None, obj=None):
"""
Create an association between two IonObjects with a given predicate.
Supports bulk mode
"""
if self.bulk:
if not subject or not predicate or not obj:
raise iex.BadRequest("Association must have all elements set: %s/%s/%s" % (subject, predicate, obj))
if "_id" not in subject:
raise iex.BadRequest("Subject id not available")
subject_id = subject._id
st = subject._get_type()
if "_id" not in obj:
raise iex.BadRequest("Object id not available")
object_id = obj._id
ot = obj._get_type()
assoc_id = create_unique_association_id()
assoc_obj = IonObject("Association",
s=subject_id, st=st,
p=predicate,
o=object_id, ot=ot,
ts=get_ion_ts())
assoc_obj._id = assoc_id
self.bulk_objects[assoc_id] = assoc_obj
return assoc_id, '1-norev'
else:
return self.container.resource_registry.create_association(subject, predicate, obj)
# --------------------------------------------------------------------------------------------------
# Add specific types of resources below
def _load_Contact(self, row):
""" create constraint IonObject but do not insert into DB,
cache in dictionary for inclusion in other preload objects """
id = row[self.COL_ID]
log.debug('creating contact: ' + id)
if id in self.contact_defs:
raise iex.BadRequest('contact with ID already exists: ' + id)
roles = self._get_typed_value(row['c/roles'], targettype='simplelist')
del row['c/roles']
# phones = self._get_typed_value(row['c/phones'], targettype='simplelist')
phones = self._parse_phones(row['c/phones'])
del row['c/phones']
contact = self._create_object_from_row("ContactInformation", row, "c/")
contact.roles = roles
contact.phones = phones
self.contact_defs[id] = contact
def _parse_dict(self, text):
""" parse a SIMPLE dictionary of unquoted string keys and values
"""
out = { }
pairs = text.split(',')
for pair in pairs:
fields = pair.split(':')
key = fields[0].strip()
value = fields[1].strip()
out[key] = value
return out
def _parse_phones(self, text):
if ':' in text:
out = []
for type,number in self._parse_dict(text).iteritems():
out.append(IonObject("Phone", phone_number=number, phone_type=type))
return out
elif text:
return [ IonObject("Phone", phone_number=text.strip(), phone_type='office') ]
else:
return []
def _load_Constraint(self, row):
""" create constraint IonObject but do not insert into DB,
cache in dictionary for inclusion in other preload objects """
id = row[self.COL_ID]
if id in self.constraint_defs:
raise iex.BadRequest('constraint with ID already exists: ' + id)
type = row['type']
if type=='geospatial' or type=='geo' or type=='space':
self.constraint_defs[id] = self._create_geospatial_constraint(row)
elif type=='temporal' or type=='temp' or type=='time':
self.constraint_defs[id] = self._create_temporal_constraint(row)
else:
raise iex.BadRequest('constraint type must be either geospatial or temporal, not ' + type)
def _load_CoordinateSystem(self, row):
gcrs = self._create_object_from_row("GeospatialCoordinateReferenceSystem", row, "m/")
id = row[self.COL_ID]
self.resource_ids[id] = gcrs
def _load_CoordinateSystem_OOI(self):
fakerow = {}
fakerow[self.COL_ID] = 'OOI_SUBMERGED_CS'
fakerow['m/geospatial_geodetic_crs'] = 'http://www.opengis.net/def/crs/EPSG/0/4326'
fakerow['m/geospatial_vertical_crs'] = 'http://www.opengis.net/def/cs/EPSG/0/6498'
fakerow['m/geospatial_latitude_units'] = 'degrees_north'
fakerow['m/geospatial_longitude_units'] = 'degrees_east'
fakerow['m/geospatial_vertical_units'] = 'meter'
fakerow['m/geospatial_vertical_positive'] = 'down'
self._load_CoordinateSystem(fakerow)
def _create_geospatial_constraint(self, row):
z = row['vertical_direction']
if z=='depth':
min = float(row['top'])
max = float(row['bottom'])
elif z=='elevation':
min = float(row['bottom'])
max = float(row['top'])
else:
raise iex.BadRequest('vertical_direction must be "depth" or "elevation", not ' + z)
constraint = IonObject("GeospatialBounds",
geospatial_latitude_limit_north=float(row['north']),
geospatial_latitude_limit_south=float(row['south']),
geospatial_longitude_limit_east=float(row['east']),
geospatial_longitude_limit_west=float(row['west']),
geospatial_vertical_min=min,
geospatial_vertical_max=max)
return constraint
def _create_temporal_constraint(self, row):
format = row['time_format'] or DEFAULT_TIME_FORMAT
start = calendar.timegm(time.strptime(row['start'], format))
end = calendar.timegm(time.strptime(row['end'], format))
return IonObject("TemporalBounds", start_datetime=start, end_datetime=end)
def _get_system_actor_headers(self):
return {'ion-actor-id': self.resource_ids[self.ID_SYSTEM_ACTOR],
'ion-actor-roles': {'ION': ['ION_MANAGER', 'ORG_MANAGER']},
'expiry':'0'}
def _load_User(self, row):
# TODO: Make the calls below with an actor_id for the web server
alias = row['ID']
subject = row["subject"]
name = row["name"]
description = row['description']
ims = self._get_service_client("identity_management")
# Prepare contact and UserInfo attributes
contacts = self._get_contacts(row, field='contact_id', type='User')
if len(contacts) > 1:
raise iex.BadRequest('User %s defined with too many contacts (should be 1)' % alias)
contact = contacts[0] if len(contacts)==1 else None
user_attrs = dict(name=name, description=description)
if contact:
user_attrs['name'] = "%s %s" % (contact.individual_names_given, contact.individual_name_family)
user_attrs['contact'] = contact
# Build ActorIdentity
actor_name = "Identity for %s" % user_attrs['name']
actor_identity_obj = IonObject("ActorIdentity", name=actor_name, alt_ids=["PRE:"+alias])
actor_id = ims.create_actor_identity(actor_identity_obj, headers=self._get_system_actor_headers())
actor_identity_obj._id = actor_id
self._register_id(alias, actor_id, actor_identity_obj)
# Build UserCredentials
user_credentials_obj = IonObject("UserCredentials", name=subject,
description="Default credentials for %s" % user_attrs['name'])
ims.register_user_credentials(actor_id, user_credentials_obj, headers=self._get_system_actor_headers())
# Build UserInfo
user_info_obj = IonObject("UserInfo", **user_attrs)
ims.create_user_info(actor_id, user_info_obj, headers=self._get_system_actor_headers())
def _load_Org(self, row):
log.trace("Loading Org (ID=%s)", row[self.COL_ID])
contacts = self._get_contacts(row, field='contact_id', type='Org')
res_obj = self._create_object_from_row("Org", row, "org/")
if contacts:
res_obj.contacts = [contacts[0]]
log.trace("Org: %s", res_obj)
headers = self._get_op_headers(row)
res_id = None
org_type = row["org_type"]
if org_type == "MarineFacility":
svc_client = self._get_service_client("observatory_management")
res_id = svc_client.create_marine_facility(res_obj, headers=headers)
elif org_type == "VirtualObservatory":
svc_client = self._get_service_client("observatory_management")
res_id = svc_client.create_virtual_observatory(res_obj, headers=headers)
else:
log.warn("Unknown Org type: %s" % org_type)
if res_id:
res_obj._id = res_id
self._register_id(row[self.COL_ID], res_id, res_obj)
def _load_UserRole(self, row):
org_id = row["org_id"]
if org_id:
org_id = self.resource_ids[org_id]
user_id = self.resource_ids[row["user_id"]]
role_name = row["role_name"]
svc_client = self._get_service_client("org_management")
auto_enroll = self._get_typed_value(row["auto_enroll"], targettype="bool")
if auto_enroll:
svc_client.enroll_member(org_id, user_id, headers=self._get_system_actor_headers())
if role_name != "ORG_MEMBER":
svc_client.grant_role(org_id, user_id, role_name, headers=self._get_system_actor_headers())
def _load_SensorModel(self, row):
row['sm/reference_urls'] = repr(self._get_typed_value(row['sm/reference_urls'], targettype="simplelist"))
self._basic_resource_create(row, "SensorModel", "sm/",
"instrument_management", "create_sensor_model",
support_bulk=True)
def _get_org_ids(self, ooi_rd_list):
if not ooi_rd_list:
return ""
marine_ios = set()
for ooi_rd in ooi_rd_list:
marine_io = self.ooi_loader.get_marine_io(ooi_rd)
if marine_io == "CG":
marine_ios.add("MF_CGSN")
elif marine_io == "RSN":
marine_ios.add("MF_RSN")
elif marine_io == "EA":
marine_ios.add("MF_EA")
return ",".join(marine_ios)
def _match_filter(self, rdlist):
"""Returns true if at least one item in given list (or comma separated str) matches a filter in ooifilter"""
if not self.ooifilter:
return True
if not rdlist:
return False
if type(rdlist) is str:
rdlist = [val.strip() for val in rdlist.split(",")]
for item in rdlist:
if item in self.ooifilter:
return True
return False
def _load_PlatformModel(self, row):
res_id = self._basic_resource_create(row, "PlatformModel", "pm/",
"instrument_management", "create_platform_model",
support_bulk=True)
def _load_PlatformModel_OOI(self):
ooi_objs = self.ooi_loader.get_type_assets("nodetype")
for ooi_id, ooi_obj in ooi_objs.iteritems():
fakerow = {}
fakerow[self.COL_ID] = ooi_id + "_PM"
fakerow['pm/name'] = ooi_obj['name']
fakerow['pm/alt_ids'] = "['OOI:" + ooi_id + "_PM" + "']"
fakerow['org_ids'] = self._get_org_ids(ooi_obj.get('array_list', None))
if not self._match_filter(ooi_obj.get('array_list', None)):
continue
self._load_PlatformModel(fakerow)
def _load_InstrumentModel(self, row):
row['im/reference_urls'] = repr(self._get_typed_value(row['im/reference_urls'], targettype="simplelist"))
#raw_stream_def = row['raw_stream_def']
#parsed_stream_def = row['parsed_stream_def']
#row['im/stream_configuration'] = "{'raw': '%s', 'parsed': '%s'}" % (raw_stream_def, parsed_stream_def)
res_id = self._basic_resource_create(row, "InstrumentModel", "im/",
"instrument_management", "create_instrument_model",
support_bulk=True)
def _load_InstrumentModel_OOI(self):
ooi_objs = self.ooi_loader.get_type_assets("subseries")
for ooi_id, ooi_obj in ooi_objs.iteritems():
series_obj = self.ooi_loader.get_type_assets("series")[ooi_id[:6]]
class_obj = self.ooi_loader.get_type_assets("class")[ooi_id[:5]]
family_obj = self.ooi_loader.get_type_assets("family")[class_obj['family']]
fakerow = {}
fakerow[self.COL_ID] = ooi_id
fakerow['im/name'] = ooi_obj['name']
fakerow['im/alt_ids'] = "['OOI:" + ooi_id + "']"
fakerow['im/description'] = ooi_obj['description']
fakerow['im/instrument_family'] = class_obj['family']
fakerow['raw_stream_def'] = ''
fakerow['parsed_stream_def'] = ''
fakerow['org_ids'] = self._get_org_ids(class_obj.get('array_list', None))
reference_urls = []
addl = {}
if ooi_obj.get('makemodel', None) and ooi_obj['makemodel'][0]:
# TODO: Catch case where there is more than one makemodel per subseries
makemodel_obj = self.ooi_loader.get_type_assets("makemodel")[ooi_obj['makemodel'][0]]
fakerow['im/manufacturer'] = makemodel_obj['Manufacturer']
fakerow['im/manufacturer_url'] = makemodel_obj['Vendor Website']
addl.update(dict(connector=makemodel_obj['Connector'],
makemodel=ooi_obj['makemodel'][0],
makemodel_description=makemodel_obj['Make_Model_Description'],
input_voltage_range=makemodel_obj['Input Voltage Range'],
interface=makemodel_obj['Interface'],
makemodel_url=makemodel_obj['Make/Model Website'],
output_description=makemodel_obj['Output Description'],
))
if makemodel_obj['Make/Model Website']: reference_urls.append(makemodel_obj['Make/Model Website'])
fakerow['im/reference_urls'] = ",".join(reference_urls)
addl['alternate_name'] = ooi_obj['Alternate Instrument Class Name']
addl['class_long_name'] = ooi_obj['ClassLongName']
addl['comments'] = ooi_obj['Comments']
fakerow['im/addl'] = repr(addl)
if not self._match_filter(class_obj.get('array_list', None)):
continue
self._load_InstrumentModel(fakerow)
def _load_Observatory(self, row):
constraints = self._get_constraints(row, type='Observatory')
coordinate_name = row['coordinate_system']
res_id = self._basic_resource_create(row, "Observatory", "obs/",
"observatory_management", "create_observatory",
constraints=constraints, constraint_field='constraint_list',
set_attributes=dict(coordinate_reference_system=self.resource_ids[coordinate_name]) if coordinate_name else None,
support_bulk=True)
def _load_Observatory_OOI(self):
ooi_objs = self.ooi_loader.get_type_assets("array")
for ooi_id, ooi_obj in ooi_objs.iteritems():
fakerow = {}
fakerow[self.COL_ID] = ooi_id
fakerow['obs/name'] = ooi_obj['name']
fakerow['obs/alt_ids'] = "['OOI:" + ooi_id + "']"
fakerow['constraint_ids'] = ''
fakerow['coordinate_system'] = 'OOI_SUBMERGED_CS'
fakerow['org_ids'] = self._get_org_ids([ooi_id])
if not self._match_filter(ooi_id):
continue
self._load_Observatory(fakerow)
def _load_Subsite(self, row):
constraints = self._get_constraints(row, type='Subsite')
coordinate_name = row['coordinate_system']
res_id = self._basic_resource_create(row, "Subsite", "site/",
"observatory_management", "create_subsite",
constraints=constraints, constraint_field='constraint_list',
set_attributes=dict(coordinate_reference_system=self.resource_ids[coordinate_name]) if coordinate_name else None,
support_bulk=True)
headers = self._get_op_headers(row)
psite_id = row.get("parent_site_id", None)
if psite_id:
if self.bulk:
psite_obj = self._get_resource_obj(psite_id)
site_obj = self._get_resource_obj(row[self.COL_ID])
self._create_association(psite_obj, PRED.hasSite, site_obj)
else:
svc_client = self._get_service_client("observatory_management")
svc_client.assign_site_to_site(res_id, self.resource_ids[psite_id],
headers=headers)