-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathresource.py
executable file
·1900 lines (1455 loc) · 70.1 KB
/
resource.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
# -*- coding: utf-8 -*-
###
# (C) Copyright [2021] Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
from future.utils import lmap
standard_library.install_aliases()
import logging
import os
from copy import deepcopy
from urllib.parse import quote
from functools import partial
from hpeOneView.resources.task_monitor import TaskMonitor
from hpeOneView import exceptions
RESOURCE_CLIENT_RESOURCE_WAS_NOT_PROVIDED = 'Resource was not provided'
RESOURCE_CLIENT_INVALID_FIELD = 'Invalid field was provided'
RESOURCE_CLIENT_INVALID_ID = 'Invalid id was provided'
RESOURCE_CLIENT_UNKNOWN_OBJECT_TYPE = 'Unknown object type'
UNRECOGNIZED_URI = 'Unrecognized URI for this resource'
RESOURCE_CLIENT_TASK_EXPECTED = "Failed: Expected a TaskResponse."
RESOURCE_ID_OR_URI_REQUIRED = 'It is required to inform the Resource ID or URI.'
UNAVAILABLE_METHOD = "Method is not available for this resource"
MISSING_UNIQUE_IDENTIFIERS = "Missing unique identifiers(URI/Name) for the resource"
RESOURCE_DOES_NOT_EXIST = "Resource does not exist with the provided unique identifiers"
logger = logging.getLogger(__name__)
class EnsureResourceClient(object):
"""Decorator class to update the resource data."""
def __init__(self, method=None, update_data=False):
self.method = method
self.update_data = update_data
def __get__(self, obj, objtype):
return partial(self.__call__, obj)
def __call__(self, obj, *args, **kwargs):
if self.method:
obj.ensure_resource_data(update_data=self.update_data)
return self.method(obj, *args, **kwargs)
def wrap(*args, **kwargs):
args[0].ensure_resource_data(update_data=self.update_data)
return obj(*args, **kwargs)
return wrap
# Decorator to ensure the resource client
ensure_resource_client = EnsureResourceClient
class Resource(object):
"""Base class for OneView resources.
Args:
connection: OneView connection object
data: Resource data
"""
# Base URI for the rest calls
URI = '/rest'
# Unique identifiers to query the resource
UNIQUE_IDENTIFIERS = ['uri', 'name']
# Default values required for the api versions
DEFAULT_VALUES = {}
def __init__(self, connection, data=None):
self._connection = connection
self._task_monitor = TaskMonitor(connection)
self._helper = ResourceHelper(self.URI,
self._connection,
self._task_monitor)
# Resource data
self.data = data if data else {}
# Merge resoure data with the default values
self._merge_default_values()
def ensure_resource_data(self, update_data=False):
"""Retrieves data from OneView and updates resource object.
Args:
update_data: Flag to update resource data when it is required.
"""
# Check for unique identifier in the resource data
if not any(key in self.data for key in self.UNIQUE_IDENTIFIERS):
raise exceptions.HPEOneViewMissingUniqueIdentifiers(MISSING_UNIQUE_IDENTIFIERS)
# Returns if data update is not required
if not update_data:
return
resource_data = None
if 'uri' in self.UNIQUE_IDENTIFIERS and self.data.get('uri'):
resource_data = self._helper.do_get(self.data['uri'])
else:
for identifier in self.UNIQUE_IDENTIFIERS:
identifier_value = self.data.get(identifier)
if identifier_value:
result = self.get_by(identifier, identifier_value)
if result and isinstance(result, list):
resource_data = result[0]
break
if resource_data:
self.data.update(resource_data)
else:
raise exceptions.HPEOneViewResourceNotFound(RESOURCE_DOES_NOT_EXIST)
@ensure_resource_client
def refresh(self):
"""Helps to get the latest resource data from the server."""
self.data = self._helper.do_get(self.data["uri"])
def get_all(self, start=0, count=-1, filter='', sort=''):
"""Gets all items according with the given arguments.
Args:
start: The first item to return, using 0-based indexing.
If not specified, the default is 0 - start with the first available item.
count: The number of resources to return. A count of -1 requests all items (default).
filter (list or str): A general filter/query string to narrow the list of items returned. The default is no
filter; all resources are returned.
sort: The sort order of the returned data set. By default, the sort order is based on create time with the
oldest entry first.
Returns:
list: A list of items matching the specified filter.
"""
result = self._helper.get_all(start=start, count=count, filter=filter, sort=sort)
return result
def create(self, data=None, uri=None, timeout=-1, custom_headers=None, force=False):
"""Makes a POST request to create a resource when a request body is required.
Args:
data: Additional fields can be passed to create the resource.
uri: Resouce uri
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
custom_headers: Allows set specific HTTP headers.
Returns:
Created resource.
"""
if not data:
data = {}
default_values = self._get_default_values()
data = self._helper.update_resource_fields(data, default_values)
logger.debug('Create (uri = %s, resource = %s)' % (uri, str(data)))
resource_data = self._helper.create(data, uri, timeout, custom_headers, force)
new_resource = self.new(self._connection, resource_data)
return new_resource
@ensure_resource_client
def delete(self, timeout=-1, custom_headers=None, force=False):
"""Deletes current resource.
Args:
timeout: Timeout in seconds.
custom_headers: Allows to set custom http headers.
force: Flag to force the operation.
"""
uri = self.data['uri']
logger.debug("Delete resource (uri = %s)" % (str(uri)))
return self._helper.delete(uri, timeout=timeout,
custom_headers=custom_headers, force=force)
@ensure_resource_client(update_data=True)
def update(self, data=None, timeout=-1, custom_headers=None, force=False):
"""Makes a PUT request to update a resource when a request body is required.
Args:
data:
Data to update the resource.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
custom_headers:
Allows to add custom HTTP headers.
force:
Force the update operation.
Returns:
A dict with the updated resource data.
"""
uri = self.data['uri']
resource = deepcopy(self.data)
resource.update(data)
logger.debug('Update async (uri = %s, resource = %s)' %
(uri, str(resource)))
self.data = self._helper.update(resource, uri, force, timeout, custom_headers)
return self
def get_by(self, field, value):
"""Get the resource by passing a field and its value.
Note:
This function uses get_all passing a filter.The search is case-insensitive.
Args:
field: Field name to filter.
value: Value to filter.
Returns:
dict
"""
if not field:
logger.exception(RESOURCE_CLIENT_INVALID_FIELD)
raise ValueError(RESOURCE_CLIENT_INVALID_FIELD)
filter = "\"{0}='{1}'\"".format(field, value)
results = self.get_all(filter=filter)
# Workaround when the OneView filter does not work, it will filter again
if "." not in field:
# This filter only work for the first level
results = [item for item in results if str(item.get(field, "")).lower() == value.lower()]
return results
def get_by_name(self, name):
"""Retrieves a resource by its name.
Args:
name: Resource name.
Returns:
Resource object or None if resource does not exist.
"""
result = self.get_by("name", name)
if result:
data = result[0]
new_resource = self.new(self._connection, data)
else:
new_resource = None
return new_resource
# Sometimes get_all() with filters are not returning correct values, so added this method to overcome that issue
def get_by_field(self, field, value):
"""Retrieves a resource by its field.
Args:
field: Resource field name.
value: Resource field value.
Returns:
Resource object or None if resource does not exist.
"""
if not field:
logger.exception(RESOURCE_CLIENT_INVALID_FIELD)
raise ValueError(RESOURCE_CLIENT_INVALID_FIELD)
results = self.get_all()
# This filter only work for the first level
result = [item for item in results if str(item.get(field, "")).lower() == value.lower()]
if result:
data = result[0]
new_resource = self.new(self._connection, data)
else:
new_resource = None
return new_resource
def get_by_uri(self, uri):
"""Retrieves a resource by its URI
Args:
uri: URI of the resource
Returns:
Resource object
"""
self._helper.validate_resource_uri(uri)
data = self._helper.do_get(uri)
if data:
new_resource = self.new(self._connection, data)
else:
new_resource = None
return new_resource
def get_by_id(self, id):
"""Retrieves a resource by its id.
Args:
id: id of Resource
Returns:
Resource object or None if resource does not exist.
"""
uri = "{}/{}".format(self.URI, id)
self._helper.validate_resource_uri(uri)
data = self._helper.do_get(uri)
if data:
new_resource = self.new(self._connection, data)
else:
new_resource = None
return new_resource
def _get_default_values(self, default_values=None):
"""Gets the default values set for a resource"""
if not default_values:
default_values = self.DEFAULT_VALUES
if default_values:
api_version = str(self._connection._apiVersion)
values = default_values.get(api_version, {}).copy()
else:
values = {}
return values
def _merge_default_values(self):
"""Merge default values with resource data."""
values = self._get_default_values()
for key, value in values.items():
if not self.data.get(key):
self.data[key] = value
@classmethod
def new(cls, connection, data):
"""Returns a new resource object"""
return cls(connection, data)
class ResourceHelper(object):
def __init__(self, base_uri, connection, task_monitor):
self._base_uri = base_uri
self._connection = connection
self._task_monitor = task_monitor
def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fields='', uri=None, scope_uris='', custom_headers=None,
name_prefix='', category=[], childLimit=0, topCount=0,):
"""Gets all items according with the given arguments.
Args:
start: The first item to return, using 0-based indexing.
If not specified, the default is 0 - start with the first available item.
count: The number of resources to return. A count of -1 requests all items (default).
filter (list or str): A general filter/query string to narrow the list of items returned. The default is no
filter; all resources are returned.
query: A single query parameter can do what would take multiple parameters or multiple GET requests using
filter. Use query for more complex queries. NOTE: This parameter is experimental for OneView 2.0.
sort: The sort order of the returned data set. By default, the sort order is based on create time with the
oldest entry first.
view:
Returns a specific subset of the attributes of the resource or collection by specifying the name of a
predefined view. The default view is expand (show all attributes of the resource and all elements of
the collections or resources).
fields:
Name of the fields.
uri:
A specific URI (optional)
scope_uris:
An expression to restrict the resources returned according to the scopes to
which they are assigned.
custom_headers: custom headers
Returns:
list: A list of items matching the specified filter.
"""
if not uri:
uri = self._base_uri
uri = self.build_query_uri(uri=uri,
start=start,
count=count,
filter=filter,
query=query,
sort=sort,
view=view,
fields=fields,
scope_uris=scope_uris,
name_prefix=name_prefix,
category=category,
childLimit=childLimit,
topCount=topCount)
logger.debug('Getting all resources with uri: {0}'.format(uri))
return self.do_requests_to_getall(uri, count, custom_headers=custom_headers)
def delete_all(self, filter, force=False, timeout=-1):
"""
Deletes all resources from the appliance that match the provided filter.
Args:
filter:
A general filter/query string to narrow the list of items deleted.
force:
If set to true, the operation completes despite any problems with network connectivity or errors
on the resource itself. The default is false.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
bool: Indicates if the resources were successfully deleted.
"""
uri = "{}?filter={}&force={}".format(self._base_uri, quote(filter), force)
logger.debug("Delete all resources (uri = %s)" % uri)
return self.delete(uri)
def create(self, data=None, uri=None, timeout=-1, custom_headers=None, force=False):
"""Makes a POST request to create a resource when a request body is required.
Args:
data: Additional fields can be passed to create the resource.
uri: Resouce uri
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
custom_headers: Allows set specific HTTP headers.
Returns:
Created resource.
"""
if not uri:
uri = self._base_uri
if force:
uri += '?force={}'.format(force)
logger.debug('Create (uri = %s, resource = %s)' % (uri, str(data)))
return self.do_post(uri, data, timeout, custom_headers)
def delete(self, uri, force=False, timeout=-1, custom_headers=None):
"""Deletes current resource.
Args:
force: Flag to delete the resource forcefully, default is False.
timeout: Timeout in seconds.
custom_headers: Allows to set custom http headers.
"""
if force:
uri += '?force=True'
logger.debug("Delete resource (uri = %s)" % (str(uri)))
task, body = self._connection.delete(uri, custom_headers=custom_headers)
if not task:
# 204 NO CONTENT
# Successful return from a synchronous delete operation.
return True
task = self._task_monitor.wait_for_task(task, timeout=timeout)
return task
def update(self, resource, uri=None, force=False, timeout=-1, custom_headers=None):
"""Makes a PUT request to update a resource when a request body is required.
Args:
resource:
Data to update the resource.
uri:
Resource uri
force:
If set to true, the operation completes despite any problems
with network connectivity or errors on the resource itself. The default is false.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
custom_headers:
Allows to add custom HTTP headers.
Returns:
A dict with the updated resource data.
"""
logger.debug('Update async (uri = %s, resource = %s)' %
(uri, str(resource)))
if not uri:
uri = resource['uri']
if force:
uri += '?force=True'
return self.do_put(uri, resource, timeout, custom_headers)
def update_with_zero_body(self, uri, timeout=-1, custom_headers=None):
"""Makes a PUT request to update a resource when no request body is required.
Args:
uri: Allows to use a different URI other than resource URI
timeout: Timeout in seconds. Wait for task completion by default.
The timeout does not abort the operation in OneView; it just stops waiting for its completion.
custom_headers: Allows to set custom HTTP headers.
Returns:
A dict with updated resource data.
"""
logger.debug('Update with zero length body (uri = %s)' % uri)
return self.do_put(uri, None, timeout, custom_headers)
def create_report(self, uri, timeout=-1):
"""
Creates a report and returns the output.
Args:
uri: URI
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
list:
"""
logger.debug('Creating Report')
task, _ = self._connection.post(uri, {})
if not task:
raise exceptions.HPEOneViewException(RESOURCE_CLIENT_TASK_EXPECTED)
task = self._task_monitor.get_completed_task(task, timeout)
return task['taskOutput']
def get_collection(self, uri=None, filter='', path=''):
"""Retrieves a collection of resources.
Use this function when the 'start' and 'count' parameters are not allowed in the GET call.
Otherwise, use get_all instead.
Optional filtering criteria may be specified.
Args:
filter (list or str): General filter/query string.
path (str): path to be added with base URI
Returns:
Collection of the requested resource.
"""
if not uri:
uri = self._base_uri
if filter:
filter = self.make_query_filter(filter)
filter = "?" + filter[1:]
uri = "{uri}{path}{filter}".format(uri=uri, path=path, filter=filter)
logger.debug('Get resource collection (uri = %s)' % uri)
response = self._connection.get(uri)
return self.get_members(response)
def build_query_uri(self, uri=None, start=0, count=-1, filter='', query='', sort='', view='', fields='', scope_uris='',
name_prefix='', category=[], childLimit=0, topCount=0):
"""Builds the URI from given parameters.
More than one request can be send to get the items, regardless the query parameter 'count', because the actual
number of items in the response might differ from the requested count. Some types of resource have a limited
number of items returned on each call. For those resources, additional calls are made to the API to retrieve
any other items matching the given filter. The actual number of items can also differ from the requested call
if the requested number of items would take too long.
The use of optional parameters for OneView 2.0 is described at:
http://h17007.www1.hpe.com/docs/enterprise/servers/oneview2.0/cic-api/en/api-docs/current/index.html
Note:
Single quote - "'" - inside a query parameter is not supported by OneView API.
Args:
start: The first item to return, using 0-based indexing.
If not specified, the default is 0 - start with the first available item.
count: The number of resources to return. A count of -1 requests all items (default).
filter (list or str): A general filter/query string to narrow the list of items returned. The default is no
filter; all resources are returned.
query: A single query parameter can do what would take multiple parameters or multiple GET requests using
filter. Use query for more complex queries. NOTE: This parameter is experimental for OneView 2.0.
sort: The sort order of the returned data set. By default, the sort order is based on create time with the
oldest entry first.
view: Returns a specific subset of the attributes of the resource or collection by specifying the name of a
predefined view. The default view is expand (show all attributes of the resource and all elements of
the collections or resources).
fields: Name of the fields.
uri: A specific URI (optional)
scope_uris: An expression to restrict the resources returned according to the scopes to
which they are assigned.
name_prefix: Filters the resource returned by the given prefix.
Returns:
uri: The complete uri
"""
if filter:
filter = self.make_query_filter(filter)
if query:
query = "&query=" + quote(query)
if sort:
sort = "&sort=" + quote(sort)
if view:
view = "&view=" + quote(view)
if fields:
fields = "&fields=" + quote(fields)
if scope_uris:
scope_uris = "&scopeUris=" + quote(scope_uris)
if name_prefix:
name_prefix = "&namePrefix=" + quote(name_prefix)
categories = ''
if category:
for cat in category:
categories = categories + "&category=" + quote(cat)
if childLimit:
childLimit = "&childLimit=" + str(childLimit)
if topCount:
topCount = "&topCount=" + str(topCount)
path = uri if uri else self._base_uri
self.validate_resource_uri(path)
symbol = '?' if '?' not in path else '&'
uri = "{0}{1}start={2}&count={3}{4}{5}{6}{7}{8}{9}{10}{11}".format(path, symbol, start, count, filter, query, sort,
view, fields, scope_uris, name_prefix, categories)
return uri
def build_uri_with_query_string(self, kwargs, sufix_path='', uri=None):
if not uri:
uri = self._base_uri
query_string = '&'.join('{}={}'.format(key, kwargs[key]) for key in sorted(kwargs))
return uri + sufix_path + '?' + query_string
def build_uri(self, id_or_uri):
"""Helps to build the URI from resource id and validate the URI.
Args:
id_or_uri: ID/URI of the resource.
Returns:
Returns a valid resource URI
"""
if not id_or_uri:
logger.exception(RESOURCE_CLIENT_INVALID_ID)
raise ValueError(RESOURCE_CLIENT_INVALID_ID)
if "/" in id_or_uri:
self.validate_resource_uri(id_or_uri)
return id_or_uri
else:
return self._base_uri + "/" + id_or_uri
def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=None, subresource_path=''):
"""Helps to build a URI with resource path and its sub resource path.
Args:
resoure_id_or_uri: ID/URI of the main resource.
subresource_id__or_uri: ID/URI of the sub resource.
subresource_path: Sub resource path to be added with the URI.
Returns:
Returns URI
"""
if subresource_id_or_uri and "/" in subresource_id_or_uri:
return subresource_id_or_uri
else:
if not resource_id_or_uri:
raise exceptions.HPEOneViewValueError(RESOURCE_ID_OR_URI_REQUIRED)
resource_uri = self.build_uri(resource_id_or_uri)
uri = "{}/{}/{}".format(resource_uri, subresource_path, str(subresource_id_or_uri or ''))
uri = uri.replace("//", "/")
if uri.endswith("/"):
uri = uri[:-1]
return uri
def validate_resource_uri(self, path):
"""Helper method to validate URI of the resource."""
if self._base_uri not in path:
logger.exception('Get by uri : unrecognized uri: (%s)' % path)
raise exceptions.HPEOneViewUnknownType(UNRECOGNIZED_URI)
def make_query_filter(self, filters):
"""Helper method to build filter query parameter."""
if isinstance(filters, list):
formated_filter = "&filter=".join(quote(f) for f in filters)
else:
formated_filter = quote(filters)
return "&filter=" + formated_filter
def get_members(self, mlist):
"""Get members from list of resources"""
if mlist and mlist.get('members'):
return mlist['members']
else:
return []
def update_resource_fields(self, data, data_to_add):
"""Update resource data with new fields.
Args:
data: resource data
data_to_update: dict of data to update resource data
Returnes:
Returnes dict
"""
for key, value in data_to_add.items():
if not data.get(key):
data[key] = value
return data
def do_requests_to_getall(self, uri, requested_count, custom_headers=None):
"""Helps to make http request for get_all method.
Note:
This method will be checking for the pagination URI in the response
and make request to pagination URI to get all the resources.
"""
items = []
while uri:
logger.debug('Making HTTP request to get all resources. Uri: {0}'.format(uri))
response = self._connection.get(uri, custom_headers=custom_headers)
members = self.get_members(response)
items += members
logger.debug("Response getAll: nextPageUri = {0}, members list length: {1}".format(uri, str(len(members))))
uri = self.get_next_page(response, items, requested_count)
logger.debug('Total # of members found = {0}'.format(str(len(items))))
return items
def get_next_page(self, response, items, requested_count):
"""Returns next page URI."""
next_page_is_empty = response.get('nextPageUri') is None
has_different_next_page = not response.get('uri') == response.get('nextPageUri')
has_next_page = not next_page_is_empty and has_different_next_page
if len(items) >= requested_count and requested_count != -1:
return None
return response.get('nextPageUri') if has_next_page else None
def do_get(self, uri):
"""Helps to make get requests
Args:
uri: URI of the resource
Returns:
Returns: Returns the resource data
"""
self.validate_resource_uri(uri)
return self._connection.get(uri)
def do_post(self, uri, resource, timeout, custom_headers):
"""Helps to make post requests.
Args:
uri: URI of the resource.
resource: Resource data to post.
timeout: Time out for the request in seconds.
cutom_headers: Allows to add custom http headers.
Returns:
Retunrs Task object.
"""
self.validate_resource_uri(uri)
task, entity = self._connection.post(uri, resource, custom_headers=custom_headers)
if not task:
return entity
return self._task_monitor.wait_for_task(task, timeout)
def do_put(self, uri, resource, timeout, custom_headers):
"""Helps to make put requests.
Args:
uri: URI of the resource
timeout: Time out for the request in seconds.
custom_headers: Allows to set custom http headers.
Retuns:
Returns Task object
"""
self.validate_resource_uri(uri)
task, body = self._connection.put(uri, resource, custom_headers=custom_headers)
if not task:
return body
return self._task_monitor.wait_for_task(task, timeout)
def add_new_fields(data, data_to_add):
"""Update resource data with new fields.
Args:
data: resource data
data_to_update: dict of data to update resource data
Returnes:
Returnes dict
"""
for key, value in data_to_add.items():
if not data.get(key):
data[key] = value
return data
class ResourcePatchMixin(object):
@ensure_resource_client
def patch(self, operation, path, value, custom_headers=None, timeout=-1):
"""Uses the PATCH to update a resource.
Only one operation can be performed in each PATCH call.
Args
operation: Patch operation
path: Path
value: Value
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
custom_headers: Allows to add custom http headers.
Returns:
Updated resource.
"""
patch_request_body = [{'op': operation, 'path': path, 'value': value}]
resource_uri = self.data['uri']
self.data = self.patch_request(resource_uri,
body=patch_request_body,
custom_headers=custom_headers,
timeout=timeout)
return self
def patch_request(self, uri, body, custom_headers=None, timeout=-1):
"""Uses the PATCH to update a resource.
Only one operation can be performed in each PATCH call.
Args:
body (list): Patch request body
timeout (int): Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
custom_headers (dict): Allows to add custom http headers.
Returns:
Updated resource.
"""
logger.debug('Patch resource (uri = %s, data = %s)' % (uri, body))
if not custom_headers:
custom_headers = {}
if self._connection._apiVersion >= 300 and 'Content-Type' not in custom_headers:
custom_headers['Content-Type'] = 'application/json-patch+json'
task, entity = self._connection.patch(uri, body, custom_headers=custom_headers)
if not task:
return entity
return self._task_monitor.wait_for_task(task, timeout)
class ResourceFileHandlerMixin(object):
def upload(self, file_path, uri=None, timeout=-1):
"""Makes a multipart request.
Args:
file_path: File to upload.
uri: A specific URI (optional).
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
dict: Response body.
"""
if not uri:
uri = self.URI
upload_file_name = os.path.basename(file_path)
task, entity = self._connection.post_multipart_with_response_handling(uri, file_path, upload_file_name)
if not task:
return entity
return self._task_monitor.wait_for_task(task, timeout)
def download(self, uri, file_path):
"""Downloads the contents of the requested URI to a stream.
Args:
uri: URI
file_path: File path destination
Returns:
bool: Indicates if the file was successfully downloaded.
"""
with open(file_path, 'wb') as file:
return self._connection.download_to_stream(file, uri)
class ResourceUtilizationMixin(object):
def get_utilization(self, fields=None, filter=None, refresh=False, view=None):
"""Retrieves historical utilization data for the specified resource, metrics, and time span.
Args:
fields: Name of the supported metric(s) to be retrieved in the format METRIC[,METRIC]...
If unspecified, all metrics supported are returned.
filter (list or str): Filters should be in the format FILTER_NAME=VALUE[,FILTER_NAME=VALUE]...
E.g.: 'startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z'
startDate
Start date of requested starting time range in ISO 8601 format. If omitted, the startDate is
determined by the endDate minus 24 hours.
endDate
End date of requested starting time range in ISO 8601 format. When omitted, the endDate includes
the latest data sample available.
If an excessive number of samples would otherwise be returned, the results will be segmented. The
caller is responsible for comparing the returned sliceStartTime with the requested startTime in the
response. If the sliceStartTime is greater than the oldestSampleTime and the requested start time,
the caller is responsible for repeating the request with endTime set to sliceStartTime to obtain the
next segment. This process is repeated until the full data set is retrieved.
If the resource has no data, the UtilizationData is still returned but will contain no samples and
sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set
appropriately (null if no data is available). If the filter does not happen to overlap the data
that a resource has, then the metric history service will return null sample values for any
missing samples.
refresh: Specifies that if necessary, an additional request will be queued to obtain the most recent
utilization data from the iLO. The response will not include any refreshed data. To track the
availability of the newly collected data, monitor the TaskResource identified by the refreshTaskUri
property in the response. If null, no refresh was queued.
view: Specifies the resolution interval length of the samples to be retrieved. This is reflected in the
resolution in the returned response. Utilization data is automatically purged to stay within storage