예제 #1
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            ipe_package=dict(),
            boot=dict(),
            system=dict(),
            remote_dir=dict(default="flash:/"),
            delete_ipe=dict(choices=BOOLEANS, type="bool", default=False),
            reboot=dict(required=True, choices=BOOLEANS, type="bool"),
            delay=dict(type="str"),
            hostname=dict(required=True),
            username=dict(required=True),
            password=dict(required=True),
            port=dict(type="int", default=830),
        ),
        supports_check_mode=True,
    )

    if not HAS_PYHP:
        safe_fail(module, msg="There was a problem loading from the pyhpecw7 " + "module.", error=str(ie))

    ipe_package = module.params.get("ipe_package")
    boot = module.params.get("boot")
    system = module.params.get("system")

    if ipe_package:
        if boot or system:
            module.fail_json(msg="ipe_package and boot/system parameters are mutually exclusive")
    else:
        if not (boot and system):
            module.fail_json(msg="boot and system parameters must be provided if ipe_package is not")

    hostname = socket.gethostbyname(module.params["hostname"])
    username = module.params["username"]
    password = module.params["password"]
    port = module.params["port"]

    device = HPCOM7(host=hostname, username=username, password=password, port=port, timeout=150)

    changed = False

    reboot = module.params.get("reboot")
    delay = module.params.get("delay")
    already_set = False
    transfered = False

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module, device, msg=str(e), descr="Error opening connection to device.")

    try:
        ios = InstallOs(device)
        existing = ios.get_config()
    except PYHPError:
        safe_fail(module, device, msg=str(e), descr="Error getting current config.")

    existing_boot = existing["startup-primary"]["boot"]
    existing_system = existing["startup-primary"]["system"]
    remote_dir = module.params["remote_dir"]

    if ipe_package:
        ipe_basename = os.path.basename(ipe_package)
        ipe_boot_sys = re.split("-|\.", ipe_basename)[-3:-1]
        if ipe_boot_sys:
            if (
                ipe_boot_sys[0].lower() in existing_boot.lower()
                and ipe_boot_sys[0].lower() in existing_system.lower()
                and ipe_boot_sys[1].lower() in existing_boot.lower()
                and ipe_boot_sys[1].lower() in existing_system.lower()
            ):
                already_set = True

        ipe_dst = remote_dir + ipe_basename
        try:
            # preps transfer and checks if source file exists
            ipe_file_copy = FileCopy(device, ipe_package, ipe_dst)
        except PYHPError as fe:
            safe_fail(module, device, msg=str(fe), descr="Error preparing IPE file transfer.")

        if not ipe_file_copy.file_already_exists():
            try:
                ipe_file_copy.transfer_file()
                transfered = True
            except PYHPError as fe:
                safe_fail(module, device, msg=str(fe), descr="Error transfering IPE file.")

        if not already_set:
            delete_ipe = module.params.get("delete_ipe")
            ios.build("ipe", ipe=ipe_file_copy.dst, delete_ipe=delete_ipe, stage=True)
    elif boot:
        boot_basename = os.path.basename(boot)
        system_basename = os.path.basename(system)
        if boot_basename in existing_boot and system_basename in existing_system:
            already_set = True

        boot_dst = remote_dir + boot_basename
        try:
            # preps transfer and checks if source file exists
            boot_file_copy = FileCopy(device, boot, boot_dst)
        except PYHPError as fe:
            safe_fail(module, device, msg=str(fe), descr="Error preparing boot file transfer.")

        system_dst = remote_dir + system_basename
        try:
            # preps transfer and checks if source file exists
            system_file_copy = FileCopy(device, system, system_dst)
        except PYHPError as fe:
            safe_fail(module, device, msg=str(fe), descr="Error preparing system file transfer.")

        if not boot_file_copy.file_already_exists():
            try:
                boot_file_copy.transfer_file()
                transfered = True
            except PYHPError as fe:
                safe_fail(module, device, msg=str(fe), descr="Error transfering boot file.")

        if not system_file_copy.file_already_exists():
            try:
                system_file_copy.transfer_file()
                transfered = True
            except PYHPError as fe:
                safe_fail(module, device, msg=str(fe), descr="Error transfering system file.")

        if not already_set:
            ios.build("bootsys", boot=boot_file_copy.dst, system=system_file_copy.dst, stage=True)

    commands = None
    end_state = existing

    reboot_attempt = "no"
    if device.staged or transfered:
        if reboot and delay:
            reboot_attempt = "yes"
            os_reboot = Reboot(device)
            os_reboot.build(stage=True, reboot=True, delay=delay)
        commands = device.staged_to_string()
        if module.check_mode:
            safe_exit(module, device, changed=True, commands=commands, transfered=transfered, end_state=end_state)
        else:
            try:
                device.execute_staged()
                end_state = ios.get_config()
            except PYHPError as e:
                safe_fail(module, device, msg=str(e), descr="Error executing commands.")
            changed = True

    results = {}
    results["commands"] = commands
    results["transfered"] = transfered
    results["changed"] = changed
    results["end_state"] = end_state

    if reboot and not delay:
        reboot_attempt = "yes"
        try:
            device.reboot()
            changed = True

            # for some reason,
            # this is needed to activate the reboot
            try:
                device.close()
            except PYHPError:
                pass
        except PYHPError as e:
            safe_fail(module, device, msg=str(e), descr="Error rebooting the device.")

    results["reboot_attempt"] = reboot_attempt
    safe_exit(module, device, **results)
예제 #2
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            member_id=dict(type='str',
                           required=True),
            new_member_id=dict(type='str'),
            auto_update=dict(choices=['enable', 'disable']),
            domain_id=dict(type='str'),
            mad_exclude=dict(),
            priority=dict(type='str'),
            descr=dict(),
            reboot=dict(type='bool',
                        choices=BOOLEANS,
                        required=True),
            state=dict(choices=['present', 'absent'],
                       default='present'),
            hostname=dict(required=True),
            username=dict(required=True),
            password=dict(required=True),
            port=dict(type='int', default=830)
        ),
        supports_check_mode=True
    )

    if not HAS_PYHP:
        module.fail_json(
            msg='There was a problem loading from the pyhpecw7comware module')

    filtered_keys = ('hostname', 'username', 'password',
                     'port', 'CHECKMODE')

    hostname = socket.gethostbyname(module.params['hostname'])
    username = module.params['username']
    password = module.params['password']
    port = module.params['port']

    device = HPCOM7(host=hostname, username=username,
                    password=password, port=port)

    member_id = module.params.pop('member_id')
    reboot = module.params.pop('reboot')
    state = module.params.get('state')

    changed = False

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module, device, msg=str(e))

    try:
        irfm = IrfMember(device)
        existing = irfm.get_config(member_id)
    except PYHPError as e:
        if isinstance(e, IRFMemberDoesntExistError):
            new_member_id = module.params.get('new_member_id')
            try:
                if new_member_id:
                    member_id = new_member_id
                    irfm = IrfMember(device)
                    existing = irfm.get_config(member_id)
                else:
                    safe_fail(module, device, msg=str(e))
            except PYHPError as e:
                safe_fail(module, device, msg=str(e))
        else:
            safe_fail(module, device, msg=str(e))

    proposed = dict((k, v) for k, v in module.params.items()
                    if v is not None and k not in filtered_keys)

    mad_exclude = proposed.pop('mad_exclude', [])
    if isinstance(mad_exclude, str):
        mad_exclude = [mad_exclude]

    if mad_exclude:
        try:
            mad_exclude = convert_iface_list(device, mad_exclude)
        except InterfaceError as ie:
            module.fail_json(msg=str(ie))

    existing_mad_exclude = existing.pop('mad_exclude', [])
    mad_delta = list(set(mad_exclude).difference(
        existing_mad_exclude))

    delta =  dict(set(proposed.items()) - set(existing.items()))

    proposed['mad_exclude'] = mad_exclude
    existing['mad_exclude'] = existing_mad_exclude

    if state == 'present':
        if delta or mad_delta:
            try:
                irfm.build(
                    member_id=member_id, mad_exclude=mad_delta, **delta)
            except PYHPError as e:
                safe_fail(module, device, msg=str(e),
                          descr='There was an error preparing the'
                          + ' IRF membership configuration.')
    elif state == 'absent':
        remove_mad = list(set(mad_exclude).intersection(
            existing_mad_exclude))
        irfm.remove_mad_exclude(remove_mad)

    commands = None
    end_state = existing

    if device.staged:
        commands = device.staged_to_string()
        if module.check_mode:
            safe_exit(module, device, changed=True,
                      commands=commands)
        else:
            try:
                device.execute_staged()
                end_state = irfm.get_config(member_id)
            except PYHPError as e:
                safe_fail(module, device, msg=str(e))
            changed = True

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['commands'] = commands
    results['changed'] = changed
    results['end_state'] = end_state
    results['state'] = state

    new_member_id = proposed.get('new_member_id')
    mem_id_changed = False
    if new_member_id:
        mem_id_changed = proposed.get('new_member_id') != member_id
    
    if reboot and mem_id_changed:
        try:
            my_reboot = Reboot(device)
            my_reboot.build(reboot=True)
            changed = True
            device.execute_staged()
        except PYHPError as e:
            if isinstance(e, NCTimeoutError)\
                    or isinstance(e, ConnectionClosedError):
                module.exit_json(**results)
            else:
                safe_fail(module, device, msg=str(e))

    safe_exit(module, device, **results)
def main():
    module = AnsibleModule(argument_spec=dict(
        ipe_package=dict(),
        boot=dict(),
        system=dict(),
        remote_dir=dict(default='flash:/'),
        delete_ipe=dict(choices=BOOLEANS, type='bool', default=False),
        reboot=dict(required=True, choices=BOOLEANS, type='bool'),
        delay=dict(type='str'),
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True),
        port=dict(type='int', default=830)),
                           supports_check_mode=True)

    if not HAS_PYHP:
        safe_fail(module,
                  msg='There was a problem loading from the pyhpecw7 ' +
                  'module.',
                  error=str(ie))

    ipe_package = module.params.get('ipe_package')
    boot = module.params.get('boot')
    system = module.params.get('system')

    if ipe_package:
        if boot or system:
            module.fail_json(
                msg=
                'ipe_package and boot/system parameters are mutually exclusive'
            )
    else:
        if not (boot and system):
            module.fail_json(
                msg=
                'boot and system parameters must be provided if ipe_package is not'
            )

    hostname = socket.gethostbyname(module.params['hostname'])
    username = module.params['username']
    password = module.params['password']
    port = module.params['port']

    device = HPCOM7(host=hostname,
                    username=username,
                    password=password,
                    port=port,
                    timeout=150)

    changed = False

    reboot = module.params.get('reboot')
    delay = module.params.get('delay')
    already_set = False
    transfered = False

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module,
                  device,
                  msg=str(e),
                  descr='Error opening connection to device.')

    try:
        ios = InstallOs(device)
        existing = ios.get_config()
    except PYHPError:
        safe_fail(module,
                  device,
                  msg=str(e),
                  descr='Error getting current config.')

    existing_boot = existing['startup-primary']['boot']
    existing_system = existing['startup-primary']['system']
    remote_dir = module.params['remote_dir']
    current_boot_file = remote_dir + existing_boot
    current_sys_file = remote_dir + existing_system

    if ipe_package:
        ipe_basename = os.path.basename(ipe_package)
        ipe_boot_sys = re.split('-|\.', ipe_basename)[-3:-1]
        if ipe_boot_sys:
            if ipe_boot_sys[0].lower() in existing_boot.lower()\
                    and ipe_boot_sys[0].lower() in existing_system.lower()\
                    and ipe_boot_sys[1].lower() in existing_boot.lower()\
                    and ipe_boot_sys[1].lower() in existing_system.lower():
                already_set = True

        ipe_dst = remote_dir + ipe_basename
        try:
            # preps transfer and checks if source file exists
            ipe_file_copy = FileCopy(device, ipe_package, ipe_dst)
        except PYHPError as fe:
            safe_fail(module,
                      device,
                      msg=str(fe),
                      descr='Error preparing IPE file transfer.')

        if not ipe_file_copy.file_already_exists():
            try:
                ipe_file_copy.transfer_file()
                transfered = True
            except PYHPError as fe:
                safe_fail(module,
                          device,
                          msg=str(fe),
                          descr='Error transfering IPE file.')

        if not already_set:
            delete_ipe = module.params.get('delete_ipe')
            ios.build('ipe',
                      ipe=ipe_file_copy.dst,
                      delete_ipe=delete_ipe,
                      stage=True)
            # set current boot/sys files as backup startup images
            ios.build('bootsys',
                      boot=current_boot_file,
                      system=current_sys_file,
                      startup_type='2',
                      stage=True)
    elif boot:
        boot_basename = os.path.basename(boot)
        system_basename = os.path.basename(system)
        if boot_basename in existing_boot\
                and system_basename in existing_system:
            already_set = True

        boot_dst = remote_dir + boot_basename
        try:
            # preps transfer and checks if source file exists
            boot_file_copy = FileCopy(device, boot, boot_dst)
        except PYHPError as fe:
            safe_fail(module,
                      device,
                      msg=str(fe),
                      descr='Error preparing boot file transfer.')

        system_dst = remote_dir + system_basename
        try:
            # preps transfer and checks if source file exists
            system_file_copy = FileCopy(device, system, system_dst)
        except PYHPError as fe:
            safe_fail(module,
                      device,
                      msg=str(fe),
                      descr='Error preparing system file transfer.')

        if not boot_file_copy.file_already_exists():
            try:
                boot_file_copy.transfer_file()
                transfered = True
            except PYHPError as fe:
                safe_fail(module,
                          device,
                          msg=str(fe),
                          descr='Error transfering boot file.')

        if not system_file_copy.file_already_exists():
            try:
                system_file_copy.transfer_file()
                transfered = True
            except PYHPError as fe:
                safe_fail(module,
                          device,
                          msg=str(fe),
                          descr='Error transfering system file.')

        if not already_set:
            ios.build('bootsys',
                      boot=boot_file_copy.dst,
                      system=system_file_copy.dst,
                      stage=True)
            # set current boot/sys files as backup startup images
            ios.build('bootsys',
                      boot=current_boot_file,
                      system=current_sys_file,
                      startup_type='2',
                      stage=True)

    commands = None
    end_state = existing

    reboot_attempt = 'no'
    if device.staged or transfered:
        if reboot and delay:
            reboot_attempt = 'yes'
            os_reboot = Reboot(device)
            os_reboot.build(stage=True, reboot=True, delay=delay)
        commands = device.staged_to_string()
        if module.check_mode:
            safe_exit(module,
                      device,
                      changed=True,
                      commands=commands,
                      transfered=transfered,
                      end_state=end_state)
        else:
            try:
                device.execute_staged()
                end_state = ios.get_config()
            except PYHPError as e:
                safe_fail(module,
                          device,
                          msg=str(e),
                          descr='Error executing commands.')
            changed = True

    results = {}
    results['commands'] = commands
    results['transfered'] = transfered
    results['changed'] = changed
    results['end_state'] = end_state

    if reboot and not delay:
        reboot_attempt = 'yes'
        try:
            device.reboot()
            changed = True

            # for some reason,
            # this is needed to activate the reboot
            try:
                device.close()
            except PYHPError:
                pass
        except PYHPError as e:
            safe_fail(module,
                      device,
                      msg=str(e),
                      descr='Error rebooting the device.')

    results['reboot_attempt'] = reboot_attempt
    safe_exit(module, device, **results)
예제 #4
0
class RebootTestCase(BaseFeatureCase):

    @mock.patch('pyhpecw7.comware.HPCOM7')
    def setUp(self, mock_device):
        self.device = mock_device
        self.reboot = Reboot(self.device)

    def test_build(self):
        self.reboot.build(reboot=True)
        self.device.cli_display.assert_called_with(['reboot force'])

        self.reboot.build(stage=True, reboot=True)
        self.device.stage_config.assert_called_with(['reboot force'], 'cli_display')

    def test_build_delay(self):
        self.reboot.build(reboot=True, delay='20')
        self.device.cli_display.assert_called_with(['scheduler reboot delay 20'])

        self.reboot.build(stage=True, delay='20', reboot=True)
        self.device.stage_config.assert_called_with(['scheduler reboot delay 20'], 'cli_display')

    def test_build_at_time(self):
        self.reboot.build(reboot=True, time='10')
        self.device.cli_display.assert_called_with(['scheduler reboot at 10'])

        self.reboot.build(stage=True, time='10', reboot=True)
        self.device.stage_config.assert_called_with(['scheduler reboot at 10'], 'cli_display')

    def test_build_at_time_and_date(self):
        self.reboot.build(reboot=True, time='10', date='15')
        self.device.cli_display.assert_called_with(['scheduler reboot at 10 15'])

        self.reboot.build(stage=True, time='10', date='15', reboot=True)
        self.device.stage_config.assert_called_with(['scheduler reboot at 10 15'], 'cli_display')

    def test_param_check_time(self):
        result = self.reboot.param_check(time='03:02')
        self.assertEqual(result, None)

        with self.assertRaises(RebootTimeError):
            self.reboot.param_check(time='20')

        with self.assertRaises(RebootTimeError):
            self.reboot.param_check(time='0::03')

        with self.assertRaises(RebootTimeError):
            self.reboot.param_check(time='0:203')

    def test_param_check_date(self):
        result = self.reboot.param_check(date='03/02/2939')
        self.assertEqual(result, None)

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03.02.2939')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03/02/2939/3929')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='003/02/2939')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03/002/2939')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03/02/29393')
def main():
    module = AnsibleModule(
        argument_spec=dict(
            member_id=dict(type='str',
                           required=True),
            new_member_id=dict(type='str'),
            auto_update=dict(choices=['enable', 'disable']),
            domain_id=dict(type='str'),
            mad_exclude=dict(),
            priority=dict(type='str'),
            descr=dict(),
            reboot=dict(type='bool',
                        choices=BOOLEANS,
                        required=True),
            state=dict(choices=['present', 'absent'],
                       default='present'),
            hostname=dict(required=True),
            username=dict(required=True),
            password=dict(required=True),
            port=dict(type='int', default=830)
        ),
        supports_check_mode=True
    )

    if not HAS_PYHP:
        module.fail_json(
            msg='There was a problem loading from the pyhpecw7comware module')

    filtered_keys = ('hostname', 'username', 'password',
                     'port', 'CHECKMODE')

    hostname = socket.gethostbyname(module.params['hostname'])
    username = module.params['username']
    password = module.params['password']
    port = module.params['port']

    device = HPCOM7(host=hostname, username=username,
                    password=password, port=port)

    member_id = module.params.pop('member_id')
    reboot = module.params.pop('reboot')
    state = module.params.get('state')

    changed = False

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module, device, msg=str(e))

    try:
        irfm = IrfMember(device)
        existing = irfm.get_config(member_id)
    except PYHPError as e:
        if isinstance(e, IRFMemberDoesntExistError):
            new_member_id = module.params.get('new_member_id')
            try:
                if new_member_id:
                    member_id = new_member_id
                    irfm = IrfMember(device)
                    existing = irfm.get_config(member_id)
                else:
                    safe_fail(module, device, msg=str(e))
            except PYHPError as e:
                safe_fail(module, device, msg=str(e))
        else:
            safe_fail(module, device, msg=str(e))

    proposed = dict((k, v) for k, v in module.params.iteritems()
                    if v is not None and k not in filtered_keys)

    mad_exclude = proposed.pop('mad_exclude', [])
    if isinstance(mad_exclude, str):
        mad_exclude = [mad_exclude]

    if mad_exclude:
        try:
            mad_exclude = convert_iface_list(device, mad_exclude)
        except InterfaceError as ie:
            module.fail_json(msg=str(ie))

    existing_mad_exclude = existing.pop('mad_exclude', [])
    mad_delta = list(set(mad_exclude).difference(
        existing_mad_exclude))

    delta = dict(set(proposed.iteritems()).difference(
        existing.iteritems()))

    proposed['mad_exclude'] = mad_exclude
    existing['mad_exclude'] = existing_mad_exclude

    if state == 'present':
        if delta or mad_delta:
            try:
                irfm.build(
                    member_id=member_id, mad_exclude=mad_delta, **delta)
            except PYHPError as e:
                safe_fail(module, device, msg=str(e),
                          descr='There was an error preparing the'
                          + ' IRF membership configuration.')
    elif state == 'absent':
        remove_mad = list(set(mad_exclude).intersection(
            existing_mad_exclude))
        irfm.remove_mad_exclude(remove_mad)

    commands = None
    end_state = existing

    if device.staged:
        commands = device.staged_to_string()
        if module.check_mode:
            safe_exit(module, device, changed=True,
                      commands=commands)
        else:
            try:
                device.execute()
                end_state = irfm.get_config(member_id)
            except PYHPError as e:
                safe_fail(module, device, msg=str(e))
            changed = True

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['commands'] = commands
    results['changed'] = changed
    results['end_state'] = end_state
    results['state'] = state

    new_member_id = proposed.get('new_member_id')
    mem_id_changed = False
    if new_member_id:
        mem_id_changed = proposed.get('new_member_id') != member_id
    
    if reboot and mem_id_changed:
        try:
            my_reboot = Reboot(device)
            my_reboot.build(reboot=True)
            changed = True
            device.execute()
        except PYHPError as e:
            if isinstance(e, NCTimeoutError)\
                    or isinstance(e, ConnectionClosedError):
                module.exit_json(**results)
            else:
                safe_fail(module, device, msg=str(e))

    safe_exit(module, device, **results)
예제 #6
0
 def setUp(self, mock_device):
     self.device = mock_device
     self.reboot = Reboot(self.device)
예제 #7
0
def main():
    module = AnsibleModule(argument_spec=dict(
        reboot=dict(required=True, choices=BOOLEANS, type='bool'),
        delay=dict(required=False, type='str'),
        date=dict(required=False, type='str'),
        time=dict(required=False, type='str'),
        port=dict(default=830, type='int'),
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True),
    ),
                           supports_check_mode=True)

    if not HAS_PYHP:
        module.fail_json(msg='There was a problem loading from the pyhpecw7 ' +
                         'module.',
                         error=str(ie))

    username = module.params['username']
    password = module.params['password']
    port = module.params['port']
    hostname = socket.gethostbyname(module.params['hostname'])

    device_args = dict(host=hostname,
                       username=username,
                       password=password,
                       port=port)

    device = HPCOM7(**device_args)

    reboot = module.params['reboot']
    delay = module.params['delay']
    date = module.params['date']
    time = module.params['time']

    if date:
        if not time:
            module.fail_json(msg='time is also required when specifying date')

    proposed = dict(reboot=reboot, delay=delay, time=time, date=date)

    changed = False

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module,
                  device,
                  msg=str(e),
                  descr='error opening connection to device')

    try:
        reboot_me = Reboot(device)
        reboot_me.param_check(**proposed)
    except RebootDateError as rde:
        safe_fail(module, device, msg=str(rde))
    except RebootTimeError as rte:
        safe_fail(module, device, msg=str(rte))
    except PYHPError as e:
        safe_fail(module,
                  device,
                  msg=str(e),
                  descr='error using Reboot object')

    reboot_me.build(stage=True, **proposed)

    commands = None
    response = None
    changed = False

    results = {}

    if device.staged:
        commands = device.staged_to_string()
        if module.check_mode:
            safe_exit(module, device, changed=True, commands=commands)
        else:
            try:
                response = device.execute_staged()
                changed = True
            except PYHPError as e:
                if isinstance(e, NCTimeoutError):
                    results['changed'] = True
                    results['rebooted'] = True
                    results['commands'] = commands
                    module.exit_json(**results)
                else:
                    safe_fail(module,
                              device,
                              msg=str(e),
                              descr='error during execution')

    results['proposed'] = proposed
    results['commands'] = commands
    results['changed'] = changed
    results['end_state'] = 'N/A for this module'
    results['response'] = response

    safe_exit(module, device, **results)
예제 #8
0
class RebootTestCase(BaseFeatureCase):
    @mock.patch('pyhpecw7.comware.HPCOM7')
    def setUp(self, mock_device):
        self.device = mock_device
        self.reboot = Reboot(self.device)

    def test_build(self):
        self.reboot.build(reboot=True)
        self.device.cli_display.assert_called_with(['reboot force'])

        self.reboot.build(stage=True, reboot=True)
        self.device.stage_config.assert_called_with(['reboot force'],
                                                    'cli_display')

    def test_build_delay(self):
        self.reboot.build(reboot=True, delay='20')
        self.device.cli_display.assert_called_with(
            ['scheduler reboot delay 20'])

        self.reboot.build(stage=True, delay='20', reboot=True)
        self.device.stage_config.assert_called_with(
            ['scheduler reboot delay 20'], 'cli_display')

    def test_build_at_time(self):
        self.reboot.build(reboot=True, time='10')
        self.device.cli_display.assert_called_with(['scheduler reboot at 10'])

        self.reboot.build(stage=True, time='10', reboot=True)
        self.device.stage_config.assert_called_with(['scheduler reboot at 10'],
                                                    'cli_display')

    def test_build_at_time_and_date(self):
        self.reboot.build(reboot=True, time='10', date='15')
        self.device.cli_display.assert_called_with(
            ['scheduler reboot at 10 15'])

        self.reboot.build(stage=True, time='10', date='15', reboot=True)
        self.device.stage_config.assert_called_with(
            ['scheduler reboot at 10 15'], 'cli_display')

    def test_param_check_time(self):
        result = self.reboot.param_check(time='03:02')
        self.assertEqual(result, None)

        with self.assertRaises(RebootTimeError):
            self.reboot.param_check(time='20')

        with self.assertRaises(RebootTimeError):
            self.reboot.param_check(time='0::03')

        with self.assertRaises(RebootTimeError):
            self.reboot.param_check(time='0:203')

    def test_param_check_date(self):
        result = self.reboot.param_check(date='03/02/2939')
        self.assertEqual(result, None)

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03.02.2939')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03/02/2939/3929')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='003/02/2939')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03/002/2939')

        with self.assertRaises(RebootDateError):
            self.reboot.param_check(date='03/02/29393')
예제 #9
0
 def setUp(self, mock_device):
     self.device = mock_device
     self.reboot = Reboot(self.device)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            reboot=dict(required=True, choices=BOOLEANS, type='bool'),
            delay=dict(required=False, type='str'),
            date=dict(required=False, type='str'),
            time=dict(required=False, type='str'),
            port=dict(default=830, type='int'),
            hostname=dict(required=True),
            username=dict(required=True),
            password=dict(required=True),
        ),
        supports_check_mode=True
    )

    if not HAS_PYHP:
        module.fail_json(msg='There was a problem loading from the pyhpecw7 '
                         + 'module.', error=str(ie))

    username = module.params['username']
    password = module.params['password']
    port = module.params['port']
    hostname = socket.gethostbyname(module.params['hostname'])

    device_args = dict(host=hostname, username=username,
                       password=password, port=port)

    device = HPCOM7(**device_args)

    reboot = module.params['reboot']
    delay = module.params['delay']
    date = module.params['date']
    time = module.params['time']

    if date:
        if not time:
            module.fail_json(msg='time is also required when specifying date')

    proposed = dict(reboot=reboot, delay=delay,
                    time=time, date=date)

    changed = False

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module, device, msg=str(e),
                  descr='error opening connection to device')

    try:
        reboot_me = Reboot(device)
        reboot_me.param_check(**proposed)
    except RebootDateError as rde:
        safe_fail(module, device, msg=str(rde))
    except RebootTimeError as rte:
        safe_fail(module, device, msg=str(rte))
    except PYHPError as e:
        safe_fail(module, device, msg=str(e),
                  descr='error using Reboot object')

    reboot_me.build(stage=True, **proposed)

    commands = None
    response = None
    changed = False

    results = {}

    if device.staged:
        commands = device.staged_to_string()
        if module.check_mode:
            safe_exit(module, device, changed=True,
                      commands=commands)
        else:
            try:
                response = device.execute_staged()
                changed = True
            except PYHPError as e:
                if isinstance(e, NCTimeoutError):
                    results['changed'] = True
                    results['rebooted'] = True
                    results['commands'] = commands
                    module.exit_json(**results)
                else:
                    safe_fail(module, device, msg=str(e),
                              descr='error during execution')

    results['proposed'] = proposed
    results['commands'] = commands
    results['changed'] = changed
    results['end_state'] = 'N/A for this module'
    results['response'] = response

    safe_exit(module, device, **results)