-
Notifications
You must be signed in to change notification settings - Fork 9
/
zhmc_crypto_attachment.py
1072 lines (939 loc) · 40.7 KB
/
zhmc_crypto_attachment.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/python
# Copyright 2018-2020 IBM Corp. All Rights Reserved.
#
# 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, division, print_function)
__metaclass__ = type
# For information on the format of the ANSIBLE_METADATA, DOCUMENTATION,
# EXAMPLES, and RETURN strings, see
# http://docs.ansible.com/ansible/dev_guide/developing_modules_documenting.html
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community',
'shipped_by': 'other',
'other_repo_url': 'https://github.com/zhmcclient/zhmc-ansible-modules'
}
DOCUMENTATION = """
---
module: zhmc_crypto_attachment
version_added: "2.9.0"
short_description: Manages the attachment of crypto resources to partitions of
Z systems.
description:
- Gather facts about the attachment of crypto adapters and crypto domains to
a partition of a CPC (Z system).
- Attach a range of crypto domains and a number of crypto adapters to a
partition.
- Detach all crypto domains and all crypto adapters from a partition.
author:
- Andreas Maier (@andy-maier)
- Andreas Scheuring (@scheuran)
requirements:
- Access to the WS API of the HMC of the targeted Z system
(see :term:`HMC API`). The targeted Z system must be in the Dynamic
Partition Manager (DPM) operational mode.
- Python package zhmcclient >=0.20.0
options:
hmc_host:
description:
- The hostname or IP address of the HMC.
type: str
required: true
hmc_auth:
description:
- The authentication credentials for the HMC, as a dictionary of
C(userid), C(password).
type: dict
required: true
suboptions:
userid:
description:
- The userid (username) for authenticating with the HMC.
type: str
required: true
password:
description:
- The password for authenticating with the HMC.
type: str
required: true
cpc_name:
description:
- The name of the CPC that has the partition and the crypto adapters.
type: str
required: true
partition_name:
description:
- The name of the partition to which the crypto domains and crypto
adapters are attached.
type: str
required: true
state:
description:
- "The desired state for the attachment:"
- "* C(attached): Ensures that the specified number of crypto adapters
of the specified crypto type, and the specified range of domain index
numbers in the specified access mode are attached to the partition."
- "* C(detached): Ensures that no crypto adapter and no crypto domains
are attached to the partition."
- "* C(facts): Does not change anything on the attachment and returns
the crypto configuration of the partition."
type: str
required: true
choices: ['attached', 'detached', 'facts']
adapter_count:
description:
- "Only for C(state=attach): The number of crypto adapters the partition
needs to have attached.
The special value -1 means all adapters of the desired crypto type in
the CPC.
The C(adapter_names) and C(adapter_count) parameters are mutually
exclusive; if neither is specified the default for C(adapter_count)
applies."
type: int
required: false
default: -1
adapter_names:
description:
- "Only for C(state=attach): The names of the crypto adapters the
partition needs to have attached.
The C(adapter_names) and C(adapter_count) parameters are mutually
exclusive; if neither is specified the default for C(adapter_count)
applies."
type: list
elements: str
required: false
default: []
domain_range:
description:
- "Only for C(state=attach): The domain range the partition needs to have
attached, as a tuple of integers (min, max) that specify the inclusive
range of domain index numbers.
Other domains attached to the partition remain unchanged.
The special value -1 for the max item means the maximum supported
domain index number."
type: list
elements: int
required: false
default: [0,-1]
access_mode:
description:
- "Only for C(state=attach): The access mode in which the crypto domains
specified in C(domain_range) need to be attached."
type: str
required: false
default: 'usage'
choices: ['usage', 'control']
crypto_type:
description:
- "Only for C(state=attach): The crypto type of the crypto adapters that
will be considered for attaching."
type: str
required: false
default: 'ep11'
choices: ['ep11', 'cca', 'acc']
log_file:
description:
- "File path of a log file to which the logic flow of this module as well
as interactions with the HMC are logged. If null, logging will be
propagated to the Python root logger."
type: str
required: false
default: null
faked_session:
description:
- "A C(zhmcclient_mock.FakedSession) object that has a mocked HMC set up.
If not null, this session will be used instead of connecting to the
HMC specified in C(hmc_host). This is used for testing purposes only."
required: false
type: raw
default: null
"""
EXAMPLES = """
---
# Note: The following examples assume that some variables named 'my_*' are set.
- name: Gather facts about the crypto configuration of a partition
zhmc_crypto_attachment:
hmc_host: "{{ my_hmc_host }}"
hmc_auth: "{{ my_hmc_auth }}"
cpc_name: "{{ my_cpc_name }}"
partition_name: "{{ my_partition_name }}"
state: facts
register: crypto1
- name: Ensure domain 0 on all ep11 adapters is attached in usage mode
zhmc_crypto_attachment:
hmc_host: "{{ my_hmc_host }}"
hmc_auth: "{{ my_hmc_auth }}"
cpc_name: "{{ my_cpc_name }}"
partition_name: "{{ my_first_partition_name }}"
state: attached
crypto_type: ep11
adapter_count: -1
domain_range: 0,0
access_mode: usage
- name: Ensure domains 1-max on all ep11 adapters are attached in control mode
zhmc_crypto_attachment:
hmc_host: "{{ my_hmc_host }}"
hmc_auth: "{{ my_hmc_auth }}"
cpc_name: "{{ my_cpc_name }}"
partition_name: "{{ my_first_partition_name }}"
state: attached
crypto_type: ep11
adapter_count: -1
domain_range: 1,-1
access_mode: control
- name: Ensure domains 0-max on 1 ep11 adapter are attached to in usage mode
zhmc_crypto_attachment:
hmc_host: "{{ my_hmc_host }}"
hmc_auth: "{{ my_hmc_auth }}"
cpc_name: "{{ my_cpc_name }}"
partition_name: "{{ my_second_partition_name }}"
state: attached
crypto_type: ep11
adapter_count: 1
domain_range: 0,-1
access_mode: usage
- name: Ensure domains 0-max on two specific ep11 adapters are attached
zhmc_crypto_attachment:
hmc_host: "{{ my_hmc_host }}"
hmc_auth: "{{ my_hmc_auth }}"
cpc_name: "{{ my_cpc_name }}"
partition_name: "{{ my_second_partition_name }}"
state: attached
crypto_type: ep11
adapter_names: [CRYP00, CRYP01]
domain_range: 0,-1
access_mode: usage
"""
RETURN = """
crypto_configuration:
description:
- "For C(state=detached|attached|facts), the crypto configuration of the
partition after the changes performed by the module."
returned: success
type: dict
contains:
"{name}":
description: "Partition name"
type: dict
contains:
adapters:
description: "Attached adapters"
type: dict
contains:
"{name}":
description: "Adapter name"
type: dict
contains:
name:
description: "Adapter name"
type: str
"{property}":
description: "Additional properties of the adapter,
as described in the :term:`HMC API`
(using hyphens (-) in the property names)."
domain_config:
description: "Attached crypto domains"
type: dict
contains:
"{index}":
description: "Crypto domain index"
type: dict
contains:
"{access_mode}":
description: "Access mode ('control' or 'usage')."
type: str
usage_domains:
description: "Domain index numbers of the crypto domains attached
in usage mode"
type: list
elements: str
control_domains:
description: "Domain index numbers of the crypto domains attached
in control mode"
type: list
elements: str
changes:
description:
- "For C(state=detached|attached|facts), a dictionary with the changes
performed."
returned: success
type: dict
contains:
added-adapters:
description: "Names of the adapters that were added to the partition"
type: list
elements: str
added-domains:
description: "Domain index numbers of the crypto domains that were added
to the partition"
type: list
elements: str
"""
import logging # noqa: E402
import traceback # noqa: E402
from ansible.module_utils.basic import AnsibleModule # noqa: E402
from ..module_utils.common import log_init, Error, ParameterError, \
get_hmc_auth, get_session, missing_required_lib # noqa: E402
try:
import requests.packages.urllib3
IMP_URLLIB3 = True
except ImportError:
IMP_URLLIB3 = False
IMP_URLLIB3_ERR = traceback.format_exc()
try:
import zhmcclient
IMP_ZHMCCLIENT = True
except ImportError:
IMP_ZHMCCLIENT = False
IMP_ZHMCCLIENT_ERR = traceback.format_exc()
# Python logger name for this module
LOGGER_NAME = 'zhmc_crypto_attachment'
LOGGER = logging.getLogger(LOGGER_NAME)
# Conversion of crypto types between module parameter values and HMC values
CRYPTO_TYPES_MOD2HMC = {
'acc': 'accelerator',
'cca': 'cca-coprocessor',
'ep11': 'ep11-coprocessor',
}
# Conversion of access modes between module parameter values and HMC values
ACCESS_MODES_MOD2HMC = {
'usage': 'control-usage',
'control': 'control',
}
ACCESS_MODES_HMC2MOD = {
'control-usage': 'usage',
'control': 'control',
}
def get_partition_config(partition, all_adapters):
"""
Return the result of the module by inspecting the current crypto
config. Used for all 'state' parameter values.
Parameters:
partition: Partition object for target partition
all_adapters: List of Adapter objects for all crypto adapters in the CPC
"""
# result items
adapters = dict() # adapter name: adapter properties
domain_config = dict() # domain index: access mode
usage_domains = list() # domains attached in usage mode
control_domains = list() # domains attached in control mode
partition.pull_full_properties() # Make sure it contains the changes
partition_config = partition.get_property('crypto-configuration')
if partition_config:
adapter_uris = partition_config['crypto-adapter-uris']
for a in all_adapters:
if a.uri in adapter_uris:
adapters[a.name] = a.properties
for dc in partition_config['crypto-domain-configurations']:
di = int(dc['domain-index'])
am = ACCESS_MODES_HMC2MOD[dc['access-mode']]
domain_config[di] = am
if am == 'control':
control_domains.append(di)
else:
if am != 'usage':
raise AssertionError("am={0}".format(am))
usage_domains.append(di)
result = dict()
result[partition.name] = dict()
partition_result = result[partition.name]
partition_result['adapters'] = adapters
partition_result['domain_config'] = domain_config
partition_result['usage_domains'] = usage_domains
partition_result['control_domains'] = control_domains
return result
def get_conflicting_domains(
desired_domains, hmc_access_mode, adapter, partition,
all_crypto_config, all_partitions):
"""
Internal function that determines those domains from the desired domains
on a particular adapter that cannot be attached to a particular partition
in the desired mode because they are already attached to other partitions
in a mode that prevents that.
"""
conflicting_domains = dict()
if adapter.uri in all_crypto_config:
domains_dict = all_crypto_config[adapter.uri]
for di in desired_domains:
if di in domains_dict:
# The domain is already attached to some
# partition(s) in some access mode
for am, p_uri in domains_dict[di]:
if am == 'control':
# An attachment in control mode does not
# prevent additional attachments
continue
if p_uri == partition.uri and \
am == hmc_access_mode:
# This is our target partition, and the
# domain is already attached in the desired
# mode.
continue
p = all_partitions[p_uri]
conflicting_domains[di] = (am, p.name)
return conflicting_domains
def ensure_attached(params, check_mode):
"""
Ensure that the specified crypto adapters and crypto domains are attached
to the target partition.
Raises:
ParameterError: An issue with the module parameters.
Error: Other errors during processing.
zhmcclient.Error: Any zhmcclient exception can happen.
"""
# Note: Defaults specified in argument_spec will be set in params dict
host = params['hmc_host']
userid, password = get_hmc_auth(params['hmc_auth'])
cpc_name = params['cpc_name']
partition_name = params['partition_name']
adapter_count = params['adapter_count']
adapter_names = params['adapter_names']
domain_range = params['domain_range']
access_mode = params['access_mode']
crypto_type = params['crypto_type']
faked_session = params.get('faked_session', None) # No default specified
try:
if len(domain_range) != 2:
raise AssertionError("len(domain_range)={0}".
format(len(domain_range)))
domain_range_lo = int(domain_range[0])
domain_range_hi = int(domain_range[1])
except (ValueError, AssertionError):
raise ParameterError(
"The 'domain_range' parameter must be a list containing two "
"integer numbers, but is: {0!r}".format(domain_range))
hmc_crypto_type = CRYPTO_TYPES_MOD2HMC[crypto_type]
hmc_access_mode = ACCESS_MODES_MOD2HMC[access_mode]
changed = False
result = dict()
result_changes = dict()
try:
session = get_session(faked_session, host, userid, password)
client = zhmcclient.Client(session)
cpc = client.cpcs.find(name=cpc_name)
partition = cpc.partitions.find(name=partition_name)
# The default exception handling is sufficient for the above.
# Determine all crypto adapters of the specified crypto type.
filter_args = {
'adapter-family': 'crypto',
'crypto-type': hmc_crypto_type,
}
all_adapters = cpc.adapters.list(filter_args=filter_args,
full_properties=True)
if not all_adapters:
raise Error("No crypto adapters of type {0!r} found on CPC {1!r} ".
format(crypto_type, cpc_name))
all_adapters_dict = {a.name: a for a in all_adapters}
# All crypto adapters in a CPC have the same number of domains
# (otherwise the concept of attaching domains across all attached
# adapters cannot work). Therefore, the max number of domains can be
# gathered from any adapter.
max_domains = all_adapters[0].maximum_crypto_domains
# Parameter checking on domain range.
# (can be done only now because it requires the max_domains).
if domain_range_hi == -1:
domain_range_hi = max_domains - 1
if domain_range_lo > domain_range_hi:
raise ParameterError(
"In the 'domain_range' parameter, the lower boundary (={0}) "
"of the range must be less than the higher boundary (={1})".
format(domain_range_lo, domain_range_hi))
# Parameter checking on adapter count and adapter names.
# (can be done only now because it requires the number of adapters).
if adapter_count != -1:
# The adapter_count parameter was specified.
# Note: Specifying it with its default value counts as not
# specified!
if not adapter_names:
# The adapter_names parameter was also specified.
raise ParameterError(
"The 'adapter_count' and 'adapter_names' parameters are "
"mutually exclusive, but both have been specified: "
"adapter_count={0!r}, adapter_names={1!r}".
format(adapter_count, adapter_names))
elif adapter_count < 1:
raise ParameterError(
"The 'adapter_count' parameter must be at least 1, but "
"is: {0}".
format(adapter_count))
elif adapter_count > len(all_adapters):
raise ParameterError(
"The 'adapter_count' parameter must not exceed the "
"number of {0} crypto adapters of type {1!r} in CPC "
"{2!r}, but is {3}".
format(len(all_adapters), crypto_type, cpc_name,
adapter_count))
elif adapter_names:
# Only the adapter_names parameter was specified.
adapter_count = len(adapter_names)
else:
# Neither of the adapter_count and adapter_names parameters were
# specified.
adapter_count = len(all_adapters)
# At this point, we have:
# - adapter_count is a valid number 1..max in all cases.
# - adapter_names is [] if the adapters do not matter or is a
# list of existing adapter names of length adapter_count.
# Verify the specified adapters exist
for aname in adapter_names:
if aname not in all_adapters_dict:
raise ParameterError(
"The 'adapter_name' parameter specifies an adapter "
"named {0!r} that does not exist in CPC {1!r}".
format(aname, cpc_name))
#
# Get current crypto config of the target partition.
#
# Domains attached to the partition, as a dict with:
# key: domain index
# value: access mode
attached_domains = dict()
# Adapters attached to the partition, as a list of Adapter objects:
attached_adapters = list()
# Adapters not attached to the partition, as a list of Adapter objects:
detached_adapters = list()
_attached_adapter_uris = list() # URIs of attached adapters
cc = partition.get_property('crypto-configuration')
if cc:
_attached_adapter_uris = cc['crypto-adapter-uris']
for dc in cc['crypto-domain-configurations']:
di = int(dc['domain-index'])
am = dc['access-mode']
LOGGER.debug(
"Crypto config of partition %r: "
"Domain %r is attached in %r mode", partition.name, di, am)
attached_domains[di] = am
for a in all_adapters:
if a.uri in _attached_adapter_uris:
LOGGER.debug(
"Crypto config of partition %r: "
"Adapter %r is attached", partition.name, a.name)
attached_adapters.append(a)
else:
LOGGER.debug(
"Crypto config of partition %r: "
"Adapter %r is not attached", partition.name, a.name)
detached_adapters.append(a)
del _attached_adapter_uris
#
# Get the current crypto config of all partitions of the CPC.
#
# This is needed because finding out whether an adapter has the right
# domains available by simply attaching it to the target partition
# and reacting to the returned status does not work for stopped
# partitions.
#
# All partition of the CPC, as a dict:
# key: partition URI
# value: Partition object
all_partitions = cpc.partitions.list()
all_partitions = dict(zip([p.uri for p in all_partitions],
all_partitions))
# Crypto config of all partitions of the CPC, as a dict with:
# key: adapter URI
# value: dict:
# key: domain index (for attached domains)
# value: list of tuple(access mode, partition URI)
all_crypto_config = dict()
for p_uri in all_partitions:
p = all_partitions[p_uri]
cc = p.get_property('crypto-configuration')
# The 'crypto-configuration' property is None or:
# {
# 'crypto-adapter-uris': ['/api/...', ...],
# 'crypto-domain-configurations': [
# {'domain-index': 15, 'access-mode': 'control-usage'},
# ...
# ]
# }
if cc:
_adapter_uris = cc['crypto-adapter-uris']
for dc in cc['crypto-domain-configurations']:
di = int(dc['domain-index'])
am = dc['access-mode']
for a_uri in _adapter_uris:
if a_uri not in all_crypto_config:
all_crypto_config[a_uri] = dict()
domains_dict = all_crypto_config[a_uri] # mutable
if di not in domains_dict:
domains_dict[di] = list()
domains_dict[di].append((am, p.uri))
#
# Determine the domains to be attached to the target partition
#
desired_domains = list(range(domain_range_lo, domain_range_hi + 1))
add_domains = list() # List of domain index numbers to be attached
for di in desired_domains:
if di not in attached_domains:
# This domain is not attached to the target partition
add_domains.append(di)
elif attached_domains[di] != hmc_access_mode:
# This domain is attached to the target partition but not in
# the desired access mode. The access mode could be extended
# from control to control+usage, but that is not implemented
# by this code here.
raise Error(
"Domain {0} is currently attached in {1!r} mode to target "
"partition {2!r}, but requested was for mode {3!r}".
format(di,
ACCESS_MODES_HMC2MOD[attached_domains[di]],
partition.name, access_mode))
else:
# This domain is attached to the target partition in the
# desired access mode
pass
# Create the domain config structure for the domains to be attached
add_domain_config = list()
for di in add_domains:
add_domain_config.append(
{'domain-index': di,
'access-mode': hmc_access_mode})
# Check that the domains to be attached to the partition are available
# on the currently attached adapters
for a in attached_adapters:
domains_dict = all_crypto_config[a.uri]
for di in add_domains:
if di in domains_dict:
for am, p_uri in domains_dict[di]:
if am != 'control' and hmc_access_mode != 'control':
# Multiple attachments conflict only when both are
# in usage mode
p = all_partitions[p_uri]
raise Error(
"Domain {0} cannot be attached in {1!r} mode "
"to target partition {2!r} because it is "
"already attached in {3!r} mode to partition "
"{4!r}".format(di, access_mode, partition.name,
ACCESS_MODES_HMC2MOD[am],
p.name))
# Make sure the desired adapters are attached to the partition
# and the desired domains are attached.
# The HMC enforces the following for non-empty crypto configurations of
# a partition:
# - In the resulting config, the partition needs to have at least one
# adapter attached.
# - In the resulting config, the partition needs to have at least one
# domain attached in usage mode.
# As a result, on an empty crypto config, the first adapter and the
# first domain(s) need to be attached at the same time.
result_changes['added-adapters'] = []
result_changes['added-domains'] = []
if not adapter_names:
# Only the number of adapters was specified so it can be any
# adapter. We accept any already attached adapter.
missing_count = max(0, adapter_count - len(attached_adapters))
if missing_count == 0 and add_domain_config:
# Adapters already sufficient, but domains need to be attached
LOGGER.debug(
"Adapters sufficient - attaching domains %r in %r mode to "
"target partition %r",
add_domains, access_mode, partition.name)
if not check_mode:
try:
partition.increase_crypto_config([], add_domain_config)
except zhmcclient.Error as exc:
raise Error(
"Attaching domains {0!r} in {1!r} mode to target "
"partition {2!r} failed: {3}".
format(add_domains, access_mode, partition.name,
exc))
changed = True
result_changes['added-domains'].extend(add_domains)
elif missing_count > 0:
# Adapters need to be attached
for adapter in detached_adapters:
if missing_count == 0:
break
# Check that the adapter has all needed domains available
conflicting_domains = get_conflicting_domains(
desired_domains, hmc_access_mode, adapter, partition,
all_crypto_config, all_partitions)
if conflicting_domains:
LOGGER.debug(
"Skipping adapter %r because the following of "
"its domains are already attached to other "
"partitions: %r",
adapter.name, conflicting_domains)
continue
LOGGER.debug(
"Attaching adapter %r and domains %r in %r mode to "
"target partition %r",
adapter.name, add_domains, access_mode, partition.name)
if not check_mode:
try:
partition.increase_crypto_config(
[adapter], add_domain_config)
except zhmcclient.Error as exc:
raise Error(
"Attaching adapter {0!r} and domains {1!r} in "
"{2!r} mode to target partition {3!r} "
"failed: {4}".
format(adapter.name, add_domains, access_mode,
partition.name, exc))
changed = True
result_changes['added-adapters'].append(adapter.name)
result_changes['added-domains'].extend(add_domains)
# Don't try to add domains again for next adapter:
add_domain_config = []
add_domains = []
missing_count -= 1
if missing_count > 0:
# Because adapters may be skipped, it is possible that
# there are not enough adapters
raise Error(
"Did not find enough crypto adapters with attachable "
"domains - missing adapters: {0}; Requested domains: "
"{1}, Access mode: {2}".
format(missing_count, desired_domains, access_mode))
else:
# Specific adapters need to be attached. We check already attached
# adapters and add the missing ones. We do not detach adapters
# that are currently attached but not in the input list.
attached_adapter_names = {a.name for a in attached_adapters}
for aname in adapter_names:
if aname not in attached_adapter_names:
adapter = all_adapters_dict[aname]
# Check that the adapter has all needed domains available
conflicting_domains = get_conflicting_domains(
desired_domains, hmc_access_mode, adapter, partition,
all_crypto_config, all_partitions)
if conflicting_domains:
raise Error(
"Crypto adapter {0!r} cannot be attached to "
"partition {1!r} because the following of "
"its domains are already attached to other "
"partitions in conflicting modes: {2!r}".
format(adapter.name, partition.name,
conflicting_domains))
if not check_mode:
try:
partition.increase_crypto_config(
[adapter], add_domain_config)
except zhmcclient.Error as exc:
raise Error(
"Attaching adapter {0!r} and domains {1!r} in "
"{2!r} mode to target partition {3!r} "
"failed: {4}".
format(adapter.name, add_domains, access_mode,
partition.name, exc))
changed = True
result_changes['added-adapters'].append(adapter.name)
result_changes['added-domains'].extend(add_domains)
# Don't try to add domains again for next adapter:
add_domain_config = []
add_domains = []
if add_domain_config:
# The desired adapters were already attached so the additional
# domains need to be added to the crypto config.
LOGGER.debug(
"Adapters were already attached to target partition %r "
"- attaching domains %r in %r mode",
partition.name, add_domains, access_mode)
if not check_mode:
try:
partition.increase_crypto_config(
[], add_domain_config)
except zhmcclient.Error as exc:
raise Error(
"Attaching domains {0!r} in {1!r} mode to "
"target partition {2!r} failed: {3}".
format(add_domains, access_mode, partition.name,
exc))
changed = True
result_changes['added-domains'].extend(add_domains)
if not check_mode:
# This is not optimal because it does not produce a result
# in check mode, but because the actual config is determined,
# instead of the artificially calculated one, it seems better
# to return no config than the unchanged actual config.
result.update(get_partition_config(partition, all_adapters))
return changed, result, result_changes
finally:
session.logoff()
def ensure_detached(params, check_mode):
"""
Ensure that the target partition has no adapters and no domains attached.
Raises:
ParameterError: An issue with the module parameters.
Error: Other errors during processing.
zhmcclient.Error: Any zhmcclient exception can happen.
"""
# Note: Defaults specified in argument_spec will be set in params dict
host = params['hmc_host']
userid, password = get_hmc_auth(params['hmc_auth'])
cpc_name = params['cpc_name']
partition_name = params['partition_name']
faked_session = params.get('faked_session', None) # No default specified
changed = False
result = dict()
result_changes = dict()
try:
session = get_session(faked_session, host, userid, password)
client = zhmcclient.Client(session)
cpc = client.cpcs.find(name=cpc_name)
partition = cpc.partitions.find(name=partition_name)
# The default exception handling is sufficient for the above.
# Determine all crypto adapters of any crypto type
filter_args = {
'adapter-family': 'crypto',
}
all_adapters = cpc.adapters.list(filter_args=filter_args,
full_properties=True)
cc = partition.get_property('crypto-configuration')
# The 'crypto-configuration' property is None or:
# {
# 'crypto-adapter-uris': ['/api/...', ...],
# 'crypto-domain-configurations': [
# {'domain-index': 15, 'access-mode': 'control-usage'},
# ...
# ]
# }
if cc:
attached_adapter_uris = cc['crypto-adapter-uris']
remove_adapters = []
remove_adapter_names = []
for a in all_adapters:
if a.uri in attached_adapter_uris:
remove_adapters.append(a)
remove_adapter_names.append(a.name)
remove_domains = []
for dc in cc['crypto-domain-configurations']:
di = dc['domain-index']
remove_domains.append(di)
LOGGER.debug(
"Detaching adapters %r and domains %r from target "
"partition %r", remove_adapter_names, remove_domains,
partition.name)
if not check_mode:
try:
partition.decrease_crypto_config(
remove_adapters, remove_domains)
except zhmcclient.Error as exc:
raise Error(
"Detaching adapters {0!r} and domains {1!r} from "
"target partition {2!r} failed: {3}".
format(remove_adapter_names, remove_domains,
partition.name, exc))
changed = True
result_changes['removed-adapters'] = remove_adapter_names
result_changes['removed-domains'] = remove_domains
if not check_mode:
# This is not optimal because it does not produce a result
# in check mode, but because the actual config is determined,
# instead of the artificially calculated one, it seems better
# to return no config than the unchanged actual config.
result.update(get_partition_config(partition, all_adapters))
return changed, result, result_changes
finally:
session.logoff()
def facts(params, check_mode):
"""
Return facts about the crypto configuration of the partition.
Raises:
ParameterError: An issue with the module parameters.
zhmcclient.Error: Any zhmcclient exception can happen.
"""
host = params['hmc_host']
userid, password = get_hmc_auth(params['hmc_auth'])
cpc_name = params['cpc_name']
partition_name = params['partition_name']
faked_session = params.get('faked_session', None) # No default specified
try:
session = get_session(faked_session, host, userid, password)
client = zhmcclient.Client(session)
cpc = client.cpcs.find(name=cpc_name)
partition = cpc.partitions.find(name=partition_name)
# The default exception handling is sufficient for the above.
# Determine all crypto adapters of any crypto type
filter_args = {
'adapter-family': 'crypto',
}
all_adapters = cpc.adapters.list(filter_args=filter_args,
full_properties=True)
result = get_partition_config(partition, all_adapters)
return False, result, None
finally:
session.logoff()
def perform_task(params, check_mode):
"""
Perform the task for this module, dependent on the 'state' module
parameter.
If check_mode is True, check whether changes would occur, but don't
actually perform any changes.
Raises:
ParameterError: An issue with the module parameters.
zhmcclient.Error: Any zhmcclient exception can happen.
"""
actions = {
"attached": ensure_attached,
"detached": ensure_detached,
"facts": facts,
}