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
|
# 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.
"""
Ironic SeaMicro interfaces.
Provides basic power control of servers in SeaMicro chassis via
python-seamicroclient.
Provides vendor passthru methods for SeaMicro specific functionality.
"""
import os
import re
from oslo_config import cfg
from oslo_utils import importutils
from six.moves.urllib import parse as urlparse
from ironic.common import boot_devices
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common.i18n import _LE
from ironic.common.i18n import _LW
from ironic.common import states
from ironic.conductor import task_manager
from ironic.drivers import base
from ironic.drivers.modules import console_utils
from ironic.openstack.common import log as logging
from ironic.openstack.common import loopingcall
seamicroclient = importutils.try_import('seamicroclient')
if seamicroclient:
from seamicroclient import client as seamicro_client
from seamicroclient import exceptions as seamicro_client_exception
opts = [
cfg.IntOpt('max_retry',
default=3,
help='Maximum retries for SeaMicro operations'),
cfg.IntOpt('action_timeout',
default=10,
help='Seconds to wait for power action to be completed')
]
CONF = cfg.CONF
opt_group = cfg.OptGroup(name='seamicro',
title='Options for the seamicro power driver')
CONF.register_group(opt_group)
CONF.register_opts(opts, opt_group)
LOG = logging.getLogger(__name__)
_BOOT_DEVICES_MAP = {
boot_devices.DISK: 'hd0',
boot_devices.PXE: 'pxe',
}
REQUIRED_PROPERTIES = {
'seamicro_api_endpoint': _("API endpoint. Required."),
'seamicro_password': _("password. Required."),
'seamicro_server_id': _("server ID. Required."),
'seamicro_username': _("username. Required."),
}
OPTIONAL_PROPERTIES = {
'seamicro_api_version': _("version of SeaMicro API client; default is 2. "
"Optional.")
}
COMMON_PROPERTIES = REQUIRED_PROPERTIES.copy()
COMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)
CONSOLE_PROPERTIES = {
'seamicro_terminal_port': _("node's UDP port to connect to. "
"Only required for console access.")
}
PORT_BASE = 2000
def _get_client(*args, **kwargs):
"""Creates the python-seamicro_client
:param kwargs: A dict of keyword arguments to be passed to the method,
which should contain: 'username', 'password',
'auth_url', 'api_version' parameters.
:returns: SeaMicro API client.
"""
cl_kwargs = {'username': kwargs['username'],
'password': kwargs['password'],
'auth_url': kwargs['api_endpoint']}
try:
return seamicro_client.Client(kwargs['api_version'], **cl_kwargs)
except seamicro_client_exception.UnsupportedVersion as e:
raise exception.InvalidParameterValue(_(
"Invalid 'seamicro_api_version' parameter. Reason: %s.") % e)
def _parse_driver_info(node):
"""Parses and creates seamicro driver info
:param node: An Ironic node object.
:returns: SeaMicro driver info.
:raises: MissingParameterValue if any required parameters are missing.
:raises: InvalidParameterValue if required parameter are invalid.
"""
info = node.driver_info or {}
missing_info = [key for key in REQUIRED_PROPERTIES if not info.get(key)]
if missing_info:
raise exception.MissingParameterValue(_(
"SeaMicro driver requires the following parameters to be set in"
" node's driver_info: %s.") % missing_info)
api_endpoint = info.get('seamicro_api_endpoint')
username = info.get('seamicro_username')
password = info.get('seamicro_password')
server_id = info.get('seamicro_server_id')
api_version = info.get('seamicro_api_version', "2")
port = info.get('seamicro_terminal_port')
if port:
try:
port = int(port)
except ValueError:
raise exception.InvalidParameterValue(_(
"SeaMicro terminal port is not an integer."))
r = re.compile(r"(^[0-9]+)/([0-9]+$)")
if not r.match(server_id):
raise exception.InvalidParameterValue(_(
"Invalid 'seamicro_server_id' parameter in node's "
"driver_info. Expected format of 'seamicro_server_id' "
"is <int>/<int>"))
url = urlparse.urlparse(api_endpoint)
if (not (url.scheme == "http") or not url.netloc):
raise exception.InvalidParameterValue(_(
"Invalid 'seamicro_api_endpoint' parameter in node's "
"driver_info."))
res = {'username': username,
'password': password,
'api_endpoint': api_endpoint,
'server_id': server_id,
'api_version': api_version,
'uuid': node.uuid,
'port': port}
return res
def _get_server(driver_info):
"""Get server from server_id."""
s_client = _get_client(**driver_info)
return s_client.servers.get(driver_info['server_id'])
def _get_volume(driver_info, volume_id):
"""Get volume from volume_id."""
s_client = _get_client(**driver_info)
return s_client.volumes.get(volume_id)
def _get_power_status(node):
"""Get current power state of this node
:param node: Ironic node one of :class:`ironic.db.models.Node`
:raises: InvalidParameterValue if a seamicro parameter is invalid.
:raises: MissingParameterValue if required seamicro parameters are
missing.
:raises: ServiceUnavailable on an error from SeaMicro Client.
:returns: Power state of the given node
"""
seamicro_info = _parse_driver_info(node)
try:
server = _get_server(seamicro_info)
if not hasattr(server, 'active') or server.active is None:
return states.ERROR
if not server.active:
return states.POWER_OFF
elif server.active:
return states.POWER_ON
except seamicro_client_exception.NotFound:
raise exception.NodeNotFound(node=node.uuid)
except seamicro_client_exception.ClientException as ex:
LOG.error(_LE("SeaMicro client exception %(msg)s for node %(uuid)s"),
{'msg': ex.message, 'uuid': node.uuid})
raise exception.ServiceUnavailable(message=ex.message)
def _power_on(node, timeout=None):
"""Power ON this node
:param node: An Ironic node object.
:param timeout: Time in seconds to wait till power on is complete.
:raises: InvalidParameterValue if a seamicro parameter is invalid.
:raises: MissingParameterValue if required seamicro parameters are
missing.
:returns: Power state of the given node.
"""
if timeout is None:
timeout = CONF.seamicro.action_timeout
state = [None]
retries = [0]
seamicro_info = _parse_driver_info(node)
server = _get_server(seamicro_info)
def _wait_for_power_on(state, retries):
"""Called at an interval until the node is powered on."""
state[0] = _get_power_status(node)
if state[0] == states.POWER_ON:
raise loopingcall.LoopingCallDone()
if retries[0] > CONF.seamicro.max_retry:
state[0] = states.ERROR
raise loopingcall.LoopingCallDone()
try:
retries[0] += 1
server.power_on()
except seamicro_client_exception.ClientException:
LOG.warning(_LW("Power-on failed for node %s."),
node.uuid)
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_power_on,
state, retries)
timer.start(interval=timeout).wait()
return state[0]
def _power_off(node, timeout=None):
"""Power OFF this node
:param node: Ironic node one of :class:`ironic.db.models.Node`
:param timeout: Time in seconds to wait till power off is compelete
:raises: InvalidParameterValue if a seamicro parameter is invalid.
:raises: MissingParameterValue if required seamicro parameters are
missing.
:returns: Power state of the given node
"""
if timeout is None:
timeout = CONF.seamicro.action_timeout
state = [None]
retries = [0]
seamicro_info = _parse_driver_info(node)
server = _get_server(seamicro_info)
def _wait_for_power_off(state, retries):
"""Called at an interval until the node is powered off."""
state[0] = _get_power_status(node)
if state[0] == states.POWER_OFF:
raise loopingcall.LoopingCallDone()
if retries[0] > CONF.seamicro.max_retry:
state[0] = states.ERROR
raise loopingcall.LoopingCallDone()
try:
retries[0] += 1
server.power_off()
except seamicro_client_exception.ClientException:
LOG.warning(_LW("Power-off failed for node %s."),
node.uuid)
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_power_off,
state, retries)
timer.start(interval=timeout).wait()
return state[0]
def _reboot(node, timeout=None):
"""Reboot this node.
:param node: Ironic node one of :class:`ironic.db.models.Node`
:param timeout: Time in seconds to wait till reboot is compelete
:raises: InvalidParameterValue if a seamicro parameter is invalid.
:raises: MissingParameterValue if required seamicro parameters are
missing.
:returns: Power state of the given node
"""
if timeout is None:
timeout = CONF.seamicro.action_timeout
state = [None]
retries = [0]
seamicro_info = _parse_driver_info(node)
server = _get_server(seamicro_info)
def _wait_for_reboot(state, retries):
"""Called at an interval until the node is rebooted successfully."""
state[0] = _get_power_status(node)
if state[0] == states.POWER_ON:
raise loopingcall.LoopingCallDone()
if retries[0] > CONF.seamicro.max_retry:
state[0] = states.ERROR
raise loopingcall.LoopingCallDone()
try:
retries[0] += 1
server.reset()
except seamicro_client_exception.ClientException:
LOG.warning(_LW("Reboot failed for node %s."),
node.uuid)
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_reboot,
state, retries)
server.reset()
timer.start(interval=timeout).wait()
return state[0]
def _validate_volume(driver_info, volume_id):
"""Validates if volume is in Storage pools designated for ironic."""
volume = _get_volume(driver_info, volume_id)
# Check if the ironic <scard>/ironic-<pool_id>/<volume_id> naming scheme
# is present in volume id
try:
pool_id = volume.id.split('/')[1].lower()
except IndexError:
pool_id = ""
if "ironic-" in pool_id:
return True
else:
raise exception.InvalidParameterValue(_(
"Invalid volume id specified"))
def _get_pools(driver_info, filters=None):
"""Get SeaMicro storage pools matching given filters."""
s_client = _get_client(**driver_info)
return s_client.pools.list(filters=filters)
def _create_volume(driver_info, volume_size):
"""Create volume in the SeaMicro storage pools designated for ironic."""
ironic_pools = _get_pools(driver_info, filters={'id': 'ironic-'})
if ironic_pools is None:
raise exception.VendorPassthruException(_(
"No storage pools found for ironic"))
least_used_pool = sorted(ironic_pools,
key=lambda x: x.freeSize)[0]
return _get_client(**driver_info).volumes.create(volume_size,
least_used_pool)
def get_telnet_port(driver_info):
"""Get SeaMicro telnet port to listen."""
server_id = int(driver_info['server_id'].split("/")[0])
return PORT_BASE + (10 * server_id)
class Power(base.PowerInterface):
"""SeaMicro Power Interface.
This PowerInterface class provides a mechanism for controlling the power
state of servers in a seamicro chassis.
"""
def get_properties(self):
return COMMON_PROPERTIES
def validate(self, task):
"""Check that node 'driver_info' is valid.
Check that node 'driver_info' contains the required fields.
:param task: a TaskManager instance containing the node to act on.
:raises: MissingParameterValue if required seamicro parameters are
missing.
"""
_parse_driver_info(task.node)
def get_power_state(self, task):
"""Get the current power state of the task's node.
Poll the host for the current power state of the node.
:param task: a TaskManager instance containing the node to act on.
:raises: ServiceUnavailable on an error from SeaMicro Client.
:raises: InvalidParameterValue if a seamicro parameter is invalid.
:raises: MissingParameterValue when a required parameter is missing
:returns: power state. One of :class:`ironic.common.states`.
"""
return _get_power_status(task.node)
@task_manager.require_exclusive_lock
def set_power_state(self, task, pstate):
"""Turn the power on or off.
Set the power state of a node.
:param task: a TaskManager instance containing the node to act on.
:param pstate: Either POWER_ON or POWER_OFF from :class:
`ironic.common.states`.
:raises: InvalidParameterValue if an invalid power state was specified
or a seamicro parameter is invalid.
:raises: MissingParameterValue when a required parameter is missing
:raises: PowerStateFailure if the desired power state couldn't be set.
"""
if pstate == states.POWER_ON:
state = _power_on(task.node)
elif pstate == states.POWER_OFF:
state = _power_off(task.node)
else:
raise exception.InvalidParameterValue(_(
"set_power_state called with invalid power state."))
if state != pstate:
raise exception.PowerStateFailure(pstate=pstate)
@task_manager.require_exclusive_lock
def reboot(self, task):
"""Cycles the power to the task's node.
:param task: a TaskManager instance containing the node to act on.
:raises: InvalidParameterValue if a seamicro parameter is invalid.
:raises: MissingParameterValue if required seamicro parameters are
missing.
:raises: PowerStateFailure if the final state of the node is not
POWER_ON.
"""
state = _reboot(task.node)
if state != states.POWER_ON:
raise exception.PowerStateFailure(pstate=states.POWER_ON)
class VendorPassthru(base.VendorInterface):
"""SeaMicro vendor-specific methods."""
def get_properties(self):
return COMMON_PROPERTIES
def validate(self, task, method, **kwargs):
_parse_driver_info(task.node)
@base.passthru(['POST'])
def set_node_vlan_id(self, task, **kwargs):
"""Sets a untagged vlan id for NIC 0 of node.
@kwargs vlan_id: id of untagged vlan for NIC 0 of node
"""
node = task.node
vlan_id = kwargs.get('vlan_id')
if not vlan_id:
raise exception.MissingParameterValue(_("No vlan id provided"))
seamicro_info = _parse_driver_info(node)
try:
server = _get_server(seamicro_info)
# remove current vlan for server
if len(server.nic['0']['untaggedVlan']) > 0:
server.unset_untagged_vlan(server.nic['0']['untaggedVlan'])
server = server.refresh(5)
server.set_untagged_vlan(vlan_id)
except seamicro_client_exception.ClientException as ex:
LOG.error(_LE("SeaMicro client exception: %s"), ex.message)
raise exception.VendorPassthruException(message=ex.message)
properties = node.properties
properties['seamicro_vlan_id'] = vlan_id
node.properties = properties
node.save()
@base.passthru(['POST'])
def attach_volume(self, task, **kwargs):
"""Attach a volume to a node.
Attach volume from SeaMicro storage pools for ironic to node.
If kwargs['volume_id'] not given, Create volume in SeaMicro
storage pool and attach to node.
@kwargs volume_id: id of pre-provisioned volume that is to be attached
as root volume of node
@kwargs volume_size: size of new volume to be created and attached
as root volume of node
"""
node = task.node
seamicro_info = _parse_driver_info(node)
volume_id = kwargs.get('volume_id')
if volume_id is None:
volume_size = kwargs.get('volume_size')
if volume_size is None:
raise exception.MissingParameterValue(
_("No volume size provided for creating volume"))
volume_id = _create_volume(seamicro_info, volume_size)
if _validate_volume(seamicro_info, volume_id):
try:
server = _get_server(seamicro_info)
server.detach_volume()
server = server.refresh(5)
server.attach_volume(volume_id)
except seamicro_client_exception.ClientException as ex:
LOG.error(_LE("SeaMicro client exception: %s"), ex.message)
raise exception.VendorPassthruException(message=ex.message)
properties = node.properties
properties['seamicro_volume_id'] = volume_id
node.properties = properties
node.save()
class Management(base.ManagementInterface):
def get_properties(self):
return COMMON_PROPERTIES
def validate(self, task):
"""Check that 'driver_info' contains SeaMicro credentials.
Validates whether the 'driver_info' property of the supplied
task's node contains the required credentials information.
:param task: a task from TaskManager.
:raises: MissingParameterValue when a required parameter is missing
"""
_parse_driver_info(task.node)
def get_supported_boot_devices(self):
"""Get a list of the supported boot devices.
:returns: A list with the supported boot devices defined
in :mod:`ironic.common.boot_devices`.
"""
return list(_BOOT_DEVICES_MAP.keys())
@task_manager.require_exclusive_lock
def set_boot_device(self, task, device, persistent=False):
"""Set the boot device for the task's node.
Set the boot device to use on next reboot of the node.
:param task: a task from TaskManager.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if the boot device will
persist to all future boots, False if not.
Default: False. Ignored by this driver.
:raises: InvalidParameterValue if an invalid boot device is
specified or if a seamicro parameter is invalid.
:raises: IronicException on an error from seamicro-client.
:raises: MissingParameterValue when a required parameter is missing
"""
if device not in self.get_supported_boot_devices():
raise exception.InvalidParameterValue(_(
"Invalid boot device %s specified.") % device)
seamicro_info = _parse_driver_info(task.node)
try:
server = _get_server(seamicro_info)
boot_device = _BOOT_DEVICES_MAP[device]
server.set_boot_order(boot_device)
except seamicro_client_exception.ClientException as ex:
LOG.error(_LE("Seamicro set boot device failed for node "
"%(node)s with the following error: %(error)s"),
{'node': task.node.uuid, 'error': ex.message})
raise exception.IronicException(message=ex.message)
def get_boot_device(self, task):
"""Get the current boot device for the task's node.
Returns the current boot device of the node. Be aware that not
all drivers support this.
:param task: a task from TaskManager.
:returns: a dictionary containing:
:boot_device: the boot device, one of
:mod:`ironic.common.boot_devices` or None if it is unknown.
:persistent: Whether the boot device will persist to all
future boots or not, None if it is unknown.
"""
# TODO(lucasagomes): The python-seamicroclient library currently
# doesn't expose a method to get the boot device, update it once
# it's implemented.
return {'boot_device': None, 'persistent': None}
def get_sensors_data(self, task):
"""Get sensors data method.
Not implemented by this driver.
:param task: a TaskManager instance.
"""
raise NotImplementedError()
class ShellinaboxConsole(base.ConsoleInterface):
"""A ConsoleInterface that uses telnet and shellinabox."""
def get_properties(self):
d = COMMON_PROPERTIES.copy()
d.update(CONSOLE_PROPERTIES)
return d
def validate(self, task):
"""Validate the Node console info.
:param task: a task from TaskManager.
:raises: MissingParameterValue if required seamicro parameters are
missing
:raises: InvalidParameterValue if required parameter are invalid.
"""
driver_info = _parse_driver_info(task.node)
if not driver_info['port']:
raise exception.MissingParameterValue(_(
"Missing 'seamicro_terminal_port' parameter in node's "
"driver_info"))
def start_console(self, task):
"""Start a remote console for the node.
:param task: a task from TaskManager
:raises: MissingParameterValue if required seamicro parameters are
missing
:raises: ConsoleError if the directory for the PID file cannot be
created
:raises: ConsoleSubprocessFailed when invoking the subprocess failed
:raises: InvalidParameterValue if required parameter are invalid.
"""
driver_info = _parse_driver_info(task.node)
telnet_port = get_telnet_port(driver_info)
chassis_ip = urlparse.urlparse(driver_info['api_endpoint']).netloc
seamicro_cmd = ("/:%(uid)s:%(gid)s:HOME:telnet %(chassis)s %(port)s"
% {'uid': os.getuid(),
'gid': os.getgid(),
'chassis': chassis_ip,
'port': telnet_port})
console_utils.start_shellinabox_console(driver_info['uuid'],
driver_info['port'],
seamicro_cmd)
def stop_console(self, task):
"""Stop the remote console session for the node.
:param task: a task from TaskManager
:raises: MissingParameterValue if required seamicro parameters are
missing
:raises: ConsoleError if unable to stop the console
:raises: InvalidParameterValue if required parameter are invalid.
"""
driver_info = _parse_driver_info(task.node)
console_utils.stop_shellinabox_console(driver_info['uuid'])
def get_console(self, task):
"""Get the type and connection information about the console.
:raises: MissingParameterValue if required seamicro parameters are
missing
:raises: InvalidParameterValue if required parameter are invalid.
"""
driver_info = _parse_driver_info(task.node)
url = console_utils.get_shellinabox_console_url(driver_info['port'])
return {'type': 'shellinabox', 'url': url}
|