Пример #1
0
 def execute_cmd(self, cmd):
     """
     Execute the command.
     """
     if self._session is None:
         if isinstance(self._session_id, zhmcclient_mock.FakedSession):
             self._session = self._session_id
         else:
             if self._host is None:
                 raise click_exception("No HMC host provided",
                                       self._error_format)
             if self._no_verify:
                 verify_cert = False
             elif self._ca_certs is None:
                 verify_cert = True  # Use 'certifi' package
             else:
                 verify_cert = self._ca_certs
             self._session = zhmcclient.Session(
                 self._host,
                 self._userid,
                 self._password,
                 session_id=self._session_id,
                 get_password=self._get_password,
                 verify_cert=verify_cert)
     if self.timestats:
         self._session.time_stats_keeper.enable()
     self.spinner.start()
     try:
         cmd()
     except zhmcclient.Error as exc:
         raise click_exception(exc, self.error_format)
     finally:
         self.spinner.stop()
         if self._session.time_stats_keeper.enabled:
             click.echo(self._session.time_stats_keeper)
def zhmc_cpc_facts(data):

    auth_hmc = data['auth_hmc']
    auth_userid = data['auth_userid']
    auth_password = data['auth_password']
    cpc_name = data['cpc_name']
    detailed = data['detailed']
    changed = False

    try:
        session = zhmcclient.Session(auth_hmc, auth_userid, auth_password)
        client = zhmcclient.Client(session)
        if detailed is None:
            detailed = False
        if cpc_name:
            cpc = client.cpcs.find(name=cpc_name, full_properties=detailed)
            result = cpc.properties
        else:
            cpcs = client.cpcs.list(detailed)
            cpc_list = list()
            for cpc in cpcs:
                cpc_list.append(cpc.properties)
            result = cpc_list

        session.logoff()
        return False, changed, result

    except zhmcclient.Error as exc:
        session.logoff()
        return True, False, str(exc)
def create_session(cred_dict, hmccreds_filename):
    """
    To create a context, a session must be created first.

    Parameters:
      cred_dict (dict): 'metric' object from the HMC credentials file,
        specifying items: hmc, userid, password, verify_cert.
      hmccreds_filename (string): Path name of HMC credentials file.

    Returns:
      zhmcclient.Session
    """

    # These warnings do not concern us
    urllib3.disable_warnings()

    verify_cert = cred_dict.get("verify_cert", True)
    if isinstance(verify_cert, six.string_types):
        if not os.path.isabs(verify_cert):
            verify_cert = os.path.join(os.path.dirname(hmccreds_filename),
                                       verify_cert)
    verbose("HMC certificate validation: {}".format(verify_cert))

    session = zhmcclient.Session(cred_dict["hmc"],
                                 cred_dict["userid"],
                                 cred_dict["password"],
                                 verify_cert=verify_cert,
                                 retry_timeout_config=RETRY_TIMEOUT_CONFIG)
    return session
Пример #4
0
def zhmc_deactivate(data):

    auth_hmc = data['auth_hmc']
    auth_userid = data['auth_userid']
    auth_password = data['auth_password']
    cpc_name = data['cpc_name']
    lpar_name = data['lpar_name']
    changed = False
    result = "Nothing"

    try:
        session = zhmcclient.Session(auth_hmc, auth_userid, auth_password)
        client = zhmcclient.Client(session)
        cpc = client.cpcs.find(name=cpc_name)
        lpar = cpc.lpars.find(name=lpar_name)

        if lpar.properties['status'] in [
                "operating", "not-operating", "exceptions"
        ]:
            result = lpar.deactivate()
            changed = True
        session.logoff()
        return False, changed, result

    except zhmcclient.Error as exc:
        session.logoff()
        return True, False, str(exc)
Пример #5
0
def zhmc_activate(data):

    auth_hmc = data['auth_hmc']
    auth_userid = data['auth_userid']
    auth_password = data['auth_password']
    cpc_name = data['cpc_name']
    lpar_name = data['lpar_name']
    load_address = data['load']
    changed = False

    try:
        session = zhmcclient.Session(auth_hmc, auth_userid, auth_password)
        client = zhmcclient.Client(session)
        cpc = client.cpcs.find(name=cpc_name)
        lpar = cpc.lpars.find(name=lpar_name)

        if lpar.properties['status'] in ["not-activated"]:
            result = lpar.activate()
            lpar = cpc.lpars.find(name=lpar_name)
            changed = True
        if lpar.properties['status'] not in ["operating"] and load_address:
            result = lpar.load(load_address)
            changed = True
        session.logoff()
        return False, changed, result

    except zhmcclient.Error as exc:
        session.logoff()
        return True, False, str(exc)
Пример #6
0
def create_session(cred_dict):
    """To create a context, a session must be created first.
    Takes a dictionary with the HMC IP, the user ID, and a password.
    Returns the session.
    """
    # These warnings do not concern us
    urllib3.disable_warnings()
    session = zhmcclient.Session(cred_dict["hmc"], cred_dict["userid"],
                                 cred_dict["password"])
    return session
def zhmc_api_version(data):

    hmc = data['auth_hmc']
    session = zhmcclient.Session(hmc)
    cl = zhmcclient.Client(session)

    result = cl.query_api_version()

    # default: something went wrong
    meta = {'response': result}
    return False, False, meta
Пример #8
0
    def test_2_hmcs(self, capsys):
        """
        Check out the HMCs specified in the HMC credentials file.
        Skip HMCs that cannot be contacted.
        """

        cpc_items = self.hmc_creds.get_cpc_items()

        if cpc_items is None:
            info(capsys, "HMC credentials file not found: %r - Skipping the "
                 "checking of HMCs", self.hmc_creds.filepath)
            return

        rt_config = zhmcclient.RetryTimeoutConfig(
            connect_timeout=10,
            connect_retries=1,
        )

        # Check HMCs and their CPCs
        for cpc_name in cpc_items:

            cpc_item = cpc_items[cpc_name]

            hmc_host = cpc_item['hmc_host']

            info(capsys, "Checking HMC %r for CPC %r", (hmc_host, cpc_name))

            session = zhmcclient.Session(
                hmc_host, cpc_item['hmc_userid'], cpc_item['hmc_password'],
                retry_timeout_config=rt_config)

            client = zhmcclient.Client(session)

            try:
                session.logon()
            except zhmcclient.ConnectionError as exc:
                info(capsys, "Skipping HMC %r for CPC %r: %s",
                     (hmc_host, cpc_name, exc))
                continue

            cpcs = client.cpcs.list()
            cpc_names = [cpc.name for cpc in cpcs]
            if cpc_name not in cpc_names:
                raise AssertionError(
                    "CPC {!r} not found in HMC {!r}.\n"
                    "Existing CPCs: {!r}".
                    format(cpc_name, hmc_host, cpc_names))

            session.logoff()
Пример #9
0
 def execute_cmd(self, cmd):
     if self._session is None:
         if isinstance(self._session_id, zhmcclient_mock.FakedSession):
             self._session = self._session_id
         else:
             if self._host is None:
                 raise_click_exception("No HMC host provided",
                                       self._error_format)
             self._session = zhmcclient.Session(
                 self._host, self._userid, self._password,
                 session_id=self._session_id,
                 get_password=self._get_password)
     if self.timestats:
         self._session.time_stats_keeper.enable()
     self.spinner.start()
     try:
         cmd()
     finally:
         self.spinner.stop()
         if self._session.time_stats_keeper.enabled:
             click.echo(self._session.time_stats_keeper)
Пример #10
0
def make_client(zhmc, userid=None, password=None):
    """
    Create a `Session` object for the specified HMC and log that on. Create a
    `Client` object using that `Session` object, and return it.

    If no userid and password are specified, and if no previous call to this
    method was made, userid and password are interactively inquired.
    Userid and password are saved in module-global variables for future calls
    to this method.
    """

    global USERID, PASSWORD  # pylint: disable=global-statement

    USERID = userid or USERID or \
        six.input('Enter userid for HMC {}: '.format(zhmc))
    PASSWORD = password or PASSWORD or \
        getpass.getpass('Enter password for {}: '.format(USERID))

    session = zhmcclient.Session(zhmc, USERID, PASSWORD)
    session.logon()
    client = zhmcclient.Client(session)
    print('Established logged-on session with HMC {} using userid {}'.
          format(zhmc, USERID))
    return client
Пример #11
0
cpcname = show_os_messages["cpcname"]
partname = show_os_messages["partname"]

cred = hmccreds.get(hmc, None)
if cred is None:
    print("Credentials for HMC %s not found in credentials file %s" % \
          (hmc, hmccreds_file))
    sys.exit(1)

userid = cred['userid']
password = cred['password']

print(__doc__)

print("Using HMC %s with userid %s ..." % (hmc, userid))
session = zhmcclient.Session(hmc, userid, password)
cl = zhmcclient.Client(session)

timestats = show_os_messages.get("timestats", False)
if timestats:
    session.time_stats_keeper.enable()

try:
    cpc = cl.cpcs.find(name=cpcname)
except zhmcclient.NotFound:
    print("Could not find CPC %s on HMC %s" % (cpcname, hmc))
    sys.exit(1)

try:
    if cpc.dpm_enabled:
        partkind = "partition"
Пример #12
0
def hmc_session(request, hmc_definition):
    """
    Pytest fixture representing the set of `zhmcclient.Session` objects to use
    for the end2end tests.

    Because the `hmc_definition` parameter of this fixture is again a fixture,
    `hmc_definition` needs to be imported as well when this fixture is used.

    Returns a `zhmcclient.Session` object that is logged on to the HMC.

    Upon teardown, the `zhmcclient.Session` object is logged off.
    """
    hd = hmc_definition

    # We use the cached skip reason from previous attempts
    skip_msg = getattr(hd, 'skip_msg', None)
    if skip_msg:
        pytest.skip("Skip reason from earlier attempt: {0}".format(skip_msg))

    if hd.faked_hmc_file:
        # A faked HMC

        # Read the faked HMC file
        filepath = os.path.join(os.path.dirname(hd.hmc_filepath),
                                hd.faked_hmc_file)
        try:
            with open(filepath) as fp:
                try:
                    data = yaml.load(fp, Loader=yamlordereddictloader.Loader)
                except (yaml.parser.ParserError,
                        yaml.scanner.ScannerError) as exc:
                    raise FakedHMCFileError(
                        "Invalid YAML syntax in faked HMC file {0!r}: {1} {2}".
                        format(filepath, exc.__class__.__name__, exc))
        except IOError as exc:
            if exc.errno == errno.ENOENT:
                raise FakedHMCFileError(
                    "The faked HMC file {0!r} was not found".format(filepath))
            else:
                raise

        client = data['faked_client']
        session = zhmcclient_mock.FakedSession(client['hmc_host'],
                                               client['hmc_name'],
                                               client['hmc_version'],
                                               client['api_version'])
        for cpc in client['cpcs']:
            session.hmc.cpcs.add(cpc['properties'])

    else:
        # A real HMC

        # Creating a session does not interact with the HMC (logon is deferred)
        session = zhmcclient.Session(hd.hmc_host, hd.hmc_userid,
                                     hd.hmc_password)

        # Check access to the HMC
        try:
            session.logon()
        except zhmcclient.Error as exc:
            msg = "Cannot log on to HMC {0} at {1} due to {2}: {3}". \
                format(hd.nickname, hd.hmc_host, exc.__class__.__name__, exc)
            hd.skip_msg = msg
            pytest.skip(msg)

    hd.skip_msg = None
    session.hmc_definition = hd

    yield session

    session.logoff()
Пример #13
0
if examples is None:
    print("examples not found in credentials file %s" % \
          (hmccreds_file))
    sys.exit(1)

api_version = examples.get("api_version", None)
if api_version is None:
    print("api_version not found in credentials file %s" % \
          (hmccreds_file))
    sys.exit(1)

loglevel = api_version.get("loglevel", None)
if loglevel is not None:
    level = getattr(logging, loglevel.upper(), None)
    if level is None:
        print("Invalid value for loglevel in credentials file %s: %s" % \
              (hmccreds_file, loglevel))
        sys.exit(1)
    logging.basicConfig(level=level)

hmc = api_version["hmc"]

print(__doc__)

print("Using HMC %s with an unauthenticated session ..." % hmc)
session = zhmcclient.Session(hmc)
cl = zhmcclient.Client(session)

vi = cl.version_info()
print("HMC API version: {}.{}".format(vi[0], vi[1]))
Пример #14
0
def setup_cpc(capsys, hmc_creds, fake_data, rt_config=None):
    """
    Set up and return some objects for the CPC that is to be used for testing.

    This function uses the get_test_cpc() function to determine the CPC to be
    used for testing. If no CPC has been defined, this function sets up a faked
    CPC using the zhmcclient mock support.

    Parameters:

      capsys: The pytest 'capsys' fixture the testcase function must specify as
        an argument and pass to this functionhere.

      hmc_creds (HmcCredentials): HMC credentials with CPC data.

      fake_data (dict): Input data in case a mock environment needs to be set
        up. The dict has the following keys:

        * hmc_host (string): Hostname or IP address of the faked HMC.

        * hmc_name (string): HMC name of the faked HMC.

        * hmc_version (string): HMC version of the faked HMC.

        * api_version (string): API version of the faked HMC.

        * cpc_properties (dict): Properties for the faked CPC. 'name' must be
          set.

      rt_config (zhmcclient.RetryTimeoutConfig): Retry / timeout config
        to override the default values. The default values used by this
        function are the global defaults defined for the zhmcclient package,
        whereby connection retries, connection timeout, operation timeout, and
        status timeout have been shortened. The resulting default values should
        be good for most function testcases.

    Returns:

      tuple: Tuple with the objects thathave been set up:

        * cpc_name (string): Name of the CPC to be used (some fake name or
          the real name that has been set up).

        * session (zhmcclient.Session or zhmcclient_mock-FakedSession):
          zhmcclient session object (faked or real) to be used for accessing
          the HMC managing that CPC.

        * client (zhmcclient.Client):
          zhmcclient Client object to be used for accessing the HMC managing
          that CPC.

        * cpc (zhmcclient.Cpc): Cpc resource object representing the CPC to be
          used (faked or real).

        * faked_cpc (zhmcclient_mock.FakedCpc): FakedCpc object in case a
          mock environment was set up (so the caller can add resources to it),
          or otherwise `None`.
    """

    cpc_name = get_test_cpc()

    if cpc_name is None:

        # No test CPC defined in the environment -> use mock support and
        # add a faked CPC.

        cpc_properties = fake_data['cpc_properties']
        cpc_name = cpc_properties['name']

        info(capsys, "Testing with faked CPC %r", cpc_name)

        session = zhmcclient_mock.FakedSession(fake_data['hmc_host'],
                                               fake_data['hmc_name'],
                                               fake_data['hmc_version'],
                                               fake_data['api_version'])

        faked_cpc = session.hmc.cpcs.add(cpc_properties)

    else:
        # A test CPC is defined in the environment -> use it!

        info(capsys, "Testing with CPC %r", cpc_name)

        eff_rt_config = DEFAULT_RT_CONFIG
        if rt_config:
            eff_rt_config.override_with(rt_config)

        cpc_item = hmc_creds.get_cpc_item(cpc_name)

        assert cpc_item, "HMC credentials file not found: {!r}".\
            format(hmc_creds.filepath)

        session = zhmcclient.Session(cpc_item['hmc_host'],
                                     cpc_item['hmc_userid'],
                                     cpc_item['hmc_password'],
                                     retry_timeout_config=eff_rt_config)

        faked_cpc = None

    client = zhmcclient.Client(session)

    cpc = client.cpcs.find(name=cpc_name)

    return cpc_name, session, client, cpc, faked_cpc