-
Notifications
You must be signed in to change notification settings - Fork 24
/
service_api.py
1580 lines (1268 loc) · 71.3 KB
/
service_api.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
import requests, json, time, re
from flask import session, jsonify, abort, current_app as app
from config import GATEWAY_HOST, GATEWAY_PORT
from copy import deepcopy
from instrument_command import BLACKLIST
from werkzeug.contrib.cache import SimpleCache
from werkzeug.exceptions import HTTPException
# import re
import config
GATEWAY_BASE_URL = 'http://%s:%d' % (GATEWAY_HOST, GATEWAY_PORT)
SERVICE_GATEWAY_BASE_URL = '%s/ion-service' % (GATEWAY_BASE_URL)
AGENT_GATEWAY_BASE_URL = '%s/ion-agent' % (GATEWAY_BASE_URL)
SERVICE_REQUEST_TEMPLATE = {
'serviceRequest': {
'serviceName': '',
'serviceOp': '',
'params': {} # Example -> 'object_name': ['restype', {}] }
}
}
AGENT_REQUEST_TEMPLATE = {
"agentRequest": {
"agentId": "",
"agentOp": "",
# "expiry": 0,
"params": {"timeout": 300, "command": { "type_": "AgentCommand", "command": "placeholder" }}
}
}
class ServiceApi(object):
@staticmethod
def platform_agent_state(platform_device_id, agent_op):
# agent_op = command
# params = {"command": {"type_": "AgentCommand", "command": 'placeholder'}}'
params = None
agent_response = service_gateway_agent_request(platform_device_id, agent_op, params)
return agent_response
@staticmethod
def get_sites_status(resource_ids):
# params = {'parent_resource_ids': resource_ids, 'include_status': True}
params = {'parent_resource_ids': resource_ids, 'include_status': True, 'include_sites': True}
req = service_gateway_post('observatory_management', 'get_sites_devices_status', raw_return=True, params=params)
return req
# return service_gateway_get('observatory_management', 'get_sites_devices_status', raw_return=True, params=params)
@staticmethod
def visualization(operation_name, visualization_parameters):
return service_gateway_get('visualization', operation_name, raw_return=True, params=visualization_parameters)
@staticmethod
def find_related_objects_has_resource(resource_id):
related_objects = service_gateway_get('resource_management', 'get_org_resource_attributes', params={'org_id': resource_id})
if related_objects:
for obj in related_objects:
if u"type__" in obj:
obj[u"type_"] = obj.pop(u"type__")
if "type__" in obj:
obj["type_"] = obj.pop("type__")
return related_objects
@staticmethod
def find_related_sites(resource_id):
related_sites = service_gateway_get('observatory_management', 'find_related_sites', params={'parent_resource_id': resource_id, 'include_parents': True, 'include_devices': True})
return related_sites
@staticmethod
def get_recent_events(resource_id, user_id):
return service_gateway_get('user_notification', 'get_recent_events', raw_return = True, params = {'resource_id': resource_id, 'user_id': user_id})
@staticmethod
def get_data_product_group_list():
dp_group_list = service_gateway_get('data_product_management', 'get_data_product_group_list', raw_return=True, params={})
return dp_group_list
@staticmethod
def find_site_data_products(resource_id):
site_data_products = service_gateway_get('observatory_management',
'find_site_data_products',
raw_return=True,
params={'parent_resource_id': resource_id,
'include_data_products': True,
'include_devices': True
})
return site_data_products
@staticmethod
def get_data_product_updates(data_product_ids, since_timestamp):
data_products_status = service_gateway_get('data_product_management',
'get_data_product_updates',
raw_return=True,
params={'data_product_id_list': data_product_ids,
'since_timestamp': since_timestamp
})
return data_products_status
@staticmethod
def get_data_product_parameters(data_product_id):
parameters = service_gateway_get('data_product_management',
'get_data_product_parameters',
raw_return=True,
params={'data_product_id' : data_product_id})
return parameters
@staticmethod
def activate_primary(deployment_id):
activate = service_gateway_post('observatory_management', 'activate_deployment', params={'deployment_id': deployment_id})
return activate
@staticmethod
def deactivate_primary(deployment_id):
deactivate = service_gateway_post('observatory_management', 'deactivate_deployment', params={'deployment_id': deployment_id})
return deactivate
@staticmethod
def activate_persistence(data_product_id):
res = service_gateway_post('data_product_management', 'activate_data_product_persistence', params={'data_product_id':data_product_id})
return res
@staticmethod
def suspend_persistence(data_product_id):
res = service_gateway_post('data_product_management', 'suspend_data_product_persistence', params={'data_product_id':data_product_id})
return res
@staticmethod
def search(search_query):
query = None
# simple search for possible raw query language
raw_starts = ["search '", "belongs to", "has '", "in '"]
searchlow = search_query.lower()
for raw in raw_starts:
if searchlow.startswith(raw):
query = search_query
# is this a resource id only?
if not query:
rrid = re.compile('^[a-z0-9]{32}$')
if rrid.match(search_query):
query = "SEARCH '_id' MATCH '%s' FROM 'resources_index' LIMIT 100" % search_query
# if not a raw query or resource id
if not query:
if ' or ' in search_query.lower() and ' and ' in search_query.lower():
abort(400,description="Search may not include both AND & OR operators.")
# split into ands|ors
# from http://stackoverflow.com/a/1180180/84732
if ' or ' in search_query.lower():
condition = 'or'
else:
condition = 'and'
rors = re.compile(' %s (?=(?:(?:[^"]*"){2})*[^"]*$)' % (condition), flags=re.IGNORECASE)
exprs = rors.split(search_query)
search_template = "SEARCH '%s' %s '%s' FROM 'data_products_index'"
queries = []
for expr in exprs:
val = expr
verb = "MATCH"
field = "_all"
# allow specifying specific field with = sign
# must allow following rules to be applied too
if val[0] != '"' and val[-1] != '"' and "=" in val:
field, val = val.split("=", 1)
# allow "LIKE" searching with ~
if val[0] == "~":
val = val[1:]
verb = "LIKE"
# quotes on both sides mean exact match only
elif val[0] == '"' and val[-1] == '"':
verb = "IS"
val = val[1:-1]
queries.append(search_template % (field, verb, val))
query = " %s " % (condition.upper()).join(queries) + " LIMIT 100"
url = build_get_request(SERVICE_GATEWAY_BASE_URL, 'discovery', 'parse', params={'search_request': query, 'id_only': False})
resp = requests.get(url)
search_json = json.loads(resp.content)
if search_json['data'].has_key('GatewayResponse'):
return search_json['data']['GatewayResponse']
return search_json['data']
@staticmethod
def adv_search(geospatial_bounds, vertical_bounds, temporal_bounds, temporal_field, search_criteria):
post_data = {'query': {},
'and': [],
'or': []}
queries = []
max_search_limit = config.MAX_SEARCH_RESULTS if hasattr(config, 'MAX_SEARCH_RESULTS') else 100
post_data['limit'] = max_search_limit
if geospatial_bounds and all(geospatial_bounds.itervalues()):
queries.append({'bottom_right': [float(geospatial_bounds['east']),
float(geospatial_bounds['south'])],
'top_left': [float(geospatial_bounds['west']),
float(geospatial_bounds['north'])],
'field': 'geospatial_point_center',
'index': 'data_products_index'})
if vertical_bounds and all(vertical_bounds.itervalues()):
queries.append({'vertical_bounds': {'from': float(vertical_bounds['lower']),
'to': float(vertical_bounds['upper'])},
'field': 'geospatial_bounds',
'index': 'data_products_index'})
if temporal_bounds and all(temporal_bounds.itervalues()) and temporal_field:
queries.append({'time': {'from': temporal_bounds['from'],
'to': temporal_bounds['to']},
'field': temporal_field,
'index': 'data_products_index'})
if search_criteria:
for item in search_criteria:
q = {'index': 'data_products_index', 'field': str(item[0])}
#Remove non alphanumeric characters but keep spaces
delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum() and not c.isspace())
v = (str(item[2]).strip()).translate(None, delchars)
# if no value, it's probably just the first one left blank
if not v:
continue
if item[1].lower() == "contains":
q['match'] = v
elif item[1].lower() == "starts with":
q['value'] = "{0}*".format(v)
elif item[1].lower() == "ends with":
q['value'] = "*{0}".format(v)
elif item[1].lower() == "like":
q['fuzzy'] = v
elif item[1].lower() == "matches":
q['value'] = v
else:
q['match'] = v # anything we didn't get
queries.append(q)
# transform queries into the expected query object
if len(queries) == 0:
abort(400, description="Advanced search requires at least one search parameter, all fields blank.")
post_data['query'] = queries[0]
post_data['and'] = queries[1:]
# have to manually call because normal SG post turns a list into the first object?
url, data = build_post_request('discovery', 'query', {'query': post_data, 'id_only': False})
resp = requests.post(url, data)
search_json = json.loads(resp.content)
if search_json['data'].has_key('GatewayResponse'):
return search_json['data']['GatewayResponse']
return search_json['data']
@staticmethod
def update_resource(resource_type, resource_obj, resource_assocs):
# grab the schema again - if this is cached, this will be quick!
#r = ResourceTypeSchema(resource_type)
#schema = r.get_data(resource_type)
# Hack to convert strings into objects, booleans
# as a workaround to shortcomings dynamically generating
# backbone-forms (booleans and user-defined key-values, such as
# custom_attributes). See ResourceTypeSchema() below, or
# /static/js/ux-editform.js for current implementation.
# reset session variable for IONUX.SESSION_MODEL on the client.
for k, v in resource_obj.iteritems():
if isinstance(v, unicode) or isinstance(v, str):
if v.startswith('{'):
try:
resource_obj.update({k: json.loads(str(v))})
except Exception as e:
# pass it to the backend for validation and error?
pass
# catch any objects that were
elif v == '[object Object]':
resource_obj.update({k: {}})
if v == 'true':
resource_obj.update({k: True})
elif v == 'false':
resource_obj.update({k: False})
if resource_type == 'UserInfo':
for variable in resource_obj['variables']:
if variable['name'] == 'ui_theme_dark':
session['ui_theme_dark'] = variable['value']
req = service_gateway_post('resource_management', 'update_resource', params={'resource': resource_obj})
reqs = [req]
# handle associations
if len(resource_assocs):
# get prepare statement to build urls
prepare = ServiceApi.get_prepare(resource_type, resource_obj['_id'], None)
assocs = prepare['associations']
def mod_assoc(assoc_mod, val):
if not assoc_mod:
raise StandardError("no request available")
params = assoc_mod['request_parameters'].copy()
rid_param = assoc_mod['resource_identifier']
for k,v in params.iteritems():
if "$(%s)" % rid_param == v:
params[k] = val
break
#print params
req = service_gateway_post(assoc_mod['service_name'],
assoc_mod['service_operation'],
params=params)
return req
def get_assocd_id(assoc):
"""
Returns the associated id of the given association to this current resource,
either subject or object side.
@TODO this feels clunky
"""
cur = assoc['s']
if cur == resource_obj['_id']:
cur = assoc['o']
return cur
for k,v in resource_assocs.iteritems():
curval = assocs[k]['associated_resources']
if assocs[k]['multiple_associations']:
# get a list of current assocs
cur_assocs = set(map(get_assocd_id, curval))
# now a list of new assocs
assert v is None or isinstance(v, list)
if v is None:
v = []
new_assocs = set(v)
# get list of removals: things in current not in new
to_remove = cur_assocs.difference(new_assocs)
# get list of additions: things in new not in current
to_add = new_assocs.difference(cur_assocs)
for aid in to_remove:
reqs.append(mod_assoc(assocs[k]['unassign_request'], aid))
for aid in to_add:
reqs.append(mod_assoc(assocs[k]['assign_request'], aid))
else:
# single
if len(curval) == 1:
curid = get_assocd_id(curval[0])
if curid != v:
# unassoc
reqs.append(mod_assoc(assocs[k]['unassign_request'], curid))
# assoc, only if value occurs though
if v:
reqs.append(mod_assoc(assocs[k]['assign_request'], v))
else:
# assert len(curval) == 0, "curval is %s" % curval
if v:
# assoc
reqs.append(mod_assoc(assocs[k]['assign_request'], v))
return reqs
@staticmethod
def create_resource_attachment(resource_id, attachment_name, attachment_description, attachment_type, attachment_content_type, content, keywords, created_by, modified_by):
# form our own data
post_data = {'resource_id' : resource_id,
'keywords' : keywords,
'attachment_name' : attachment_name,
'attachment_description' : attachment_description,
'attachment_type' : attachment_type,
'attachment_content_type' : attachment_content_type,
'attachment_created_by' : created_by,
'attachment_modified_by' : modified_by}
# use build_post_request to get url
url, req = build_post_request('attachment', None, params=post_data)
post_files = { 'file': (attachment_name, content) }
# make our own post
req = requests.post(url, req, files=post_files)
return req
@staticmethod
def delete_resource_attachment(attachment_id):
url = build_get_request(SERVICE_GATEWAY_BASE_URL, 'attachment', attachment_id)
req = requests.delete(url)
return render_service_gateway_response(req)
@staticmethod
def attachment_is_owner(attachment_id, actor_id):
ret = service_gateway_get('resource_registry', 'find_associations', params={'predicate': 'hasOwner',
'subject': attachment_id,
'object': actor_id,
'id_only': True},
raw_return=True)
return jsonify({'data':len(ret) > 0})
@staticmethod
def transition_lcstate(resource_id, transition_event):
req = service_gateway_get('resource_management', 'execute_lifecycle_transition', params={'resource_id': resource_id, 'transition_event': transition_event})
return req
@staticmethod
def get_user_subscriptions(user_id):
return service_gateway_post('user_notification', 'get_user_notifications', params={'user_info_id': user_id})
@staticmethod
def create_user_notification(resource_type, resource_id, event_type, user_id, resource_name=None):
name = 'Notification Request for %s' % resource_name if resource_name else 'NotificationTest'
description = '%s - %s - Notification Request' % (resource_type, event_type)
notification = {
"type_": "NotificationRequest",
"lcstate": "DRAFT",
"description": description,
"name": name,
"origin": resource_id,
"origin_type": resource_type,
"event_type": event_type
}
return service_gateway_post('user_notification', 'create_notification', params={'notification': notification, 'user_id': user_id})
@staticmethod
def delete_user_subscription(notification_id):
return service_gateway_post('user_notification', 'delete_notification', params={'notification_id': notification_id})
@staticmethod
def enroll_request(resource_id, actor_id):
sap = {'type_': 'EnrollmentProposal',
'originator': 1,
'consumer': actor_id,
'provider': resource_id,
'description': "Enrollment Request",
'proposal_status': 1 }
return service_gateway_post('org_management', 'negotiate', params={'sap':sap})
@staticmethod
def request_role(resource_id, actor_id, role_name):
sap = {'type_': 'RequestRoleProposal',
'originator': 1,
'consumer': actor_id,
'provider': resource_id,
'proposal_status': 1,
'description': "Role Request: %s" % role_name,
'role_name': role_name }
return service_gateway_post('org_management', 'negotiate', params={'sap':sap})
@staticmethod
def invite_user(resource_id, user_id):
# look up actor id from user id
actor_id = service_gateway_get('resource_registry', 'find_subjects', params={'predicate': 'hasInfo', 'object': user_id, 'id_only': True})[0]
sap = {'type_': 'EnrollmentProposal',
'originator': 2,
'consumer': actor_id,
'provider': resource_id,
'description': "Enrollment Invite",
'proposal_status': 1 }
return service_gateway_post('org_management', 'negotiate', params={'negotiation_type': 2,
'sap':sap})
@staticmethod
def offer_user_role(resource_id, user_id, role_name):
# look up actor id from user id
actor_id = service_gateway_get('resource_registry', 'find_subjects', params={'predicate': 'hasInfo', 'object': user_id, 'id_only': True})[0]
sap = {'type_': 'RequestRoleProposal',
'originator': 2,
'consumer': actor_id,
'provider': resource_id,
'proposal_status': 1,
'description': "Role Invite: %s" % role_name,
'role_name': role_name }
return service_gateway_post('org_management', 'negotiate', params={'negotiation_type': 2,
'sap':sap})
@staticmethod
def request_access(resource_id, res_name, actor_id, org_id):
sap = {'type_': 'AcquireResourceProposal',
'originator': 1,
'consumer': actor_id,
'provider': org_id,
'proposal_status': 1,
'description': "Access Request: %s" % res_name,
'resource_id': resource_id }
return service_gateway_post('org_management', 'negotiate', params={'sap':sap})
@staticmethod
def release_access(commitment_id):
return service_gateway_post('org_management', 'release_commitment', params={'commitment_id':commitment_id})
@staticmethod
def request_exclusive_access(resource_id, actor_id, org_id, expiration):
sap = {'type_': 'AcquireResourceExclusiveProposal',
'originator': 1,
'consumer': actor_id,
'provider': org_id,
'proposal_status': 1,
'resource_id': resource_id,
'description': "Exclusive Access Request",
'expiration': expiration}
return service_gateway_post('org_management', 'negotiate', params={'sap':sap})
@staticmethod
def accept_reject_negotiation(negotiation_id, verb, originator, reason):
if not verb in ["accept", "reject"]:
return error_message("Unknown verb %s" % verb)
url, _ = build_post_request("resolve-org-negotiation", None)
post_data = {'negotiation_id': negotiation_id,
'verb': verb,
'reason': reason,
'originator': originator}
if "actor_id" in session:
post_data['serviceRequest'] = {'requester' : session['actor_id'],
'expiry' : session['valid_until']}
data={'payload': json.dumps(post_data)}
req = requests.post(url, data)
return render_service_gateway_response(req)
@staticmethod
def get_event_types():
events_url = 'http://%s:%s/ion-service/list_resource_types?type=Event' % (GATEWAY_HOST, GATEWAY_PORT)
events = requests.get(events_url)
events_json = json.loads(events.content)
return events_json['data']['GatewayResponse']
@staticmethod
def publish_event(event_type, origin, origin_type, sub_type, description):
pdict = { 'event_type' : event_type,
'origin' : origin,
'origin_type' : origin_type,
'sub_type' : sub_type,
'description' : description}
return service_gateway_post('user_notification', 'publish_event', params=pdict)
@staticmethod
def ui_reset():
return service_gateway_get('directory', 'reset_ui_specs', params={'url': 'http://filemaker.oceanobservatories.org/database-exports/'})
@staticmethod
def find_by_resource_type(resource_type, user_info_id=None):
# Todo - Implement "My Resources" as a separate call when they are available (observatories, platforms, etc.)...
if resource_type == 'NotificationRequest':
if user_info_id:
req = service_gateway_get('user_notification', 'get_user_notifications', params={'user_info_id': user_info_id})
else:
return []
req = service_gateway_get('resource_registry', 'find_resources', params={'restype': resource_type})
return req
@staticmethod
def find_by_resource_id(resource_id):
resource = service_gateway_get('resource_registry', 'read', params={'object_id': resource_id})
return jsonify(data=resource)
@staticmethod
def get_extension(resource_type, resource_id, user_id):
if resource_type == 'InstrumentDevice':
extension = service_gateway_get('instrument_management', 'get_instrument_device_extension', params= {'instrument_device_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type in ('InstrumentModel', 'SensorModel', 'PlatformModel'):
extension = service_gateway_get('resource_registry', 'get_resource_extension', params= {'resource_id': resource_id, 'resource_extension': 'DeviceModelExtension', 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'PlatformDevice':
extension = service_gateway_get('instrument_management', 'get_platform_device_extension', params= {'platform_device_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'DataProduct':
extension = service_gateway_get('data_product_management', 'get_data_product_extension', params= {'data_product_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'UserInfo':
extension = service_gateway_get('identity_management', 'get_user_info_extension', params= {'user_info_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'DataProcessDefinition':
extension = service_gateway_get('data_process_management', 'get_data_process_definition_extension', params= {'data_process_definition_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'Org':
extension = service_gateway_get('observatory_management', 'get_marine_facility_extension', params= {'org_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'Observatory':
extension = service_gateway_get('observatory_management', 'get_observatory_site_extension', params= {'site_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'PlatformComponentSite':
extension = service_gateway_get('observatory_management', 'get_platform_component_site_extension', params= {'site_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'PlatformAssemblySite':
extension = service_gateway_get('observatory_management', 'get_platform_assembly_site_extension', params= {'site_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'StationSite':
extension = service_gateway_get('observatory_management', 'get_platform_station_site_extension', params= {'site_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'InstrumentSite':
extension = service_gateway_get('observatory_management', 'get_instrument_site_extension', params= {'site_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'Deployment':
extension = service_gateway_get('observatory_management', 'get_deployment_extension', params= {'deployment_id': resource_id, 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'NotificationRequest':
extension = service_gateway_get('resource_registry', 'get_resource_extension', params= {'resource_id': resource_id, 'resource_extension': 'NotificationRequestExtension', 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type == 'DataProcess':
extension = service_gateway_get('resource_registry', 'get_resource_extension', params= {'resource_id': resource_id, 'resource_extension': 'DataProcessExtension', 'user_id': user_id,'ext_exclude': "['recent_events']"})
elif resource_type in ('UserRole'):
extension = service_gateway_get('resource_registry', 'get_resource_extension', params= {'resource_id': resource_id, 'resource_extension': 'ExtendedInformationResource', 'user_id': user_id,'ext_exclude': "['recent_events']"})
else:
extension = service_gateway_get('resource_registry', 'get_resource_extension', params= {'resource_id': resource_id, 'resource_extension': 'ExtendedInformationResource', 'user_id': user_id,'ext_exclude': "['recent_events']"})
# brute force - if not an InformationResource, it might be taskable
if "GatewayError" in extension:
extension = service_gateway_get('resource_registry', 'get_resource_extension', params = {'resource_id': resource_id, 'resource_extension': 'ExtendedTaskableResource', 'user_id': user_id,'ext_exclude': "['recent_events']"})
#else:
# extension = error_message(msg="Resource extension for %s is not available." % resource_type)
return extension
@staticmethod
def create_resource(resource_type, org_id, resource_name=None):
prepare = ServiceApi.get_prepare(resource_type, None, None)
if isinstance(prepare, dict) and "GatewayError" in prepare:
return [prepare, None]
create_op = prepare['create_request']
resource = prepare['resource'].copy()
resource_name = resource_name or 'New %s' % resource_type
resource.update({'name': resource_name})
resp = service_gateway_post(create_op['service_name'], create_op['service_operation'], params={create_op['request_parameters'].keys()[0]: resource})
if isinstance(resp, dict) and "GatewayError" in resp:
resp2 = None
else:
resp2 = service_gateway_post('resource_registry', 'create_association', params={'subject':org_id,
'predicate': 'hasResource',
'object': resp})
return [resp, resp2]
@staticmethod
def get_prepare(resource_type, resource_id, user_id, get_backbone_schema=False):
# because of the way the UI changes the type that comes in here, we can't really trust it
# this means we need to read the resource to get the type first then use that.
if resource_id:
res = service_gateway_get('resource_registry', 'read', params={'object_id': resource_id})
resource_type = res['type_']
if resource_type == 'InstrumentDevice':
params = {}
if resource_id:
params['instrument_device_id'] = resource_id
prepare = service_gateway_get('instrument_management', 'prepare_instrument_device_support', params=params)
elif resource_type == 'PlatformDevice':
params = {}
if resource_id:
params['platform_device_id'] = resource_id
prepare = service_gateway_get('instrument_management', 'prepare_platform_device_support', params=params)
elif resource_type == "InstrumentAgentInstance":
params = {}
if resource_id:
params['instrument_agent_instance_id'] = resource_id
prepare = service_gateway_get('instrument_management', 'prepare_instrument_agent_instance_support', params=params)
elif resource_type == "DataProduct":
params = {}
if resource_id:
params['data_product_id'] = resource_id
prepare = service_gateway_get('data_product_management', 'prepare_data_product_support', params=params)
elif resource_type == "InstrumentAgent":
params = {}
if resource_id:
params['instrument_agent_id'] = resource_id
prepare = service_gateway_get('instrument_management', 'prepare_instrument_agent_support', params=params)
elif resource_type == "ExternalDatasetAgent":
params = {}
if resource_id:
params['external_dataset_agent_id'] = resource_id
prepare = service_gateway_get('data_acquisition_management', 'prepare_external_dataset_agent_support', params=params)
elif resource_type == "ExternalDatasetAgentInstance":
params = {}
if resource_id:
params['external_dataset_agent_instance_id'] = resource_id
prepare = service_gateway_get('data_acquisition_management', 'prepare_external_dataset_agent_instance_support', params=params)
elif resource_type == "Deployment":
params = {}
if resource_id:
params['deployment_id'] = resource_id
prepare = service_gateway_get('observatory_management', 'prepare_deployment_support', params=params)
elif resource_type == "UserInfo":
params = {}
if resource_id:
params['user_info_id'] = resource_id
prepare = service_gateway_get('identity_management', 'prepare_user_info_support', params=params)
else:
# GENERIC VERSION
params = {'resource_type':resource_type}
if resource_id:
params['resource_id'] = resource_id
prepare = service_gateway_get('resource_registry', 'prepare_resource_support', params=params)
# now, get the backbone schema if requested, using the converted type we got above
if get_backbone_schema:
prepare['resource_backbone_schema'] = ServiceApi.resource_type_schema(resource_type)
return prepare
"""
@staticmethod
def initiate_realtime_visualization(data_product_id):
real_time_data = service_gateway_get('visualization_service', 'initiate_realtime_visualization', params= {'data_product_id': data_product_id, 'callback': 'chart.init_realtime_visualization_cb', 'return_format': 'raw_json'})
@staticmethod
def get_realtime_visualization_data(query_token):
real_time_data = service_gateway_get('visualization_service', 'get_realtime_visualization_data', params= {'query_token': query_token, 'return_format': 'raw_json'})
@staticmethod
def get_overview_visualization_data(data_product_id):
overview_data = service_gateway_get('visualization_service', 'get_visualization_data', params={'data_product_id': data_product_id, 'return_format': 'raw_json'})
return overview_data
"""
# USER REQUESTS
# ---------------------------------------------------------------------------
@staticmethod
def find_org_user_requests(marine_facility_id, user_id=None):
org_id = service_gateway_get('marine_facility_management', 'find_marine_facility_org', params={'marine_facility_id': marine_facility_id})
if user_id:
user_requests = service_gateway_get('org_management', 'find_user_requests', params={'org_id': org_id, 'user_id': user_id})
else:
user_requests = service_gateway_get('org_management', 'find_requests', params={'org_id': org_id})
keepers = []
for e in user_requests:
user_id = e['user_id']
if not any([k["user_id"] == user_id for k in keepers]):
keepers.append(e)
return keepers
@staticmethod
def request_enrollment_in_org(marine_facility_id, user_id):
org_id = service_gateway_get('marine_facility_management', 'find_marine_facility_org', params={'marine_facility_id': marine_facility_id})
enrollment = deepcopy(SERVICE_REQUEST_TEMPLATE)
enrollment['serviceRequest']['serviceName'] = 'org_management'
enrollment['serviceRequest']['serviceOp'] = 'request_enroll'
enrollment['serviceRequest']['params'] = {'org_id': org_id, 'user_id': user_id}
url = '%s/org_management/request_enroll' % SERVICE_GATEWAY_BASE_URL
enroll_user = requests.post(url, data={'payload': json.dumps(enrollment)})
return enroll_user
@staticmethod
def handle_user_request(marine_facility_id, request_id, action, reason=None):
org_id = service_gateway_get('marine_facility_management', 'find_marine_facility_org', params={'marine_facility_id': marine_facility_id})
actions = ['approve', 'deny', 'accept', 'reject']
if action not in actions:
return "False"
if action == 'approve':
res = service_gateway_get('org_management', 'approve_request', params={'org_id': org_id, 'request_id': request_id})
elif action == 'deny':
res = service_gateway_get('org_management', 'deny_request', params={'org_id': org_id, 'request_id': request_id})
elif action == 'accept':
res = service_gateway_get('org_management', 'accept_request', params={'org_id': org_id, 'request_id': request_id})
else:
res = service_gateway_get('org_management', 'deny_request', params={'org_id': org_id, 'request_id': request_id, 'reason': reason})
return res
"""
@staticmethod
def fetch_map(ui_server, unique_key):
# TODO: service_gateway_get to support dict arguments
map_kml = requests.get('http://%s:%d/ion-service/visualization_service/get_data_product_kml?visualization_parameters={"unique_key":"%s","ui_server":"%s"}&return_mimetype=application/json' % (GATEWAY_HOST, GATEWAY_PORT, unique_key, ui_server))
return map_kml.content
"""
# INSTRUMENT COMMAND
# ---------------------------------------------------------------------------
@staticmethod
def instrument_agent_start(instrument_device_id):
instrument_agent_instance = service_gateway_get('instrument_management', 'find_instrument_agent_instance_by_instrument_device', params={'instrument_device_id': instrument_device_id})
instrument_agent_instance_id = instrument_agent_instance['_id']
agent_request = service_gateway_get('instrument_management', 'start_instrument_agent_instance', params={'instrument_agent_instance_id': str(instrument_agent_instance_id)})
return agent_request
@staticmethod
def instrument_agent_stop(instrument_device_id):
instrument_agent_instance = service_gateway_get('instrument_management', 'find_instrument_agent_instance_by_instrument_device', params={'instrument_device_id': instrument_device_id})
instrument_agent_instance_id = instrument_agent_instance['_id']
ServiceApi.reset_driver(instrument_device_id)
agent_request = service_gateway_get('instrument_management', 'stop_instrument_agent_instance', params={'instrument_agent_instance_id': str(instrument_agent_instance_id)})
return agent_request
# Used to ensure that driver is reset prior to an agent being stopped.
@staticmethod
def reset_driver(instrument_device_id):
capabilities = ServiceApi.instrument_agent_get_capabilities(instrument_device_id)
reset_cmd = 'RESOURCE_AGENT_EVENT_RESET'
reset_state = bool([True for c in capabilities['commands'] if c['name'] == reset_cmd])
if reset_state:
ServiceApi.instrument_execute(instrument_device_id, reset_cmd, '1')
return
@staticmethod
def instrument_execute(instrument_device_id, command, cap_type, session_type=None):
if cap_type == '1':
agent_op = "execute_agent"
elif cap_type in ('3','4'):
agent_op = "execute_resource"
params = {"command": {"type_": "AgentCommand", "command": command}}
if command == 'RESOURCE_AGENT_EVENT_GO_DIRECT_ACCESS':
params['command'].update({'kwargs': {'session_type': int(session_type), 'session_timeout':600, 'inactivity_timeout': 600}})
agent_request = service_gateway_agent_request(instrument_device_id, agent_op, params)
return agent_request
@staticmethod
def instrument_agent_get_capabilities(instrument_device_id):
def _to_form_schema(schema_type=None, schema_visibility=None, schema_display_name=None):
if schema_type:
if schema_type in ['list', 'tuple']:
item = {'type': 'List', 'itemType': 'TextArea', 'editorClass': 'list-textarea'}
elif schema_type == 'bool':
item = {'type': 'Checkbox'}
elif schema_type in ['int', 'float']:
item = {'type': 'Number'}
elif schema_type in ('str', 'string'):
item = {'type': 'Text'}
elif schema_type == 'dict':
item = {'type': 'TextArea'}
# TEMP: catchall
else:
item = {'type': 'Text'}
else:
item = {'type': 'Text'}
if schema_visibility in ('READ_ONLY', 'IMMUTABLE'):
item.update({'editorAttrs': {'disabled': True}})
if schema_display_name:
item.update({'title': schema_display_name})
return item
agent_req = service_gateway_agent_request(instrument_device_id, 'get_capabilities', params={})
if isinstance(agent_req, dict) and agent_req.has_key('GatewayError'): # Temp hack to catch error
return agent_req
capabilities = {}
commands = []
agent_param_names = []
resource_param_names = []
agent_schema = {}
resource_schema = {}
for param in agent_req:
cap_type = param['cap_type']
if cap_type == 1 or cap_type == 3:
commands.append(param)
if cap_type == 2:
agent_param_names.append(param['name'])
if param['schema']:
agent_schema.update({ param['name']: _to_form_schema(param['schema']['type'], param['schema']['visibility'], param['schema']['display_name'])})
if cap_type == 4:
# check for schema
if 'schema' in param:
try:
resource_param_names.append(param['name'])
resource_schema.update({ param['name']: _to_form_schema(param['schema']['value']['type'], param['schema']['visibility'], None)})
except Exception, e:
app.logger.error("REQUIRED SCHEMA NOT COMPLETE: %s %s " % (param, e))
else:
app.logger.error("MISSING RESOURCE SCHEMA: %s " % param)
if agent_param_names:
agent_params = service_gateway_agent_request(instrument_device_id, 'get_agent', params={'params': agent_param_names})
if resource_param_names:
resource_params = service_gateway_agent_request(instrument_device_id, 'get_resource', params={'params': resource_param_names})
capabilities.update({'resource_params': resource_params})
capabilities.update({'agent_schema': agent_schema})
capabilities.update({'resource_schema': resource_schema})
capabilities.update({'agent_params': agent_params})
capabilities.update({'original': agent_req})
capabilities.update({'commands': commands})
return capabilities
@staticmethod
def taskable_execute(resource_id, command):
command_obj = {'type_': 'AgentCommand', 'command': command, 'args':[], 'kwargs':{}}
taskable = service_gateway_post('resource_management', 'execute_resource', params={'resource_id':resource_id, 'command': command_obj})
return taskable
@staticmethod
def tasktable_get_capabilities(resource_id):
taskable = service_gateway_get('resource_management', 'get_capabilities', raw_return=True, params={'resource_id':resource_id})
# commands = [t for t in taskable if t['cap_type'] == 3]
capabilities = {'resource_params': {}, 'commands': []}
resource_param_names = []
for t in taskable:
if t['cap_type'] == 3:
capabilities['commands'].append(t)
elif t['cap_type'] == 4:
resource_param_names.append(t['name'])
if resource_param_names:
resource_params_request = service_gateway_get('resource_management', 'get_resource', params={'resource_id': resource_id, 'params': resource_param_names})
for k,v in resource_params_request.iteritems():
if k in resource_param_names:
capabilities['resource_params'].update({k:v})
return capabilities
@staticmethod
def set_agent(device_id, params):
agent_request = service_gateway_agent_request(device_id, 'set_agent', params={'params': params})
return agent_request
@staticmethod
def set_resource(device_id, params):
# TEMP: hack to convert '0.0' strings to workaround JavaScript/JSON.
# Also, skips null values until param schema is available.
new_params = {}
for k,v in params.iteritems():
if k in BLACKLIST or not v:
continue
if isinstance(v, unicode) and '.' in v:
new_params.update({k: float(v.strip())})
else:
new_params.update({k: v})
agent_request = service_gateway_agent_request(device_id, 'set_resource', params={'params': new_params})
return agent_request
# PLATFORM COMMAND
# ---------------------------------------------------------------------------
@staticmethod
def platform_agent_start(platform_agent_instance_id):
agent_request = service_gateway_get('instrument_management', 'start_platform_agent_instance', params={'platform_agent_instance_id': platform_agent_instance_id})
return agent_request
@staticmethod
def platform_agent_stop(platform_agent_instance_id):
agent_request = service_gateway_get('instrument_management', 'stop_platform_agent_instance', params={'platform_agent_instance_id': platform_agent_instance_id})
return agent_request
@staticmethod