1# -*- coding: utf-8 -*-
2# This code is part of Ansible, but is an independent component.
3# This particular file snippet, and this file snippet only, is BSD licensed.
4# Modules you write using this snippet, which is embedded dynamically by
5# Ansible still belong to the author of the module, and may assign their
6# own license to the complete work.
7#
8# Copyright (C) 2017 Lenovo, Inc.
9# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
10#
11# Contains LXCA common class
12# Lenovo xClarity Administrator (LXCA)
13
14from __future__ import (absolute_import, division, print_function)
15__metaclass__ = type
16
17import traceback
18try:
19    from pylxca import connect, disconnect
20    HAS_PYLXCA = True
21except ImportError:
22    HAS_PYLXCA = False
23
24
25PYLXCA_REQUIRED = "Lenovo xClarity Administrator Python Client (Python package 'pylxca') is required for this module."
26
27
28def has_pylxca(module):
29    """
30    Check pylxca is installed
31    :param module:
32    """
33    if not HAS_PYLXCA:
34        module.fail_json(msg=PYLXCA_REQUIRED)
35
36
37LXCA_COMMON_ARGS = dict(
38    login_user=dict(required=True),
39    login_password=dict(required=True, no_log=True),
40    auth_url=dict(required=True),
41)
42
43
44class connection_object:
45    def __init__(self, module):
46        self.module = module
47
48    def __enter__(self):
49        return setup_conn(self.module)
50
51    def __exit__(self, type, value, traceback):
52        close_conn()
53
54
55def setup_conn(module):
56    """
57    this function create connection to LXCA
58    :param module:
59    :return:  lxca connection
60    """
61    lxca_con = None
62    try:
63        lxca_con = connect(module.params['auth_url'],
64                           module.params['login_user'],
65                           module.params['login_password'],
66                           "True")
67    except Exception as exception:
68        error_msg = '; '.join(exception.args)
69        module.fail_json(msg=error_msg, exception=traceback.format_exc())
70    return lxca_con
71
72
73def close_conn():
74    """
75    this function close connection to LXCA
76    :param module:
77    :return:  None
78    """
79    disconnect()
80