def __init__(self):
        self.module = AnsibleModule(argument_spec=self.argument_spec, supports_check_mode=False)
        if not HAS_HPE_ONEVIEW:
            self.module.fail_json(msg=HPE_ONEVIEW_SDK_REQUIRED)

        if not self.module.params['config']:
            self.oneview_client = OneViewClient.from_environment_variables()
        else:
            self.oneview_client = OneViewClient.from_json_file(self.module.params['config'])
 def test_from_environment_variables_is_passing_right_arguments_to_the_constructor(self, mock_cls):
     mock_cls.return_value = None
     OneViewClient.from_environment_variables()
     mock_cls.assert_called_once_with({'api_version': 201,
                                       'proxy': '172.16.100.195:9999',
                                       'ip': '172.16.100.199',
                                       'image_streamer_ip': '172.172.172.172',
                                       'credentials':
                                           {'password': '******',
                                            'authLoginDomain': 'authdomain',
                                            'userName': '******'}})
Exemplo n.º 3
0
 def _create_oneview_client(self):
     if self.module.params.get('hostname'):
         config = dict(ip=self.module.params['hostname'],
                       credentials=dict(userName=self.module.params['username'], password=self.module.params['password']),
                       api_version=self.module.params['api_version'],
                       image_streamer_ip=self.module.params['image_streamer_hostname'])
         self.oneview_client = OneViewClient(config)
     elif not self.module.params['config']:
         self.oneview_client = OneViewClient.from_environment_variables()
     else:
         self.oneview_client = OneViewClient.from_json_file(self.module.params['config'])
 def test_from_environment_variables_is_passing_right_arguments_to_the_constructor_with_only_sessionID(self, mock_cls):
     mock_cls.return_value = None
     OneViewClient.from_environment_variables()
     mock_cls.assert_called_once_with({'api_version': 300,
                                       'proxy': '',
                                       'timeout': None,
                                       'ip': '172.16.100.199',
                                       'image_streamer_ip': '',
                                       'ssl_certificate': '',
                                       'credentials':
                                           {'userName': '',
                                            'password': '',
                                            'authLoginDomain': '',
                                            'sessionID': '123'}})
    def test_create_image_streamer_client_without_image_streamer_ip(self, mock_login):

        config = {"ip": "172.16.102.59",
                  "credentials": {
                      "userName": "******",
                      "password": "******"}}

        client = OneViewClient(config)
        client.connection.set_session_id('123')

        i3s = client.create_image_streamer_client()

        self.assertEqual(i3s.connection.get_session_id(), client.connection.get_session_id())
        self.assertEqual(i3s.connection._apiVersion, client.api_version)
        self.assertEqual(i3s.connection.get_host(), None)
        self.assertEqual(client.connection.get_host(), "172.16.102.59")
    def test_from_minimal_environment_variables(self, mock_set_proxy, mock_login):
        oneview_client = OneViewClient.from_environment_variables()

        mock_login.assert_called_once_with(dict(userName='******',
                                                password='******',
                                                authLoginDomain=''))
        mock_set_proxy.assert_not_called()
        self.assertEqual(300, oneview_client.connection._apiVersion)
    def __init__(self):
        self.module = AnsibleModule(argument_spec=self.argument_spec, supports_check_mode=False)
        if not HAS_HPE_ONEVIEW:
            self.module.fail_json(msg=HPE_ONEVIEW_SDK_REQUIRED)
        if not self.module.params['config']:
            logical_interconnects = OneViewClient.from_environment_variables().logical_interconnects
        else:
            logical_interconnects = OneViewClient.from_json_file(self.module.params['config']).logical_interconnects

        self.resource_client = logical_interconnects
        self.options = dict(
            qos_aggregated_configuration=logical_interconnects.get_qos_aggregated_configuration,
            snmp_configuration=logical_interconnects.get_snmp_configuration,
            port_monitor=logical_interconnects.get_port_monitor,
            internal_vlans=logical_interconnects.get_internal_vlans,
            forwarding_information_base=logical_interconnects.get_forwarding_information_base,
            firmware=logical_interconnects.get_firmware,
            unassigned_uplink_ports=logical_interconnects.get_unassigned_uplink_ports,
            telemetry_configuration=logical_interconnects.get_telemetry_configuration,
        )
    def test_from_full_environment_variables(self, mock_set_proxy, mock_login):
        oneview_client = OneViewClient.from_environment_variables()

        mock_login.assert_called_once_with(dict(userName='******',
                                                password='******',
                                                authLoginDomain='authdomain'))
        mock_set_proxy.assert_called_once_with('172.16.100.195', 9999)

        self.assertEqual(201, oneview_client.connection._apiVersion)
        self.assertEqual(oneview_client.create_image_streamer_client().connection.get_host(),
                         OS_ENVIRON_CONFIG_FULL['ONEVIEWSDK_IMAGE_STREAMER_IP'])
    def test_from_json_file_with_only_sessionID(self, mock_open, mock_login):
        json_config_content = u"""{
          "ip": "172.16.102.59",
          "credentials": {
            "sessionID": "123"
          }
        }"""
        mock_open.return_value = self.__mock_file_open(json_config_content)
        oneview_client = OneViewClient.from_json_file("config.json")

        self.assertIsInstance(oneview_client, OneViewClient)
        self.assertEqual("172.16.102.59", oneview_client.connection.get_host())
    def test_default_api_version(self, mock_open, mock_login):
        json_config_content = u"""{
          "ip": "172.16.102.59",
          "credentials": {
            "userName": "******",
            "authLoginDomain": "",
            "password": ""
          }
        }"""
        mock_open.return_value = self.__mock_file_open(json_config_content)
        oneview_client = OneViewClient.from_json_file("config.json")

        self.assertEqual(200, oneview_client.connection._apiVersion)
Exemplo n.º 11
0
    def test_from_json_file(self, mock_open, mock_login):
        json_config_content = u"""{
          "ip": "172.16.102.59",
          "credentials": {
            "userName": "******",
            "authLoginDomain": "",
            "password": ""
          }
        }"""
        mock_open.return_value = self.__mock_file_open(json_config_content)
        oneview_client = OneViewClient.from_json_file("config.json")

        self.assertIsInstance(oneview_client, OneViewClient)
        self.assertEqual("172.16.102.59", oneview_client.connection.get_host())
Exemplo n.º 12
0
def main():

    global config

    parser = argparse.ArgumentParser(add_help=True, description='Usage')
    parser.add_argument('-i',
                        '--input_file',
                        dest='input_file',
                        required=True,
                        help='Json file containing oneview and nagios details')

    # Check and parse the input arguments into python's format
    inputFile = parser.parse_args()
    # Parsing file for details
    with open(inputFile.input_file) as data_file:
        inputConfig = json.load(data_file)
    # get the logging level
    loggingLevel = inputConfig["logging_level"].upper()
    # get refresh duration
    refreshDuration = inputConfig['stats_refresh_duration']

    try:
        # Validate the data in the OneView config files.
        oneViewDetails = inputConfig["oneview_config"]
        # Validate the data in the Nagios config files.
        nagiosDetails = inputConfig["nagios_config"]

    except Exception as e:
        # We will not be able to log this message since logging is not yet initialized, hence printing
        print("Error in config files. Check and try again.")
        print(e)
        sys.exit(1)

    # Initialize logging
    initialize_logging(oneViewDetails['host'], loggingLevel)

    # Valid alert types sent by Oneview. This is used to compare the user input "alert_type" from oneview.json file
    alertTypes = ['Ok', 'Warning', 'Critical', 'Unknown']
    hardwareTypes = [
        'server-hardware', 'enclosures', 'interconnects', 'sas-interconnects',
        'logical-interconnects'
    ]

    # Validate input file
    ret = validate_input_config(oneViewDetails, nagiosDetails, hardwareTypes,
                                alertTypes)
    if ret == 0:
        logging.info("Successfully validated input file")

    if not loggingLevel:
        logging.info(
            "\"logging_level\" is not provided, taken\"WARNING\" as default.")
    if not refreshDuration:
        logging.info(
            "\"stats_refresh_duration\" is not provided, taking 120s as default."
        )
        refreshDuration = '120'

    # append global dict with required values
    config['oneViewIP'] = oneViewDetails['host']
    config['nagiosDetails'] = nagiosDetails
    config['alertHardwareTypes'] = oneViewDetails[
        "alert_hardware_category"].split(':')
    inputAlertTypes = oneViewDetails["alert_type"].split(':')
    config['inputAlertTypes'] = [x.lower() for x in inputAlertTypes
                                 ]  # User interested alert types

    # Logging input details.
    logging.info('OneView args: host = %s, alias = %s, route = %s, action = %s, process_onetime_alerts = %s, events_dated_from = %s', \
     oneViewDetails["host"], oneViewDetails["alias"], oneViewDetails["route"], oneViewDetails["action"], \
     oneViewDetails["process_onetime_alerts"], oneViewDetails["events_dated_from"])

    logging.info('Nagios args: nagiosHost = %s ', nagiosDetails["nagiosHost"])

    # Esatblish connection to OneView
    if oneViewDetails["action"] == "start":
        logging.debug("Attempting to establish connection with OV SCMB")
        logging.debug("Arguments: " + str(oneViewDetails))

        ovConfig = {
            "ip": oneViewDetails["host"],
            "credentials": {
                "userName": oneViewDetails["user"],
                "password": oneViewDetails["passwd"]
            }
        }

        try:
            oneview_client = OneViewClient(ovConfig)
            acceptEULA(oneview_client)
            logging.info("Connected to OneView appliance : {}".format(
                oneViewDetails["host"]))
        #except HPOneViewException as e:
        except Exception as e:
            #logging.error("Error connecting to appliance: msg: %s", e.msg)
            logging.error(
                "Error connecting to appliance. Check for OneView details in input json file."
            )
            logging.error(e)
            sys.exit(1)

        # Create Infrastructure in Nagios server
        create_infra_in_nagios(oneview_client, oneViewDetails, nagiosDetails)
        logging.info(
            "Infra created if not present already. Processing alerts now.")
        sleep(1)

        # Process alerts onetime at the beginning based on user's input in json file
        ret = process_alerts_one_time(oneview_client, oneViewDetails,
                                      nagiosDetails, config['inputAlertTypes'],
                                      config['alertHardwareTypes'])
        if (ret != 0):
            print("One-time processing of alerts failed.")

        # Create certs directory for storing the OV certificates
        initialize_certs()

        # Download the certificates
        getCertCa(oneview_client, oneViewDetails["host"])
        getRabbitKp(oneview_client, oneViewDetails["host"])

        # Creating new process for polling processes
        pollProcess = mp.Process(target=process_threads,
                                 args=(
                                     oneview_client,
                                     nagiosDetails,
                                     config['alertHardwareTypes'],
                                     int(refreshDuration),
                                 ))
        pollProcess.start()

        # Start listening for messages.
        recv(oneViewDetails["host"], oneViewDetails["route"])

        # Join Process pollProcess.
        pollProcess.join()

        print("Closing Thread Pool!")
        mpThreadPool.close()
        # Join the Pool
        mpThreadPool.join()

    elif oneViewDetails["action"] == "stop":
        # Stop SCMB connection for this appliance
        logging.info("TODO: stop action implementation")
        # stopSCMB(oneViewDetails.host)
    else:
        # Do nothing and exit
        logging.error(
            "Missing or invalid option for action in oneview.json; It should be start/stop."
        )
        print(
            "Missing or invalid option for action in oneview.json; It should be start/stop."
        )
Exemplo n.º 13
0
from hpOneView.oneview_client import OneViewClient
from hpOneView.exceptions import HPOneViewException
from config_loader import try_load_from_file

config = {
    "ip": "",
    "credentials": {
        "userName": "******",
        "password": ""
    }
}

# Try load config from a file (if there is a config file)
config = try_load_from_file(config)

oneview_client = OneViewClient(config)

# An existent Logical Downlink ID is required to run this example
logical_downlink_id = '246c3202-f4c8-4c92-9266-5e7b01c0598e'

# Get logical downlink by id
try:
    print("Get logical downlink by id")
    log_downlink = oneview_client.logical_downlinks.get(logical_downlink_id)
    pprint(log_downlink)
except HPOneViewException as e:
    print(e.msg)

# Get logical downlink by id without Ethernet networks
try:
    print("Get logical downlink by id without Ethernet networks")
Exemplo n.º 14
0
 def __create_oneview_client(self):
     if not self.module.params['config']:
         self.oneview_client = OneViewClient.from_environment_variables()
     else:
         self.oneview_client = OneViewClient.from_json_file(self.module.params['config'])
Exemplo n.º 15
0
remote_server_options = {
    "name": "172.18.13.11",
}

options = {
    "certificateDetails": [{
        "aliasName": "vcenter",
        "base64Data": "",
        "type": "CertificateDetailV2"
    }],
}

# Try load config from a file (if there is a config file)
config = try_load_from_file(config)
oneview_client = OneViewClient.config()
certificate_server = oneview_client.certificates_server

# Fetch server certificate of remote server
print("\nGet server certificate of remote server by ip address")
remote_server_cert = certificate_server.get_remote(
    remote_server_options['name'])
ca_certificate = remote_server_cert.data['certificateDetails'][0]['base64Data']
print(ca_certificate)

# Fetch certificate by alias name
print("\nGet server certificate by alias name")
server_certificate = certificate_server.get_by_alias_name("vcenter")
if server_certificate:
    print("\nFound server certificate by aliasName: {}.\n  uri = {}".format(
        server_certificate.data['certificateDetails'][0]['aliasName'],
# HudsonAlpha Institute for Biotechnology
# This code is under the MIT license, view the complete file at https://github.com/HudsonAlpha/synergy/blob/master/LICENSE
#

import os
import sys
import argparse
import importlib
from pprint import pprint
from hpOneView.oneview_client import OneViewClient
from hpOneView.exceptions import HPOneViewException

#
# Load OneView credentials from a file
#
oneview_client = OneViewClient.from_json_file('/hpov/haconfig.json')

#
# Arguments
#
parser = argparse.ArgumentParser(
    description='Provision node from ImageStreamer Deployment Plan')
parser.add_argument('CONFIG_FILE', help='name of the configuration file')
parser.add_argument('-v',
                    '--verbosity',
                    action='count',
                    default=0,
                    help='increase output verbosity')
args = parser.parse_args()

#
Exemplo n.º 17
0
    delete_list = []
    for profile in profile_list:
        delete_list.append(dict(name=profile['name'],uri=profile['uri'],hwuri=profile['serverHardwareUri']))
    sorted_delete = sorted(delete_list, key=lambda k: k['name'], reverse=True)

    deleted = []

    for index in range(profile_count):
        # iterate through the number of servers to remove
        print ("deleting profile : %s"%sorted_delete[index]['name'])
        try:
            ov_client.server_hardware.update_power_state(dict(powerState="Off", powerControl="MomentaryPress"),
                                                         sorted_delete[index]['hwuri'])
        except HPOneViewException as e:
            print(e.msg)
        try:
            ov_client.server_profiles.delete(sorted_delete[index]['uri'])
        except HPOneViewException as e:
            print(e.msg)
        deleted.append(sorted_delete[index]['name'])

    return make_response(jsonify({'status':'Deleting','requested':profile_count,'profiles':deleted}))


if __name__ == '__main__':
    # Connect to OneView
    print("\n\nhpe-oneview service started\n\n")
    ov_client = OneViewClient.from_environment_variables()
    get_profile_status()
    app.run(host="0.0.0.0",debug=True)
 def __init__(self):
     self.module = AnsibleModule(argument_spec=self.argument_spec, supports_check_mode=False)
     if not self.module.params['config']:
         self.oneview_client = OneViewClient.from_environment_variables()
     else:
         self.oneview_client = OneViewClient.from_json_file(self.module.params['config'])
Exemplo n.º 19
0
#   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.
###

import os
from pprint import pprint
from hpOneView.oneview_client import OneViewClient

EXAMPLE_CONFIG_FILE = os.path.join(os.path.dirname(__file__), '../config.json')

oneview_client = OneViewClient.from_json_file(EXAMPLE_CONFIG_FILE)

image_streamer_client = oneview_client.create_image_streamer_client()

plan_script_information = {
    "description": "Description of this plan script",
    "name": "Demo Plan Script",
    "hpProvided": False,
    "planType": "deploy",
    "content": 'echo "test script"'
}

# plan script which is used by buils plans and is readonly
plan_script_id_readyonly = "590746df-7354-42aa-8887-e1ea122f7ed6"

# Create a Plan Script
Exemplo n.º 20
0
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###

import os
from pprint import pprint
from hpOneView.oneview_client import OneViewClient

EXAMPLE_CONFIG_FILE = os.path.join(os.path.dirname(__file__), '../config.json')

oneview_client = OneViewClient.from_json_file(EXAMPLE_CONFIG_FILE)

image_streamer_client = oneview_client.create_image_streamer_client()

build_plan_information = {
    "name": "Demo Build Plan",
    "oeBuildPlanType": "deploy"
}

# Create a Build Plan
print("Create an OS Build Plan")
build_plan_created = image_streamer_client.build_plans.create(build_plan_information)
pprint(build_plan_created)

# Update the Build Plan
print("\nUpdate the OS Build Plan")
Exemplo n.º 21
0
def main():
    parser = argparse.ArgumentParser(add_help=True, description='Usage')
    parser.add_argument('-i', '--input_file',
                        dest='input_file',
                        required=False,
                        help='Json file containing oneview details')

    # Check and parse the input arguments into python's format
    inputParser = parser.parse_args()
    inputConfig = conf.getInputConfig(inputParser.input_file)
    oneviewDetails = inputConfig["oneview_config"]

    # Initialize logging
    ovlog.initialize_logging(syslogDir=oneviewDetails.get('syslogDir'),
                             syslogFile=oneviewDetails.get('syslog'))


    # get the logging level
    if inputConfig["logging_level"]:
        logLevel = logging.getLevelName(inputConfig["logging_level"].upper())
        logging.getLogger().setLevel(logLevel)

    # Get OneView Password
    if not oneviewDetails.get('passwd'):
        if "OV_PASSWORD" in environ:
            oneviewDetails["passwd"] = environ["OV_PASSWORD"]
        else:
            raise Exception("Missing oneview password. Please define " +
                            "the password in the input file or " +
                            "export OV_PASSWORD")
    else:
        password = base64.b64decode(oneviewDetails['passwd'].encode('utf-8'))
        oneviewDetails['passwd'] = password.decode('utf-8')

    conf.validate_input(oneviewDetails)

    # Logging input details.
    logging.info('OneView args: host = %s, alias = %s, route = %s', \
        oneviewDetails["host"], oneviewDetails["alias"], oneviewDetails["route"])

    ovConfig = {
        "ip": oneviewDetails["host"],
        "credentials": {
            "userName": oneviewDetails["user"],
            "password": oneviewDetails["passwd"],
            "authLoginDomain": oneviewDetails['authLoginDomain']
        },
        'api_version': 600
    }

    try:
        oneview_client = OneViewClient(ovConfig)
        acceptEULA(oneview_client)
        logging.info("Connected to OneView appliance : {}".format(oneviewDetails["host"]))
    except Exception as e:
        err = "Error connecting to appliance: {}\n Check for oneview details in the input file".format(e)
        logging.error(e)
        raise Exception(err)

    print("Connected to OneView appliance : {}".format(oneviewDetails["host"]))
    ovlog.create_server_map(oneview_client)

     # Create certs directory for storing the OV certificates
    #ovscmb.setupAmqpCerts(oneview_client, oneviewDetails["host"])
    ovscmb.setupAmqpCerts(oneview_client, oneviewDetails)


    if oneviewDetails['collect_stats']:
        # Creating new process for polling processes
        #pollProcess = mp.Process(target=process_threads, args=(oneview_client, conf['alertHardwareTypes'], int(refreshDuration), ))
        pollProcess = mp.Process(target=polling.process_threads,
                                 args=(oneview_client,
                                       oneviewDetails['alert_hardware_category'],
                                       oneviewDetails['refresh_interval'], ))
        pollProcess.start()

    if oneviewDetails['collect_hpeov_service_info']:
        # Creating new process for polling HPE OV Service tickets
        hpeTicketProcess = mp.Process(target=polling.collect_hpeov_service_info,
                                      args=(oneview_client, ))
        hpeTicketProcess.start()

    # Logging all active alerts to syslog
    ovlog.logAlerts(oneview_client, "activeAlerts")

    # Start listening for messages.
    ovscmb.recv(oneviewDetails["host"], oneviewDetails["route"])