コード例 #1
0
 def setup(self):
     mgmtips = []
     for device in self.options.devices:
         if isinstance(device, str):
             mgmtips.append(device)
         elif isinstance(device, DeviceAccess):
             mgmtips.append(device.address)
         else:
             raise ValueError(device)
     
     assert mgmtips, 'No devices discovered on EM?'
     with SSHInterface(**self.sshparams) as sshifc:
         with EMInterface(**self.icparams) as emifc:
             emapi = emifc.api
             statuses = EMSQL.device.get_device_state(mgmtips, ifc=sshifc)
             LOG.debug(statuses)
             uids = []
             for status in statuses:
                 if status.status in ('big3d_below_minimum', 'big3d_update_required') \
                 and status.refresh_failed_at is None:
                     uids.append(status.uid)
             
             
             if uids:
                 LOG.info('Big3d install on device_uids: %s', uids)
                 ret = emapi.big3d_install.big3dInstallCreate(self.options.task_name, 
                                                              uids, 'true', 'true')
                 job = int(ret['jobUid'])
                 
                 task = EMSQL.device.GetBig3dTask(job, ifc=sshifc) \
                        .run_wait(lambda x: x['status'] != 'started',
                                  timeout=300,
                                  progress_cb=lambda x:'big3d install: %d%%' % x.progress_percent)
                 assert task.error_count == 0, 'Errors in big3d task: %s' % task
                 return task
             else:
                 LOG.info('No devices need big3d install')
コード例 #2
0
ファイル: unmerge.py プロジェクト: xiaotdl/nosest
 def prep(self):
     self.sshifc = SSHInterface(**self.sshparams)
     self.api = self.sshifc.open()
コード例 #3
0
    def push_certificate(self, pkey, cert):

        icifc = IcontrolInterface(device=self.options.device,
                                  address=self.address,
                                  username=self.options.admin_username,
                                  password=self.options.admin_password,
                                  port=self.options.ssl_port,
                                  debug=self.options.verbose)
        ic = icifc.open()
        key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
        cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

        try:
            ic.Management.KeyCertificate.certificate_delete(
                mode='MANAGEMENT_MODE_WEBSERVER', cert_ids=['server'])
            ic.Management.KeyCertificate.key_delete(
                mode='MANAGEMENT_MODE_WEBSERVER', key_ids=['server'])
        except:
            LOG.warning('Exception occurred while deleting cert/key')

        ic.Management.KeyCertificate.certificate_import_from_pem(
                mode='MANAGEMENT_MODE_WEBSERVER', cert_ids=['server'],
                pem_data=[cert_pem], overwrite=1)

        ic.Management.KeyCertificate.key_import_from_pem(
                mode='MANAGEMENT_MODE_WEBSERVER', key_ids=['server'],
                pem_data=[key_pem], overwrite=1)

        icifc.close()

        # XXX: Unfortunately we can't reinit httpd through iControl. It's a KI
        # http://devcentral.f5.com/Default.aspx?tabid=53&forumid=1&postid=1170498&view=topic
        #
        # action = pc.System.Services.typefactory.\
        #        create('System.Services.ServiceAction').\
        #        SERVICE_ACTION_REINIT
        # service = pc.System.Services.typefactory.\
        #        create('System.Services.ServiceType').\
        #        SERVICE_HTTPD
        # pc.System.Services.set_service(services = [service], \
        #                               service_action = action)
        # pc.System.Services.get_service_status([service])

        with SSHInterface(device=self.options.device,
                          address=self.address,
                          username=self.options.root_username,
                          password=self.options.root_password,
                          port=self.options.ssh_port) as sshifc:
            version = SCMD.ssh.get_version(ifc=sshifc)
            if version >= 'bigiq 4.4' or version < 'bigiq 4.0' or \
               version >= 'iworkflow 2.0':
                sshifc.api.run('bigstart reinit webd')
            elif version >= 'bigiq 4.3' and version < 'bigiq 4.4':
                sshifc.api.run('bigstart reinit nginx')
            else:  # all BPs
                if version < 'bigip 11.5.0':
                    x = sshifc.api.run('bigstart reinit httpd')
                    LOG.debug("pushcert (res: bigstart reinit httpd): {0}".format(x))
                else:  # See BZ553787 (Matt Davey: restjavad must be restarted after pushing a cert)
                    # was for > 12.0 only but the "fix" made it to all new HFs
                    LOG.debug("pushcert (res: bigstart restart)...(because of issue with restajavad and/or httpd on certain platforms)")
                    # sshifc.api.run('bigstart restart')
                    sshifc.api.run('bigstart restart httpd')
                    self.wait_for_available(version)

        return True
コード例 #4
0
 def prep(self):
     self.sshifc = SSHInterface(**self.sshparams)
     self.api = self.sshifc.open()
     self.api.run('rm -rf {0} && mkdir -p {0}'.format(UCS_TMP))
コード例 #5
0
ファイル: extractor.py プロジェクト: jonozzz/nosest
 def prep(self):
     if not self.options.conf:
         self.sshifc = SSHInterface(**self.sshparams)
         self.api = self.sshifc.open()
     else:
         self.sshifc = None
コード例 #6
0
    def by_api(self):
        o = self.options
        timeout = o.timeout

        identifier = self.options.pversion
        build = self.options.pbuild

        if identifier:
            identifier = str(identifier)
            if build:
                build = str(build)

        if self.options.image:
            filename = self.options.image
        else:
            filename = cm.isofile(identifier=identifier, build=build,
                                  product=o.product, root=o.build_path)

        if self.options.hfimage:
            hfiso = self.options.hfimage
        elif self.options.phf:
            hfiso = cm.isofile(identifier=identifier, build=build,
                               hotfix=o.phf,
                               product=o.product,
                               root=o.build_path)
        else:
            hfiso = None

        iso_version = cm.version_from_metadata(filename)
        if (iso_version.product.is_bigip and iso_version >= 'bigip 10.0.0' or
                iso_version.product.is_em and iso_version >= 'em 2.0.0'):
            raise VersionNotSupported('Only legacy images supported through EMInstaller.')

        emifc = EMInterface(device=o.device, address=o.address,
                            username=o.admin_username, password=o.admin_password)
        emifc.open()

        with SSHInterface(device=o.device, address=o.address,
                          username=o.root_username, password=o.root_password,
                          port=self.options.ssh_port) as ssh:
            status = SCMD.ssh.get_prompt(ifc=ssh)
            if status in ['LICENSE EXPIRED', 'REACTIVATE LICENSE']:
                SCMD.ssh.relicense(ifc=ssh)
            elif status in ['LICENSE INOPERATIVE', 'NO LICENSE']:
                raise MacroError('Device at %s needs to be licensed.' % ssh)

            reachable_devices = [x['access_address'] for x in
                                 EMSQL.device.get_reachable_devices(ifc=ssh)]
            for x in self.devices:
                x.address = net.resolv(x.address)

            to_discover = [x for x in self.devices
                           if x.address not in reachable_devices]

            if to_discover:
                uid = EMAPI.device.discover(to_discover, ifc=emifc)
                task = EMSQL.device.GetDiscoveryTask(uid, ifc=ssh) \
                            .run_wait(lambda x: x['status'] != 'started',
                                      timeout=timeout,
                                      progress_cb=lambda x: 'discovery: %d%%' % x.progress_percent)
                assert task['error_count'] == 0, 'Discovery failed: %s' % task
            targets = []
            for device in self.devices:
                mgmtip = device.address
                version = EMSQL.device.get_device_version(mgmtip, ifc=ssh)
                if not o.essential_config and abs(iso_version) < abs(version):
                    LOG.warning('Enforcing --esential-config')
                    o.essential_config = True

                device_info = EMSQL.device.get_device_info(mgmtip, ifc=ssh)
                active_slot = EMSQL.device.get_device_active_slot(mgmtip,
                                                                  ifc=ssh)
                targets.append(dict(device_uid=device_info['uid'],
                                    slot_uid=active_slot['uid']))

            image_list = EMSQL.software.get_image_list(ifc=ssh)
            if iso_version not in image_list:
                base = os.path.basename(filename)
                destination = '%s.%d' % (os.path.join(SHARED_TMP, base), os.getpid())
                LOG.info('Importing base iso %s', base)
                SCMD.ssh.scp_put(device=o.device, address=o.address,
                                 destination=destination,
                                 username=self.options.root_username,
                                 password=self.options.root_password,
                                 port=self.options.ssh_port,
                                 source=filename, nokex=False)

                imuid = EMAPI.software.import_image(destination, ifc=emifc)
            else:
                imuid = image_list[iso_version]
                LOG.info('Image already imported: %d', imuid)

            if hfiso:
                hf_list = EMSQL.software.get_hotfix_list(ifc=ssh)
                hfiso_version = cm.version_from_metadata(hfiso)
                if hfiso_version not in hf_list:
                    hfbase = os.path.basename(hfiso)
                    destination = '%s.%d' % (os.path.join(SHARED_TMP, hfbase), os.getpid())
                    LOG.info('Importing hotfix iso %s', hfbase)
                    SCMD.ssh.scp_put(device=o.device, address=o.address,
                                     destination=destination,
                                     username=self.options.root_username,
                                     password=self.options.root_password,
                                     port=self.options.ssh_port,
                                     source=hfiso, nokex=False)
                    hfuid = EMAPI.software.import_image(destination, ifc=emifc)
                else:
                    hfuid = hf_list[hfiso_version]
            else:
                hfuid = None

            EMSQL.software.get_hotfix_list(ifc=ssh)

            EMSQL.device.CountActiveTasks(ifc=ssh) \
                        .run_wait(lambda x: x == 0, timeout=timeout,
                                  progress_cb=lambda x: 'waiting for other tasks')

            LOG.info('Installing %s...', iso_version)
            ret = EMAPI.software.install_image(targets, imuid, hfuid, o, ifc=emifc)
            ret = EMSQL.software.GetInstallationTask(ret['uid'], ifc=ssh).\
                run_wait(lambda x: x['status'] != 'started',
                         progress_cb=lambda x: 'install: %d%%' % x.progress_percent,
                         timeout=o.timeout)

        LOG.info('Deleting %d device(s)...', len(targets))
        EMAPI.device.delete(uids=[x['device_uid'] for x in targets], ifc=emifc)
        emifc.close()

        messages = []
        for d in ret['details']:
            if int(d['error_code']):
                messages.append("%(display_device_address)s:%(error_message)s" % d)
            if int(d['hf_error_code'] or 0):
                messages.append("%(display_device_address)s:%(hf_error_message)s" % d)
        if messages:
            raise InstallFailed('Install did not succeed: %s' %
                                ', '.join(messages))

        self.has_essential_config = o.essential_config
        return ret
コード例 #7
0
    def by_icontrol(self, filename, hfiso=None):
        iso_version = cm.version_from_metadata(filename)
        timeout = self.options.timeout
        if hfiso:
            hfiso_version = cm.version_from_metadata(hfiso)
        else:
            hfiso_version = None

        LOG.debug('iso: %s', iso_version)

        icifc = IcontrolInterface(address=self.address,
                                  username=self.options.admin_username,
                                  password=self.options.admin_password,
                                  port=self.options.ssl_port)
        ic = icifc.open()
        running_volume = ICMD.software.get_active_volume(ifc=icifc)
        assert running_volume != self.options.volume, \
            "Can't install on the active volume"

        version = ICMD.system.get_version(ifc=icifc)
        base = os.path.basename(filename)

        LOG.debug('running: %s', version)
        essential = self.options.essential_config
        if not essential and abs(iso_version) < abs(version):
            LOG.warning('Enforcing --esential-config')
            essential = True

        LOG.info('Setting the global DB vars...')
        ic.Management.Partition.set_active_partition(active_partition='Common')
        ic.Management.DBVariable.modify(variables=[
            {'name': 'LiveInstall.MoveConfig',
             'value': essential and 'disable' or 'enable'},
            {'name': 'LiveInstall.SaveConfig',
             'value': essential and 'disable' or 'enable'}
        ])
        # =======================================================================
        # Copy the ISO over to the device in /shared/images if it's not already
        # in the software repository.
        # =======================================================================
        images = ICMD.software.get_software_image(ifc=icifc)
        haz_it = any(filter(lambda x: x['verified'] and
                            x['product'] == iso_version.product.to_tmos and
                            x['version'] == iso_version.version and
                            x['build'] == iso_version.build, images))

        volume = self.options.volume or ICMD.software.get_inactive_volume(ifc=icifc)
        LOG.info('Preparing volume %s...', volume)
        ICMD.software.clear_volume(volume=volume, ifc=icifc)

        def is_available(items):
            all_count = len(items)
            return sum(bool(x['verified']) for x in items) == all_count

        is_clustered = ic.System.Cluster.is_clustered_environment()

        LOG.info('Timeout: %d', timeout)

        if essential:
            with SSHInterface(address=self.address,
                              username=self.options.root_username,
                              password=self.options.root_password,
                              timeout=timeout, port=self.options.ssh_port) as sshifc:
                ssh = sshifc.api
                lines = ssh.run('ls ' + SHARED_IMAGES).stdout.split()
                images = [x for x in lines if '.iso' in x]

            hfbase = os.path.basename(hfiso) if hfiso else None
            for image in images:
                if base != image and hfbase != image:
                    # If the image is a hotfix image
                    if 'hotfix' in image.lower():
                        LOG.info('Deleting hotfix image: %s' % image)
                        ICMD.software.delete_software_image(image, is_hf=True,
                                                            ifc=icifc)

                    # Otherwise assume it is a base image
                    else:
                        LOG.info('Deleting base image: %s' % image)
                        ICMD.software.delete_software_image(image, ifc=icifc)

        if not haz_it:
            LOG.info('Importing base iso %s', base)
            SCMD.ssh.scp_put(address=self.address,
                             username=self.options.root_username,
                             password=self.options.root_password,
                             port=self.options.ssh_port,
                             source=filename, nokex=False, timeout=timeout)

            LOG.info('Wait for image to be imported %s', base)
            ICMD.software.GetSoftwareImage(filename=base, ifc=icifc) \
                .run_wait(is_available, timeout=timeout,
                          timeout_message="Timeout ({0}s) while waiting for the software image to be imported.")

        if hfiso:
            images = ICMD.software.get_software_image(ifc=icifc, is_hf=True)
            haz_it = any(filter(lambda x: x['verified'] and
                                x['product'] == hfiso_version.product.to_tmos and
                                x['version'] == hfiso_version.version and
                                x['build'] == hfiso_version.build, images))

            if not haz_it:
                hfbase = os.path.basename(hfiso)
                LOG.info('Importing hotfix iso %s', hfiso)
                SCMD.ssh.scp_put(address=self.address,
                                 username=self.options.root_username,
                                 password=self.options.root_password,
                                 port=self.options.ssh_port,
                                 source=hfiso, nokex=False)

                LOG.info('Wait for image to be imported %s', hfbase)
                ICMD.software.GetSoftwareImage(filename=hfbase, ifc=icifc, is_hf=True) \
                    .run_wait(is_available, timeout_message="Timeout ({0}s) while waiting for the hotfix image to be imported.")

        def is_still_removing(items):
            return not any(filter(lambda x: x['status'].startswith('removing'),
                                  items))

        def is_still_installing(items):
            return not any(filter(lambda x: x['status'].startswith('installing') or
                                  x['status'].startswith('waiting') or
                                  x['status'].startswith('testing') or
                                  x['status'] in ('audited', 'auditing',
                                                  'upgrade needed'),
                                  items))

        volumes = ICMD.software.get_software_status(ifc=icifc)
        assert is_still_installing(volumes), "An install is already in " \
                                             "progress on another slot: %s" % volumes

        ICMD.software.GetSoftwareStatus(volume=volume, ifc=icifc) \
                     .run_wait(is_still_removing,
                               # CAVEAT: tracks progress only for the first blade
                               progress_cb=lambda x: x[0]['status'],
                               timeout=timeout)

        LOG.info('Installing %s...', iso_version)

        ICMD.software.install_software(hfiso_version or iso_version,
                                       volume=volume, ifc=icifc)

        ret = ICMD.software.GetSoftwareStatus(volume=volume, ifc=icifc) \
            .run_wait(is_still_installing,
                      # CAVEAT: tracks progress only for the first blade
                      progress_cb=lambda x: x[0]['status'],
                      timeout=timeout,
                      timeout_message="Timeout ({0}s) while waiting software install to finish.",
                      stabilize=10)

        LOG.info('Resetting the global DB vars...')
        ic.Management.DBVariable.modify(variables=[
            {'name': 'LiveInstall.MoveConfig',
             'value': essential and 'enable' or 'disable'},
            {'name': 'LiveInstall.SaveConfig',
             'value': essential and 'enable' or 'disable'}
        ])

        if sum(x['status'] == 'complete' for x in ret) != len(ret):
            raise InstallFailed('Install did not succeed: %s' % ret)

        LOG.info('Setting the active boot location %s.', volume)
        if is_clustered:
            # ===================================================================
            # Apparently on chassis systems the device is rebooted automatically
            # upon setting the active location, just like `b software desired
            # HD1.N active enable`.
            # ===================================================================
            uptime = ic.System.SystemInfo.get_uptime()
            ic.System.SoftwareManagement.set_cluster_boot_location(location=volume)
            time.sleep(60)
        else:
            ic.System.SoftwareManagement.set_boot_location(location=volume)
            LOG.info('Rebooting...')
            uptime = ICMD.system.reboot(ifc=icifc)

        # Grab a new iControl handle that uses the default admin credentials.
        if essential:
            icifc.close()
            icifc = IcontrolInterface(address=self.address,
                                      port=self.options.ssl_port)
            icifc.open()

        if uptime:
            ICMD.system.HasRebooted(uptime, ifc=icifc).run_wait(timeout=timeout)
            LOG.info('Device is rebooting...')

        LOG.info('Wait for box to be ready...')
        ICMD.system.IsServiceUp('MCPD', ifc=icifc).\
            run_wait(timeout=timeout,
                     timeout_message="Timeout ({0}s) while waiting for MCPD to come up")
        ICMD.system.IsServiceUp('TMM', ifc=icifc).\
            run_wait(timeout_message="Timeout ({0}s) while waiting for TMM to come up")

        ICMD.management.GetDbvar('Configsync.LocalConfigTime', ifc=icifc).\
            run_wait(lambda x: int(x) > 0,
                     progress_cb=lambda x: 'waiting configsync...',
                     timeout=timeout)
        ICMD.system.FileExists('/var/run/mprov.pid', ifc=icifc).\
            run_wait(lambda x: x is False,
                     progress_cb=lambda x: 'mprov still running...',
                     timeout=timeout)
        ICMD.system.FileExists('/var/run/grub.conf.lock', ifc=icifc).\
            run_wait(lambda x: x is False,
                     progress_cb=lambda x: 'grub.lock still present...',
                     timeout=timeout)

        current_version = ICMD.system.get_version(ifc=icifc)
        expected_version = hfiso_version or iso_version
        try:
            if expected_version != current_version:
                raise InstallFailed('Version expected: %s but found %s' %
                                    (expected_version, current_version))
        finally:
            icifc.close()

        # Will use SSH!
        if essential:
            self._initialize_big3d()

        if essential and current_version.product.is_em:
            self._initialize_em()

        self.has_essential_config = essential
コード例 #8
0
    def by_image2disk(self, filename, hfiso=None):
        iso_version = cm.version_from_metadata(filename)

        if hfiso:
            hfiso_version = cm.version_from_metadata(hfiso)
            reboot = False
        else:
            hfiso_version = None
            reboot = True

        LOG.debug('iso: %s', iso_version)

        base = os.path.basename(filename)
        essential = self.options.essential_config
        timeout = self.options.timeout

        if self.options.format_partitions or self.options.format_volumes:
            reboot = True

        with SSHInterface(address=self.address,
                          username=self.options.root_username,
                          password=self.options.root_password,
                          timeout=timeout, port=self.options.ssh_port) as sshifc:
            ssh = sshifc.api
            version = SCMD.ssh.get_version(ifc=sshifc)
            LOG.info('running on %s', version)

            if version > 'bigip 9.6.0':
                try:
                    ret = SCMD.tmsh.list('sys cluster', ifc=sshifc)
                except:
                    ret = None
                if ret:
                    raise NotImplementedError('Due to potential complications image2disk '
                                              'installations on clustered '
                                              'systems are not supported by this tool '
                                              'and should be done by hand. Sorry!')

            if not essential and abs(iso_version) < abs(version) or \
               iso_version.product != version.product:
                LOG.warning('Enforcing --esential-config')
                essential = True

            if essential:
                lines = ssh.run('ls ' + SHARED_IMAGES).stdout.split()
                images = [x for x in lines if '.iso' in x]

                hfbase = os.path.basename(hfiso) if hfiso else None
                for image in images:
                    if base != image and hfbase != image:
                        LOG.info('Deleting image: %s' % image)
                        ssh.run('rm -rf %s/%s' % (SHARED_IMAGES, image))

            # XXX: Image checksum is not verified!!
            if (base not in ssh.run('ls ' + SHARED_IMAGES).stdout.split()):
                LOG.info('Importing iso %s', filename)
                SCMD.ssh.scp_put(ifc=sshifc, source=filename, nokex=False)

            filename = os.path.join(SHARED_IMAGES, base)

            if self.options.format_volumes:
                fmt = 'lvm'
            elif self.options.format_partitions:
                fmt = 'partitions'
            else:
                fmt = None

            def log_progress(stdout, stderr):
                output = ''
                if stdout:
                    output += stdout
                if stderr:
                    output += '\n'
                    output += stderr

                # An in-house grep.
                for line in output.splitlines():
                    line = line.strip()
                    if line and not line.startswith('info: '):
                        LOG.debug(line)

            try:
                audit = SCMD.ssh.audit_software(version=version, ifc=sshifc)
                volume = get_inactive_volume(audit)
            except:
                volume = 'HD1.1'
                LOG.warning('Assuming destination slot %s', volume)
            LOG.info('Installing %s on %s...', iso_version, volume)
            SCMD.ssh.install_software(version=version, ifc=sshifc,
                                      repository=filename, format=fmt,
                                      essential=essential, volume=volume,
                                      progress_cb=log_progress,
                                      reboot=reboot,
                                      repo_version=iso_version)

        if reboot:
            # Grab a new iControl handle that uses the default admin credentials.
            self._wait_after_reboot(essential)

        if hfiso:
            if essential:
                sshifc = SSHInterface(address=self.address, timeout=timeout,
                                      port=self.options.ssh_port)
            else:
                sshifc = SSHInterface(address=self.address, timeout=timeout,
                                      username=self.options.root_username,
                                      password=self.options.root_password,
                                      port=self.options.ssh_port)

            with sshifc:
                version = SCMD.ssh.get_version(ifc=sshifc)
                LOG.info('running on %s', version)
                if reboot:
                    audit = SCMD.ssh.audit_software(version=version, ifc=sshifc)
                    volume = get_inactive_volume(audit)
                    LOG.info('Installing image on %s...', volume)
                    SCMD.ssh.install_software(version=version, ifc=sshifc,
                                              repository=filename, reboot=False,
                                              essential=essential, volume=volume,
                                              progress_cb=log_progress,
                                              repo_version=iso_version)
                hfbase = os.path.basename(hfiso)
                if (hfbase not in sshifc.api.run('ls ' + SHARED_IMAGES).stdout.split()):
                    LOG.info('Importing hotfix %s', hfiso)
                    SCMD.ssh.scp_put(ifc=sshifc, source=hfiso, nokex=not reboot)
                hfiso = os.path.join(SHARED_IMAGES, hfbase)

                LOG.info('Installing hotfix on %s...', volume)
                SCMD.ssh.install_software(version=version, ifc=sshifc,
                                          repository=hfiso, is_hf=True,
                                          essential=essential, volume=volume,
                                          progress_cb=log_progress,
                                          repo_version=hfiso_version,
                                          reboot=False)
                LOG.info('Rebooting...')
                SCMD.ssh.switchboot(ifc=sshifc, volume=volume)
                SCMD.ssh.reboot(ifc=sshifc)

        # Grab a new iControl handle that uses the default admin credentials.
        current_version = self._wait_after_reboot(essential)
        expected_version = hfiso_version or iso_version

        if expected_version != current_version:
            raise InstallFailed('Version expected: %s but found %s' %
                                (expected_version, current_version))

        if essential:
            self._initialize_big3d()

        if essential and current_version.product.is_em:
            self._initialize_em()

        self.has_essential_config = essential
コード例 #9
0
    def push_certificate(self, pkey, cert):

        icifc = IcontrolInterface(device=self.options.device,
                                  address=self.address,
                                  username=self.options.admin_username,
                                  password=self.options.admin_password,
                                  port=self.options.ssl_port,
                                  debug=self.options.verbose)
        ic = icifc.open()
        key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
        cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

        try:
            ic.Management.KeyCertificate.certificate_delete(
                mode='MANAGEMENT_MODE_WEBSERVER', cert_ids=['server'])
            ic.Management.KeyCertificate.key_delete(
                mode='MANAGEMENT_MODE_WEBSERVER', key_ids=['server'])
        except:
            LOG.warning('Exception occurred while deleting cert/key')

        ic.Management.KeyCertificate.certificate_import_from_pem(
            mode='MANAGEMENT_MODE_WEBSERVER',
            cert_ids=['server'],
            pem_data=[cert_pem],
            overwrite=1)

        ic.Management.KeyCertificate.key_import_from_pem(
            mode='MANAGEMENT_MODE_WEBSERVER',
            key_ids=['server'],
            pem_data=[key_pem],
            overwrite=1)

        icifc.close()

        # XXX: Unfortunately we can't reinit httpd through iControl. It's a KI
        # http://devcentral.f5.com/Default.aspx?tabid=53&forumid=1&postid=1170498&view=topic
        #
        # action = pc.System.Services.typefactory.\
        #        create('System.Services.ServiceAction').\
        #        SERVICE_ACTION_REINIT
        # service = pc.System.Services.typefactory.\
        #        create('System.Services.ServiceType').\
        #        SERVICE_HTTPD
        # pc.System.Services.set_service(services = [service], \
        #                               service_action = action)
        # pc.System.Services.get_service_status([service])

        with SSHInterface(device=self.options.device,
                          address=self.address,
                          username=self.options.root_username,
                          password=self.options.root_password,
                          port=self.options.ssh_port) as sshifc:
            version = SCMD.ssh.get_version(ifc=sshifc)
            if version >= 'bigiq 4.4':
                sshifc.api.run('bigstart reinit webd')
            elif version >= 'bigiq 4.3' and version < 'bigiq 4.4':
                sshifc.api.run('bigstart reinit nginx')
            else:
                sshifc.api.run('bigstart reinit httpd')

        return True
コード例 #10
0
ファイル: cloner.py プロジェクト: zone1511/f5test2
    def do_inject(self):
        LOG.info('* Cloning mode *')
        bulk_sql = []
        ip_offset = self.options.ip_offset
        with EMInterface(**self.emicparams) as emicifc:
            LOG.info('Disable auto-refresh on EM...')
            EMAPI.device.set_config(auto_refresh=False, ifc=emicifc)

        with SSHInterface(**self.emparams) as emsshifc:
            version = SCMD.ssh.get_version(ifc=emsshifc)
            has_groups = version < 'em 2.3.0'
            rows = SQL.query('SELECT MAX(device.uid) AS device, MAX(device_slot.uid) AS slot FROM device, device_slot;', ifc=emsshifc)
            max_device_uid = int(rows[0].device)
            max_slot_uid = int(rows[0].slot)

            bpmgmt = self.bigipparams.address
            template = self.do_get_template(bpmgmt, emsshifc)
            assert template.access_address != template.mgmt_address, \
                    "Template device must be discovered by its self IP."
            device_uid = int(template.uid)
            LOG.info('Template: %s', template.host_name)
            start_ip = IPAddress(START_IP)
            LOG.info('Inserting device rows...')
            for i in range(1, self.options.clones + 1, 1):
                template.uid = max_device_uid + UIDOFFSET + i
                template.access_address = str(start_ip + ip_offset + i)
                template.system_id = None
                template.last_refresh = None
                query = "INSERT INTO `device` %s" % self.do_prep_insert(template)
                bulk_sql.append(query)
                if has_groups:
                    bulk_sql.append("INSERT INTO device_2_device_group VALUES (NULL,%d,1)" % template.uid)

            while bulk_sql:
                SQL.query(";".join(bulk_sql[:MAXSQL]), ifc=emsshifc)
                bulk_sql[:MAXSQL] = []

            # Prepare device slot
            rows = SQL.query("SELECT * FROM device_slot WHERE device_id=%d;" % device_uid, ifc=emsshifc)
            last_device_slot_uid = max_slot_uid + UIDOFFSET
            LOG.info('Inserting device_slot rows...')
            for row in rows:
                last_device_uid = max_device_uid + UIDOFFSET
                for i in range(1, self.options.clones + 1, 1):
                    last_device_slot_uid += 1
                    last_device_uid += 1
                    row.uid = last_device_slot_uid
                    row.device_id = last_device_uid
                    query = "INSERT INTO `device_slot` %s" % self.do_prep_insert(row)
                    bulk_sql.append(query)

            while bulk_sql:
                SQL.query(";".join(bulk_sql[:MAXSQL]), ifc=emsshifc)
                bulk_sql[:MAXSQL] = []

        LOG.info('Creating SelfIPs on %s...', bpmgmt)
        self_ips = [str(start_ip + ip_offset + x)
                    for x in range(1, self.options.clones + 1, 1)]
        vlan_names = ['internal'] * self.options.clones
        netmasks = ['255.255.0.0'] * self.options.clones
        unit_ids = [0] * self.options.clones
        floating_states = ['STATE_DISABLED'] * self.options.clones
        with IcontrolInterface(**self.bigipparams) as bigipicifc:
            ic = bigipicifc.api
            ic.Networking.SelfIP.create(self_ips=self_ips, vlan_names=vlan_names,
                                        netmasks=netmasks, unit_ids=unit_ids,
                                        floating_states=floating_states)
            access_lists = [dict(self_ip=x, mode='ALLOW_MODE_ALL', protocol_ports=[])
                            for x in self_ips]
            ic.Networking.SelfIPPortLockdown.add_allow_access_list(access_lists=access_lists)