A service for managing and provisioning Bare Metal servers.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

snmp.py 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. # Copyright 2013,2014 Cray Inc
  2. #
  3. # All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """
  17. Ironic SNMP power manager.
  18. Provides basic power control using an SNMP-enabled smart power controller.
  19. Uses a pluggable driver model to support devices with different SNMP object
  20. models.
  21. """
  22. import abc
  23. import time
  24. from oslo_log import log as logging
  25. from oslo_service import loopingcall
  26. from oslo_utils import importutils
  27. import six
  28. from ironic.common import exception
  29. from ironic.common.i18n import _
  30. from ironic.common import states
  31. from ironic.common import utils
  32. from ironic.conductor import task_manager
  33. from ironic.conf import CONF
  34. from ironic.drivers import base
  35. pysnmp = importutils.try_import('pysnmp')
  36. if pysnmp:
  37. from pysnmp import error as snmp_error
  38. from pysnmp import hlapi as snmp
  39. snmp_auth_protocols = {
  40. 'md5': snmp.usmHMACMD5AuthProtocol,
  41. 'sha': snmp.usmHMACSHAAuthProtocol,
  42. 'none': snmp.usmNoAuthProtocol,
  43. }
  44. # available since pysnmp 4.4.1
  45. try:
  46. snmp_auth_protocols.update(
  47. {
  48. 'sha224': snmp.usmHMAC128SHA224AuthProtocol,
  49. 'sha256': snmp.usmHMAC192SHA256AuthProtocol,
  50. 'sha384': snmp.usmHMAC256SHA384AuthProtocol,
  51. 'sha512': snmp.usmHMAC384SHA512AuthProtocol,
  52. }
  53. )
  54. except AttributeError:
  55. pass
  56. snmp_priv_protocols = {
  57. 'des': snmp.usmDESPrivProtocol,
  58. '3des': snmp.usm3DESEDEPrivProtocol,
  59. 'aes': snmp.usmAesCfb128Protocol,
  60. 'aes192': snmp.usmAesCfb192Protocol,
  61. 'aes256': snmp.usmAesCfb256Protocol,
  62. 'none': snmp.usmNoPrivProtocol,
  63. }
  64. # available since pysnmp 4.4.3
  65. try:
  66. snmp_priv_protocols.update(
  67. {
  68. 'aes192blmt': snmp.usmAesBlumenthalCfb192Protocol,
  69. 'aes256blmt': snmp.usmAesBlumenthalCfb256Protocol,
  70. }
  71. )
  72. except AttributeError:
  73. pass
  74. else:
  75. snmp = None
  76. snmp_error = None
  77. snmp_auth_protocols = {
  78. 'none': None
  79. }
  80. snmp_priv_protocols = {
  81. 'none': None
  82. }
  83. LOG = logging.getLogger(__name__)
  84. SNMP_V1 = '1'
  85. SNMP_V2C = '2c'
  86. SNMP_V3 = '3'
  87. SNMP_PORT = 161
  88. REQUIRED_PROPERTIES = {
  89. 'snmp_driver': _("PDU manufacturer driver. Required."),
  90. 'snmp_address': _("PDU IPv4 address or hostname. Required."),
  91. 'snmp_outlet': _("PDU power outlet index (1-based). Required."),
  92. }
  93. OPTIONAL_PROPERTIES = {
  94. 'snmp_version':
  95. _("SNMP protocol version: %(v1)s, %(v2c)s or %(v3)s "
  96. "(optional, default %(v1)s).")
  97. % {"v1": SNMP_V1, "v2c": SNMP_V2C, "v3": SNMP_V3},
  98. 'snmp_port':
  99. _("SNMP port, default %(port)d.") % {"port": SNMP_PORT},
  100. 'snmp_community':
  101. _("SNMP community name to use for read and/or write class SNMP "
  102. "commands unless `snmp_community_read` and/or "
  103. "`snmp_community_write` properties are present in which case the "
  104. "latter takes over. Applicable only to versions %(v1)s and %(v2c)s.")
  105. % {"v1": SNMP_V1, "v2c": SNMP_V2C},
  106. 'snmp_community_read':
  107. _("SNMP community name to use for read class SNMP commands. "
  108. "Takes precedence over the `snmp_community` property. "
  109. "Applicable only to versions %(v1)s and %(v2c)s.")
  110. % {"v1": SNMP_V1, "v2c": SNMP_V2C},
  111. 'snmp_community_write':
  112. _("SNMP community name to use for write class SNMP commands. "
  113. "Takes precedence over the `snmp_community` property. "
  114. "Applicable only to versions %(v1)s and %(v2c)s.")
  115. % {"v1": SNMP_V1, "v2c": SNMP_V2C},
  116. 'snmp_user':
  117. _("SNMPv3 User-based Security Model (USM) username. "
  118. "Required for version %(v3)s.")
  119. % {"v3": SNMP_V3},
  120. 'snmp_auth_protocol':
  121. _("SNMPv3 message authentication protocol ID. "
  122. "Known values are: %(auth)s. "
  123. "Default is 'none' unless 'snmp_auth_key' is provided. "
  124. "In the latter case 'md5' is the default.")
  125. % {'auth': sorted(snmp_auth_protocols)},
  126. 'snmp_auth_key':
  127. _("SNMPv3 message authentication key. "
  128. "Must be 8+ characters long. "
  129. "Required when message authentication is used. "
  130. "This key is used by the 'snmp_auth_protocol' algorithm."),
  131. 'snmp_priv_protocol':
  132. _("SNMPv3 message privacy (encryption) protocol ID. "
  133. "Known values are: %(priv)s. "
  134. "Using message privacy requires using message authentication. "
  135. "Default is 'none' unless 'snmp_priv_key' is provided. "
  136. "In the latter case 'des' is the default.")
  137. % {'priv': sorted(snmp_priv_protocols)},
  138. 'snmp_priv_key':
  139. _("SNMPv3 message authentication key. "
  140. "Must be 8+ characters long. "
  141. "Required when message authentication is used. "
  142. "This key is used by the 'snmp_priv_protocol' algorithm."),
  143. 'snmp_context_engine_id':
  144. _("SNMPv3 context engine ID. "
  145. "Default is the value of authoritative engine ID."),
  146. 'snmp_context_name':
  147. _("SNMPv3 context name. "
  148. "Default is an empty string ('')."),
  149. }
  150. DEPRECATED_PROPERTIES = {
  151. # synonym for `snmp_user`
  152. 'snmp_security':
  153. _("SNMPv3 User-based Security Model (USM) username. "
  154. "Required for version %(v3)s. "
  155. "This property is deprecated, please use `snmp_user` instead.")
  156. % {"v3": SNMP_V3},
  157. }
  158. COMMON_PROPERTIES = REQUIRED_PROPERTIES.copy()
  159. COMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)
  160. COMMON_PROPERTIES.update(DEPRECATED_PROPERTIES)
  161. class SNMPClient(object):
  162. """SNMP client object.
  163. Performs low level SNMP get and set operations. Encapsulates all
  164. interaction with PySNMP to simplify dynamic importing and unit testing.
  165. """
  166. def __init__(self, address, port, version,
  167. read_community=None, write_community=None,
  168. user=None, auth_proto=None,
  169. auth_key=None, priv_proto=None,
  170. priv_key=None, context_engine_id=None, context_name=None):
  171. if not snmp:
  172. raise exception.DriverLoadError(
  173. driver=self.__class__.__name__,
  174. reason=_("Unable to import python-pysnmp library")
  175. )
  176. self.address = address
  177. self.port = port
  178. self.version = version
  179. if self.version == SNMP_V3:
  180. self.user = user
  181. self.auth_proto = auth_proto
  182. self.auth_key = auth_key
  183. self.priv_proto = priv_proto
  184. self.priv_key = priv_key
  185. else:
  186. self.read_community = read_community
  187. self.write_community = write_community
  188. self.context_engine_id = context_engine_id
  189. self.context_name = context_name or ''
  190. self.snmp_engine = snmp.SnmpEngine()
  191. def _get_auth(self, write_mode=False):
  192. """Return the authorization data for an SNMP request.
  193. :param write_mode: `True` if write class SNMP command is
  194. executed. Default is `False`.
  195. :returns: Either
  196. :class:`pysnmp.hlapi.CommunityData`
  197. or :class:`pysnmp.hlapi.UsmUserData`
  198. object depending on SNMP version being used.
  199. """
  200. if self.version == SNMP_V3:
  201. return snmp.UsmUserData(
  202. self.user,
  203. authKey=self.auth_key,
  204. authProtocol=self.auth_proto,
  205. privKey=self.priv_key,
  206. privProtocol=self.priv_proto
  207. )
  208. else:
  209. mp_model = 1 if self.version == SNMP_V2C else 0
  210. return snmp.CommunityData(
  211. self.write_community if write_mode else self.read_community,
  212. mpModel=mp_model
  213. )
  214. def _get_transport(self):
  215. """Return the transport target for an SNMP request.
  216. :returns: A :class:
  217. `pysnmp.hlapi.UdpTransportTarget` object.
  218. :raises: :class:`pysnmp.error.PySnmpError` if the transport address
  219. is bad.
  220. """
  221. # The transport target accepts timeout and retries parameters, which
  222. # default to 1 (second) and 5 respectively. These are deemed sensible
  223. # enough to allow for an unreliable network or slow device.
  224. return snmp.UdpTransportTarget(
  225. (self.address, self.port),
  226. timeout=CONF.snmp.udp_transport_timeout,
  227. retries=CONF.snmp.udp_transport_retries)
  228. def _get_context(self):
  229. """Return the SNMP context for an SNMP request.
  230. :returns: A :class:
  231. `pysnmp.hlapi.ContextData` object.
  232. :raises: :class:`pysnmp.error.PySnmpError` if SNMP context data
  233. is bad.
  234. """
  235. return snmp.ContextData(
  236. contextEngineId=self.context_engine_id,
  237. contextName=self.context_name
  238. )
  239. def get(self, oid):
  240. """Use PySNMP to perform an SNMP GET operation on a single object.
  241. :param oid: The OID of the object to get.
  242. :raises: SNMPFailure if an SNMP request fails.
  243. :returns: The value of the requested object.
  244. """
  245. try:
  246. snmp_gen = snmp.getCmd(self.snmp_engine,
  247. self._get_auth(),
  248. self._get_transport(),
  249. self._get_context(),
  250. snmp.ObjectType(snmp.ObjectIdentity(oid)))
  251. except snmp_error.PySnmpError as e:
  252. raise exception.SNMPFailure(operation="GET", error=e)
  253. error_indication, error_status, error_index, var_binds = next(snmp_gen)
  254. if error_indication:
  255. # SNMP engine-level error.
  256. raise exception.SNMPFailure(operation="GET",
  257. error=error_indication)
  258. if error_status:
  259. # SNMP PDU error.
  260. raise exception.SNMPFailure(operation="GET",
  261. error=error_status.prettyPrint())
  262. # We only expect a single value back
  263. name, val = var_binds[0]
  264. return val
  265. def get_next(self, oid):
  266. """Use PySNMP to perform an SNMP GET NEXT operation on a table object.
  267. :param oid: The OID of the object to get.
  268. :raises: SNMPFailure if an SNMP request fails.
  269. :returns: A list of values of the requested table object.
  270. """
  271. try:
  272. snmp_gen = snmp.nextCmd(self.snmp_engine,
  273. self._get_auth(),
  274. self._get_transport(),
  275. self._get_context(),
  276. snmp.ObjectType(snmp.ObjectIdentity(oid)),
  277. lexicographicMode=False)
  278. except snmp_error.PySnmpError as e:
  279. raise exception.SNMPFailure(operation="GET_NEXT", error=e)
  280. vals = []
  281. for (error_indication, error_status, error_index,
  282. var_binds) in snmp_gen:
  283. if error_indication:
  284. # SNMP engine-level error.
  285. raise exception.SNMPFailure(operation="GET_NEXT",
  286. error=error_indication)
  287. if error_status:
  288. # SNMP PDU error.
  289. raise exception.SNMPFailure(operation="GET_NEXT",
  290. error=error_status.prettyPrint())
  291. # this is not a table, but a table row
  292. # e.g. 1-D array of tuples
  293. _name, value = var_binds[0]
  294. vals.append(value)
  295. return vals
  296. def set(self, oid, value):
  297. """Use PySNMP to perform an SNMP SET operation on a single object.
  298. :param oid: The OID of the object to set.
  299. :param value: The value of the object to set.
  300. :raises: SNMPFailure if an SNMP request fails.
  301. """
  302. try:
  303. snmp_gen = snmp.setCmd(self.snmp_engine,
  304. self._get_auth(write_mode=True),
  305. self._get_transport(),
  306. self._get_context(),
  307. snmp.ObjectType(
  308. snmp.ObjectIdentity(oid), value))
  309. except snmp_error.PySnmpError as e:
  310. raise exception.SNMPFailure(operation="SET", error=e)
  311. error_indication, error_status, error_index, var_binds = next(snmp_gen)
  312. if error_indication:
  313. # SNMP engine-level error.
  314. raise exception.SNMPFailure(operation="SET",
  315. error=error_indication)
  316. if error_status:
  317. # SNMP PDU error.
  318. raise exception.SNMPFailure(operation="SET",
  319. error=error_status.prettyPrint())
  320. def _get_client(snmp_info):
  321. """Create and return an SNMP client object.
  322. :param snmp_info: SNMP driver info.
  323. :returns: A :class:`SNMPClient` object.
  324. """
  325. return SNMPClient(snmp_info["address"],
  326. snmp_info["port"],
  327. snmp_info["version"],
  328. snmp_info.get("read_community"),
  329. snmp_info.get("write_community"),
  330. snmp_info.get("user"),
  331. snmp_info.get("auth_proto"),
  332. snmp_info.get("auth_key"),
  333. snmp_info.get("priv_proto"),
  334. snmp_info.get("priv_key"),
  335. snmp_info.get("context_engine_id"),
  336. snmp_info.get("context_name"))
  337. _memoized = {}
  338. def memoize(f):
  339. def memoized(self, node_info):
  340. hashable_node_info = frozenset((key, val)
  341. for key, val in node_info.items()
  342. if key is not 'outlet')
  343. if hashable_node_info not in _memoized:
  344. _memoized[hashable_node_info] = f(self)
  345. return _memoized[hashable_node_info]
  346. return memoized
  347. def retry_on_outdated_cache(f):
  348. def wrapper(self):
  349. try:
  350. return f(self)
  351. except exception.SNMPFailure:
  352. hashable_node_info = (
  353. frozenset((key, val)
  354. for key, val in self.snmp_info.items()
  355. if key is not 'outlet')
  356. )
  357. del _memoized[hashable_node_info]
  358. self.driver = self._get_pdu_driver(self.snmp_info)
  359. return f(self)
  360. return wrapper
  361. @six.add_metaclass(abc.ABCMeta)
  362. class SNMPDriverBase(object):
  363. """SNMP power driver base class.
  364. The SNMPDriver class hierarchy implements manufacturer-specific MIB actions
  365. over SNMP to interface with different smart power controller products.
  366. """
  367. oid_enterprise = (1, 3, 6, 1, 4, 1)
  368. retry_interval = 1
  369. def __init__(self, snmp_info):
  370. self.snmp_info = snmp_info
  371. self.client = _get_client(snmp_info)
  372. @abc.abstractmethod
  373. def _snmp_power_state(self):
  374. """Perform the SNMP request required to get the current power state.
  375. :raises: SNMPFailure if an SNMP request fails.
  376. :returns: power state. One of :class:`ironic.common.states`.
  377. """
  378. @abc.abstractmethod
  379. def _snmp_power_on(self):
  380. """Perform the SNMP request required to set the power on.
  381. :raises: SNMPFailure if an SNMP request fails.
  382. """
  383. @abc.abstractmethod
  384. def _snmp_power_off(self):
  385. """Perform the SNMP request required to set the power off.
  386. :raises: SNMPFailure if an SNMP request fails.
  387. """
  388. def _snmp_wait_for_state(self, goal_state):
  389. """Wait for the power state of the PDU outlet to change.
  390. :param goal_state: The power state to wait for, one of
  391. :class:`ironic.common.states`.
  392. :raises: SNMPFailure if an SNMP request fails.
  393. :returns: power state. One of :class:`ironic.common.states`.
  394. """
  395. def _poll_for_state(mutable):
  396. """Called at an interval until the node's power is consistent.
  397. :param mutable: dict object containing "state" and "next_time"
  398. :raises: SNMPFailure if an SNMP request fails.
  399. """
  400. mutable["state"] = self._snmp_power_state()
  401. if mutable["state"] == goal_state:
  402. raise loopingcall.LoopingCallDone()
  403. mutable["next_time"] += self.retry_interval
  404. if mutable["next_time"] >= CONF.snmp.power_timeout:
  405. mutable["state"] = states.ERROR
  406. raise loopingcall.LoopingCallDone()
  407. # Pass state to the looped function call in a mutable form.
  408. state = {"state": None, "next_time": 0}
  409. timer = loopingcall.FixedIntervalLoopingCall(_poll_for_state,
  410. state)
  411. timer.start(interval=self.retry_interval).wait()
  412. LOG.debug("power state '%s'", state["state"])
  413. return state["state"]
  414. def power_state(self):
  415. """Returns a node's current power state.
  416. :raises: SNMPFailure if an SNMP request fails.
  417. :returns: power state. One of :class:`ironic.common.states`.
  418. """
  419. return self._snmp_power_state()
  420. def power_on(self):
  421. """Set the power state to this node to ON.
  422. :raises: SNMPFailure if an SNMP request fails.
  423. :returns: power state. One of :class:`ironic.common.states`.
  424. """
  425. self._snmp_power_on()
  426. return self._snmp_wait_for_state(states.POWER_ON)
  427. def power_off(self):
  428. """Set the power state to this node to OFF.
  429. :raises: SNMPFailure if an SNMP request fails.
  430. :returns: power state. One of :class:`ironic.common.states`.
  431. """
  432. self._snmp_power_off()
  433. return self._snmp_wait_for_state(states.POWER_OFF)
  434. def power_reset(self):
  435. """Reset the power to this node.
  436. :raises: SNMPFailure if an SNMP request fails.
  437. :returns: power state. One of :class:`ironic.common.states`.
  438. """
  439. power_result = self.power_off()
  440. if power_result != states.POWER_OFF:
  441. return states.ERROR
  442. time.sleep(CONF.snmp.reboot_delay)
  443. power_result = self.power_on()
  444. if power_result != states.POWER_ON:
  445. return states.ERROR
  446. return power_result
  447. class SNMPDriverSimple(SNMPDriverBase):
  448. """SNMP driver base class for simple PDU devices.
  449. Here, simple refers to devices which provide a single SNMP object for
  450. controlling the power state of an outlet.
  451. The default OID of the power state object is of the form
  452. <enterprise OID>.<device OID>.<outlet ID>. A different OID may be specified
  453. by overriding the _snmp_oid method in a subclass.
  454. """
  455. def __init__(self, *args, **kwargs):
  456. super(SNMPDriverSimple, self).__init__(*args, **kwargs)
  457. self.oid = self._snmp_oid()
  458. @abc.abstractproperty
  459. def oid_device(self):
  460. """Device dependent portion of the power state object OID."""
  461. @abc.abstractproperty
  462. def value_power_on(self):
  463. """Value representing power on state."""
  464. @abc.abstractproperty
  465. def value_power_off(self):
  466. """Value representing power off state."""
  467. def _snmp_oid(self):
  468. """Return the OID of the power state object.
  469. :returns: Power state object OID as a tuple of integers.
  470. """
  471. outlet = self.snmp_info['outlet']
  472. return self.oid_enterprise + self.oid_device + (outlet,)
  473. def _snmp_power_state(self):
  474. state = self.client.get(self.oid)
  475. # Translate the state to an Ironic power state.
  476. if state == self.value_power_on:
  477. power_state = states.POWER_ON
  478. elif state == self.value_power_off:
  479. power_state = states.POWER_OFF
  480. else:
  481. LOG.warning("SNMP PDU %(addr)s outlet %(outlet)s: "
  482. "unrecognised power state %(state)s.",
  483. {'addr': self.snmp_info['address'],
  484. 'outlet': self.snmp_info['outlet'],
  485. 'state': state})
  486. power_state = states.ERROR
  487. return power_state
  488. def _snmp_power_on(self):
  489. value = snmp.Integer(self.value_power_on)
  490. self.client.set(self.oid, value)
  491. def _snmp_power_off(self):
  492. value = snmp.Integer(self.value_power_off)
  493. self.client.set(self.oid, value)
  494. class SNMPDriverAten(SNMPDriverSimple):
  495. """SNMP driver class for Aten PDU devices.
  496. SNMP objects for Aten PDU:
  497. 1.3.6.1.4.1.21317.1.3.2.2.2.2 Outlet Power
  498. Values: 1=Off, 2=On, 3=Pending, 4=Reset
  499. """
  500. system_id = (21317,)
  501. oid_device = (21317, 1, 3, 2, 2, 2, 2)
  502. value_power_on = 2
  503. value_power_off = 1
  504. def _snmp_oid(self):
  505. """Return the OID of the power state object.
  506. :returns: Power state object OID as a tuple of integers.
  507. """
  508. outlet = self.snmp_info['outlet']
  509. return self.oid_enterprise + self.oid_device + (outlet, 0,)
  510. class SNMPDriverAPCMasterSwitch(SNMPDriverSimple):
  511. """SNMP driver class for APC MasterSwitch PDU devices.
  512. SNMP objects for APC SNMPDriverAPCMasterSwitch PDU:
  513. 1.3.6.1.4.1.318.1.1.4.4.2.1.3 sPDUOutletCtl
  514. Values: 1=On, 2=Off, 3=PowerCycle, [...more options follow]
  515. """
  516. system_id = (318, 1, 1, 4)
  517. oid_device = (318, 1, 1, 4, 4, 2, 1, 3)
  518. value_power_on = 1
  519. value_power_off = 2
  520. class SNMPDriverAPCMasterSwitchPlus(SNMPDriverSimple):
  521. """SNMP driver class for APC MasterSwitchPlus PDU devices.
  522. SNMP objects for APC SNMPDriverAPCMasterSwitchPlus PDU:
  523. 1.3.6.1.4.1.318.1.1.6.5.1.1.5 sPDUOutletControlMSPOutletCommand
  524. Values: 1=On, 3=Off, [...more options follow]
  525. """
  526. system_id = (318, 1, 1, 6)
  527. oid_device = (318, 1, 1, 6, 5, 1, 1, 5)
  528. value_power_on = 1
  529. value_power_off = 3
  530. class SNMPDriverAPCRackPDU(SNMPDriverSimple):
  531. """SNMP driver class for APC RackPDU devices.
  532. SNMP objects for APC SNMPDriverAPCRackPDU PDU:
  533. # 1.3.6.1.4.1.318.1.1.12.3.3.1.1.4 rPDUOutletControlOutletCommand
  534. Values: 1=On, 2=Off, 3=PowerCycle, [...more options follow]
  535. """
  536. system_id = (318, 1, 1, 12)
  537. oid_device = (318, 1, 1, 12, 3, 3, 1, 1, 4)
  538. value_power_on = 1
  539. value_power_off = 2
  540. class SNMPDriverCyberPower(SNMPDriverSimple):
  541. """SNMP driver class for CyberPower PDU devices.
  542. SNMP objects for CyberPower PDU:
  543. 1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4 ePDUOutletControlOutletCommand
  544. Values: 1=On, 2=Off, 3=PowerCycle, [...more options follow]
  545. """
  546. # NOTE(mgoddard): This device driver is currently untested, this driver has
  547. # been implemented based upon its published MIB
  548. # documentation.
  549. system_id = (3808,)
  550. oid_device = (3808, 1, 1, 3, 3, 3, 1, 1, 4)
  551. value_power_on = 1
  552. value_power_off = 2
  553. class SNMPDriverTeltronix(SNMPDriverSimple):
  554. """SNMP driver class for Teltronix PDU devices.
  555. SNMP objects for Teltronix PDU:
  556. 1.3.6.1.4.1.23620.1.2.2.1.4 Outlet Power
  557. Values: 1=Off, 2=On
  558. """
  559. system_id = (23620,)
  560. oid_device = (23620, 1, 2, 2, 1, 4)
  561. value_power_on = 2
  562. value_power_off = 1
  563. class SNMPDriverEatonPower(SNMPDriverBase):
  564. """SNMP driver class for Eaton Power PDU.
  565. The Eaton power PDU does not follow the model of SNMPDriverSimple as it
  566. uses multiple SNMP objects.
  567. SNMP objects for Eaton Power PDU
  568. 1.3.6.1.4.1.534.6.6.7.6.6.1.2.<outlet ID> outletControlStatus
  569. Read 0=off, 1=on, 2=pending off, 3=pending on
  570. 1.3.6.1.4.1.534.6.6.7.6.6.1.3.<outlet ID> outletControlOffCmd
  571. Write 0 for immediate power off
  572. 1.3.6.1.4.1.534.6.6.7.6.6.1.4.<outlet ID> outletControlOnCmd
  573. Write 0 for immediate power on
  574. """
  575. # NOTE(mgoddard): This device driver is currently untested, this driver has
  576. # been implemented based upon its published MIB
  577. # documentation.
  578. system_id = (534,)
  579. oid_device = (534, 6, 6, 7, 6, 6, 1)
  580. oid_status = (2,)
  581. oid_poweron = (3,)
  582. oid_poweroff = (4,)
  583. status_off = 0
  584. status_on = 1
  585. status_pending_off = 2
  586. status_pending_on = 3
  587. value_power_on = 0
  588. value_power_off = 0
  589. def __init__(self, *args, **kwargs):
  590. super(SNMPDriverEatonPower, self).__init__(*args, **kwargs)
  591. # Due to its use of different OIDs for different actions, we only form
  592. # an OID that holds the common substring of the OIDs for power
  593. # operations.
  594. self.oid_base = self.oid_enterprise + self.oid_device
  595. def _snmp_oid(self, oid):
  596. """Return the OID for one of the outlet control objects.
  597. :param oid: The action-dependent portion of the OID, as a tuple of
  598. integers.
  599. :returns: The full OID as a tuple of integers.
  600. """
  601. outlet = self.snmp_info['outlet']
  602. return self.oid_base + oid + (outlet,)
  603. def _snmp_power_state(self):
  604. oid = self._snmp_oid(self.oid_status)
  605. state = self.client.get(oid)
  606. # Translate the state to an Ironic power state.
  607. if state in (self.status_on, self.status_pending_off):
  608. power_state = states.POWER_ON
  609. elif state in (self.status_off, self.status_pending_on):
  610. power_state = states.POWER_OFF
  611. else:
  612. LOG.warning("Eaton Power SNMP PDU %(addr)s outlet %(outlet)s: "
  613. "unrecognised power state %(state)s.",
  614. {'addr': self.snmp_info['address'],
  615. 'outlet': self.snmp_info['outlet'],
  616. 'state': state})
  617. power_state = states.ERROR
  618. return power_state
  619. def _snmp_power_on(self):
  620. oid = self._snmp_oid(self.oid_poweron)
  621. value = snmp.Integer(self.value_power_on)
  622. self.client.set(oid, value)
  623. def _snmp_power_off(self):
  624. oid = self._snmp_oid(self.oid_poweroff)
  625. value = snmp.Integer(self.value_power_off)
  626. self.client.set(oid, value)
  627. class SNMPDriverBaytechMRP27(SNMPDriverSimple):
  628. """SNMP driver class for Baytech MRP27 PDU devices.
  629. SNMP objects for Baytech MRP27 PDU:
  630. 4779, 1, 3, 5, 3, 1, 3, {unit_id} Outlet Power
  631. Values: 0=Off, 1=On, 2=Reboot
  632. """
  633. # TODO(srobert): Add support for dynamically allocated unit_id when needed
  634. unit_id = 1
  635. oid_device = (4779, 1, 3, 5, 3, 1, 3) + (unit_id,)
  636. value_power_off = 0
  637. value_power_on = 1
  638. class SNMPDriverAuto(SNMPDriverBase):
  639. SYS_OBJ_OID = (1, 3, 6, 1, 2, 1, 1, 2)
  640. def __init__(self, *args, **kwargs):
  641. super(SNMPDriverAuto, self).__init__(*args, **kwargs)
  642. self.driver = self._get_pdu_driver(*args, **kwargs)
  643. def _get_pdu_driver(self, *args, **kwargs):
  644. drivers_map = {}
  645. for name, obj in DRIVER_CLASSES.items():
  646. if not getattr(obj, 'system_id', False):
  647. continue
  648. system_id = self.oid_enterprise + getattr(obj, 'system_id')
  649. if (system_id in drivers_map and
  650. drivers_map[system_id] is not obj):
  651. raise exception.InvalidParameterValue(_(
  652. "SNMPDriverAuto: duplicate driver system ID prefix "
  653. "%(system_id)s") % {'system_id': system_id})
  654. drivers_map[system_id] = obj
  655. LOG.debug("SNMP driver mapping %(system_id)s -> %(name)s",
  656. {'system_id': system_id, 'name': obj.__name__})
  657. system_id = self._fetch_driver(*args, **kwargs)
  658. LOG.debug("SNMP device reports sysObjectID %(system_id)s",
  659. {'system_id': system_id})
  660. system_id_prefix = tuple(system_id)
  661. # pick driver by the longest matching sysObjectID prefix
  662. while len(system_id_prefix) > len(self.oid_enterprise):
  663. try:
  664. Driver = drivers_map[system_id_prefix]
  665. LOG.debug("Chosen SNMP driver %(name)s based on sysObjectID "
  666. "prefix %(system_id_prefix)s", {Driver.__name__,
  667. system_id_prefix})
  668. return Driver(*args, **kwargs)
  669. except KeyError:
  670. system_id_prefix = system_id_prefix[:-1]
  671. raise exception.InvalidParameterValue(_(
  672. "SNMPDriverAuto: no driver matching %(system_id)s") %
  673. {'system_id': system_id})
  674. @retry_on_outdated_cache
  675. def _snmp_power_state(self):
  676. current_power_state = self.driver._snmp_power_state()
  677. return current_power_state
  678. @retry_on_outdated_cache
  679. def _snmp_power_on(self):
  680. return self.driver._snmp_power_on()
  681. @retry_on_outdated_cache
  682. def _snmp_power_off(self):
  683. return self.driver._snmp_power_off()
  684. @memoize
  685. def _fetch_driver(self):
  686. return self.client.get(self.SYS_OBJ_OID)
  687. # A dictionary of supported drivers keyed by snmp_driver attribute
  688. DRIVER_CLASSES = {
  689. 'apc': SNMPDriverAPCMasterSwitch,
  690. 'apc_masterswitch': SNMPDriverAPCMasterSwitch,
  691. 'apc_masterswitchplus': SNMPDriverAPCMasterSwitchPlus,
  692. 'apc_rackpdu': SNMPDriverAPCRackPDU,
  693. 'aten': SNMPDriverAten,
  694. 'cyberpower': SNMPDriverCyberPower,
  695. 'eatonpower': SNMPDriverEatonPower,
  696. 'teltronix': SNMPDriverTeltronix,
  697. 'baytech_mrp27': SNMPDriverBaytechMRP27,
  698. 'auto': SNMPDriverAuto,
  699. }
  700. def _parse_driver_info_snmpv3_user(node, info):
  701. snmp_info = {}
  702. if 'snmp_user' not in info and 'snmp_security' not in info:
  703. raise exception.MissingParameterValue(_(
  704. "SNMP driver requires `driver_info/snmp_user` to be set in "
  705. "node %(node)s configuration for SNMP version %(ver)s.") %
  706. {'node': node.uuid, 'ver': SNMP_V3})
  707. snmp_info['user'] = info.get('snmp_user', info.get('snmp_security'))
  708. if 'snmp_security' in info:
  709. LOG.warning("The `driver_info/snmp_security` parameter is deprecated "
  710. "in favor of `driver_info/snmp_user` parameter. Please "
  711. "remove the `driver_info/snmp_security` parameter from "
  712. "node %(node)s configuration.", {'node': node.uuid})
  713. if 'snmp_user' in info:
  714. LOG.warning("The `driver_info/snmp_security` parameter is ignored "
  715. "in favor of `driver_info/snmp_user` parameter in "
  716. "node %(node)s configuration.", {'node': node.uuid})
  717. return snmp_info
  718. def _parse_driver_info_snmpv3_crypto(node, info):
  719. snmp_info = {}
  720. if 'snmp_auth_protocol' in info:
  721. auth_p = info['snmp_auth_protocol']
  722. try:
  723. snmp_info['auth_protocol'] = snmp_auth_protocols[auth_p]
  724. except KeyError:
  725. raise exception.InvalidParameterValue(_(
  726. "SNMPPowerDriver: unknown SNMPv3 authentication protocol "
  727. "`driver_info/snmp_auth_protocol` %(proto)s in node %(node)s "
  728. "configuration, known protocols are: %(protos)s") %
  729. {'node': node.uuid, 'proto': auth_p,
  730. 'protos': ', '.join(snmp_auth_protocols)}
  731. )
  732. if 'snmp_priv_protocol' in info:
  733. priv_p = info['snmp_priv_protocol']
  734. try:
  735. snmp_info['priv_protocol'] = snmp_priv_protocols[priv_p]
  736. except KeyError:
  737. raise exception.InvalidParameterValue(_(
  738. "SNMPPowerDriver: unknown SNMPv3 privacy protocol "
  739. "`driver_info/snmp_priv_protocol` %(proto)s in node "
  740. "%(node)s configuration, known protocols are: %(protos)s") %
  741. {'node': node.uuid, 'proto': priv_p,
  742. 'protos': ', '.join(snmp_priv_protocols)}
  743. )
  744. if 'snmp_auth_key' in info:
  745. auth_k = info['snmp_auth_key']
  746. if len(auth_k) < 8:
  747. raise exception.InvalidParameterValue(_(
  748. "SNMPPowerDriver: short SNMPv3 authentication key "
  749. "`driver_info/snmp_auth_key` in node %(node)s configuration "
  750. "(8+ chars required)") % {'node': node.uuid})
  751. snmp_info['auth_key'] = auth_k
  752. if 'auth_protocol' not in snmp_info:
  753. snmp_info['auth_protocol'] = snmp_auth_protocols['md5']
  754. if 'snmp_priv_key' in info:
  755. priv_k = info['snmp_priv_key']
  756. if len(priv_k) < 8:
  757. raise exception.InvalidParameterValue(_(
  758. "SNMPPowerDriver: short SNMPv3 privacy key "
  759. "`driver_info/snmp_priv_key` node %(node)s configuration "
  760. "(8+ chars required)") % {'node': node.uuid})
  761. snmp_info['priv_key'] = priv_k
  762. if 'priv_protocol' not in snmp_info:
  763. snmp_info['priv_protocol'] = snmp_priv_protocols['des']
  764. if ('priv_protocol' in snmp_info and
  765. 'auth_protocol' not in snmp_info):
  766. raise exception.MissingParameterValue(_(
  767. "SNMPPowerDriver: SNMPv3 privacy requires authentication. "
  768. "Please add `driver_info/auth_protocol` property to node "
  769. "%(node)s configuration.") % {'node': node.uuid})
  770. if ('auth_protocol' in snmp_info and
  771. 'auth_key' not in snmp_info):
  772. raise exception.MissingParameterValue(_(
  773. "SNMPPowerDriver: missing SNMPv3 authentication key while "
  774. "`driver_info/snmp_auth_protocol` is present. Please "
  775. "add `driver_info/snmp_auth_key` to node %(node)s "
  776. "configuration.") % {'node': node.uuid})
  777. if ('priv_protocol' in snmp_info and
  778. 'priv_key' not in snmp_info):
  779. raise exception.MissingParameterValue(_(
  780. "SNMPPowerDriver: missing SNMPv3 privacy key while "
  781. "`driver_info/snmp_priv_protocol` is present. Please "
  782. "add `driver_info/snmp_priv_key` to node %(node)s "
  783. "configuration.") % {'node': node.uuid})
  784. return snmp_info
  785. def _parse_driver_info_snmpv3_context(node, info):
  786. snmp_info = {}
  787. if 'snmp_context_engine_id' in info:
  788. snmp_info['context_engine_id'] = info['snmp_context_engine_id']
  789. if 'snmp_context_name' in info:
  790. snmp_info['context_name'] = info['snmp_context_name']
  791. return snmp_info
  792. def _parse_driver_info(node):
  793. """Parse a node's driver_info values.
  794. Return a dictionary of validated driver information, usable for
  795. SNMPDriver object creation.
  796. :param node: An Ironic node object.
  797. :returns: SNMP driver info.
  798. :raises: MissingParameterValue if any required parameters are missing.
  799. :raises: InvalidParameterValue if any parameters are invalid.
  800. """
  801. info = node.driver_info or {}
  802. missing_info = [key for key in REQUIRED_PROPERTIES if not info.get(key)]
  803. if missing_info:
  804. raise exception.MissingParameterValue(_(
  805. "SNMP driver requires the following parameters to be set in "
  806. "node's driver_info: %s.") % missing_info)
  807. snmp_info = {}
  808. # Validate PDU driver type
  809. snmp_info['driver'] = info['snmp_driver']
  810. if snmp_info['driver'] not in DRIVER_CLASSES:
  811. raise exception.InvalidParameterValue(_(
  812. "SNMPPowerDriver: unknown driver: '%s'") % snmp_info['driver'])
  813. # In absence of a version, default to SNMPv1
  814. snmp_info['version'] = info.get('snmp_version', SNMP_V1)
  815. if snmp_info['version'] not in (SNMP_V1, SNMP_V2C, SNMP_V3):
  816. raise exception.InvalidParameterValue(_(
  817. "SNMPPowerDriver: unknown SNMP version: '%s'") %
  818. snmp_info['version'])
  819. # In absence of a configured UDP port, default to the standard port
  820. port_str = info.get('snmp_port', SNMP_PORT)
  821. snmp_info['port'] = utils.validate_network_port(port_str, 'snmp_port')
  822. if snmp_info['port'] < 1 or snmp_info['port'] > 65535:
  823. raise exception.InvalidParameterValue(_(
  824. "SNMPPowerDriver: SNMP UDP port out of range: %d")
  825. % snmp_info['port'])
  826. # Extract version-dependent required parameters
  827. if snmp_info['version'] in (SNMP_V1, SNMP_V2C):
  828. read_community = info.get('snmp_community_read')
  829. if read_community is None:
  830. read_community = info.get('snmp_community')
  831. write_community = info.get('snmp_community_write')
  832. if write_community is None:
  833. write_community = info.get('snmp_community')
  834. if not read_community or not write_community:
  835. raise exception.MissingParameterValue(_(
  836. "SNMP driver requires `snmp_community` or "
  837. "`snmp_community_read`/`snmp_community_write` properties "
  838. "to be set for version %s.") % snmp_info['version'])
  839. snmp_info['read_community'] = read_community
  840. snmp_info['write_community'] = write_community
  841. elif snmp_info['version'] == SNMP_V3:
  842. snmp_info.update(_parse_driver_info_snmpv3_user(node, info))
  843. snmp_info.update(_parse_driver_info_snmpv3_crypto(node, info))
  844. snmp_info.update(_parse_driver_info_snmpv3_context(node, info))
  845. # Target PDU IP address and power outlet identification
  846. snmp_info['address'] = info['snmp_address']
  847. outlet = info['snmp_outlet']
  848. try:
  849. snmp_info['outlet'] = int(outlet)
  850. except ValueError:
  851. raise exception.InvalidParameterValue(_(
  852. "SNMPPowerDriver: PDU power outlet index is not an integer: %s")
  853. % outlet)
  854. return snmp_info
  855. def _get_driver(node):
  856. """Return a new SNMP driver object of the correct type for `node`.
  857. :param node: Single node object.
  858. :raises: InvalidParameterValue if node power config is incomplete or
  859. invalid.
  860. :returns: SNMP driver object.
  861. """
  862. snmp_info = _parse_driver_info(node)
  863. cls = DRIVER_CLASSES[snmp_info['driver']]
  864. return cls(snmp_info)
  865. class SNMPPower(base.PowerInterface):
  866. """SNMP Power Interface.
  867. This PowerInterface class provides a mechanism for controlling the power
  868. state of a physical device using an SNMP-enabled smart power controller.
  869. """
  870. def get_properties(self):
  871. """Return the properties of the interface.
  872. :returns: dictionary of <property name>:<property description> entries.
  873. """
  874. return COMMON_PROPERTIES
  875. def validate(self, task):
  876. """Check that node.driver_info contains the requisite fields.
  877. :raises: MissingParameterValue if required SNMP parameters are missing.
  878. :raises: InvalidParameterValue if SNMP parameters are invalid.
  879. """
  880. _parse_driver_info(task.node)
  881. def get_power_state(self, task):
  882. """Get the current power state.
  883. Poll the SNMP device for the current power state of the node.
  884. :param task: An instance of `ironic.manager.task_manager.TaskManager`.
  885. :raises: MissingParameterValue if required SNMP parameters are missing.
  886. :raises: InvalidParameterValue if SNMP parameters are invalid.
  887. :raises: SNMPFailure if an SNMP request fails.
  888. :returns: power state. One of :class:`ironic.common.states`.
  889. """
  890. driver = _get_driver(task.node)
  891. power_state = driver.power_state()
  892. return power_state
  893. @task_manager.require_exclusive_lock
  894. def set_power_state(self, task, pstate, timeout=None):
  895. """Turn the power on or off.
  896. Set the power state of a node.
  897. :param task: An instance of `ironic.manager.task_manager.TaskManager`.
  898. :param pstate: Either POWER_ON or POWER_OFF from :class:
  899. `ironic.common.states`.
  900. :param timeout: timeout (in seconds). Unsupported by this interface.
  901. :raises: MissingParameterValue if required SNMP parameters are missing.
  902. :raises: InvalidParameterValue if SNMP parameters are invalid or
  903. `pstate` is invalid.
  904. :raises: PowerStateFailure if the final power state of the node is not
  905. as requested after the timeout.
  906. :raises: SNMPFailure if an SNMP request fails.
  907. """
  908. # TODO(rloo): Support timeouts!
  909. if timeout is not None:
  910. LOG.warning(
  911. "The 'snmp' Power Interface's 'set_power_state' method "
  912. "doesn't support the 'timeout' parameter. Ignoring "
  913. "timeout=%(timeout)s",
  914. {'timeout': timeout})
  915. driver = _get_driver(task.node)
  916. if pstate == states.POWER_ON:
  917. state = driver.power_on()
  918. elif pstate == states.POWER_OFF:
  919. state = driver.power_off()
  920. else:
  921. raise exception.InvalidParameterValue(_("set_power_state called "
  922. "with invalid power "
  923. "state %s.") % str(pstate))
  924. if state != pstate:
  925. raise exception.PowerStateFailure(pstate=pstate)
  926. @task_manager.require_exclusive_lock
  927. def reboot(self, task, timeout=None):
  928. """Cycles the power to a node.
  929. :param task: An instance of `ironic.manager.task_manager.TaskManager`.
  930. :param timeout: timeout (in seconds). Unsupported by this interface.
  931. :raises: MissingParameterValue if required SNMP parameters are missing.
  932. :raises: InvalidParameterValue if SNMP parameters are invalid.
  933. :raises: PowerStateFailure if the final power state of the node is not
  934. POWER_ON after the timeout.
  935. :raises: SNMPFailure if an SNMP request fails.
  936. """
  937. # TODO(rloo): Support timeouts!
  938. if timeout is not None:
  939. LOG.warning("The 'snmp' Power Interface's 'reboot' method "
  940. "doesn't support the 'timeout' parameter. Ignoring "
  941. "timeout=%(timeout)s",
  942. {'timeout': timeout})
  943. driver = _get_driver(task.node)
  944. state = driver.power_reset()
  945. if state != states.POWER_ON:
  946. raise exception.PowerStateFailure(pstate=states.POWER_ON)