示例#1
0
    def track(self):
        print "Collecting existing VMWare data..."

        while True:
            print "Searching for VMs"
            # Download all of the Endpoints
            context = ssl._create_unverified_context()
            si = SmartConnect(host=self.config['vc_url'],
                              user=self.config['vc_user'],
                              pwd=self.config['vc_pw'],
                              port='443',
                              sslContext=context)
            content = si.RetrieveContent()

            for child in content.rootFolder.childEntity:
                if hasattr(child, 'vmFolder'):
                    datacenter = child
                    vmFolder = datacenter.vmFolder
                    vmList = vmFolder.childEntity
                    for vm in vmList:
                        self.get_vm_info(vm)

            if self.stopped():
                print "Cleaning up track thread"
                Disconnect(si)
                return

            Disconnect(si)

            sleep(int(self.config["frequency"]))
示例#2
0
def _vm_power_state(esx_ip, esx_passwd, vm_name):
    try:
        c = SmartConnectNoSSL(host=esx_ip,
                              user=OPENSTACK_DEV_USER,
                              pwd=esx_passwd)
    except Exception as e:
        return False, "连接目标esxi失败"
    datacenter = c.content.rootFolder.childEntity[0]
    vms = datacenter.vmFolder.childEntity
    vmlist = []
    for i in vms:
        vmlist.append(i.name)
    if vm_name not in vmlist:
        return False, "ESXi中未找到目标vm"
    else:
        index = vmlist.index(vm_name)
        index_int = int(index)
        vm_state = vms[index_int].summary.runtime.powerState
        if not vm_state:
            Disconnect(c)
            return False, "获取vm状态失败"
        elif vm_state != "poweredOff":
            Disconnect(c)
            return False, "vm未关机"
        else:
            Disconnect(c)
            return True, "VM已关机"
示例#3
0
def _vm_disksize(esx_ip, esx_passwd, vm_name):
    try:
        c = SmartConnectNoSSL(host=esx_ip,
                              user=OPENSTACK_DEV_USER,
                              pwd=esx_passwd)
    except Exception as e:
        return False, "连接目标esxi失败"
    datacenter = c.content.rootFolder.childEntity[0]
    vms = datacenter.vmFolder.childEntity
    vmlist = []
    for i in vms:
        vmlist.append(i.name)
    if vm_name not in vmlist:
        return False, "ESXi中未找到目标vm"
    else:
        index = vmlist.index(vm_name)
        index_int = int(index)
        vm_disk = vms[index_int].summary.storage.committed + vms[
            index_int].summary.storage.uncommitted
        if not vm_disk:
            Disconnect(c)
            return False, "获取vm磁盘大小失败"
        else:
            vm_disk_GB = vm_disk / 1024 / 1024 / 1024 + 1
            Disconnect(c)
            return True, vm_disk_GB
示例#4
0
def renameFn(Properties, Type):
    task = Properties['task']
    params = getParameters(task['Parameters'])
    opStatus = {}

    # ===========================================================================
    # Connect to Vcenter
    # ===========================================================================
    si = connectVcenter(Properties)

    obj = getObjRef(si.content, Type, params['OldName'])
    if obj is None:
        msg = "A object named " + params['OldName'] + " could not be found"
        updateFailedTaskList(task['TaskName'], params, msg, opStatus)

    else:
        print(" Current name : %s" % obj.name)
        print(" Renaming from %s to %s..." % (obj.name, params['NewName']))

        try:
            WaitForTask(obj.Rename(params['NewName']))
            print(" Rename successful")
            opStatus['ObjectName'] = getObjName(obj)
            opStatus['Status'] = 'Passed'

        except Exception as e:
            updateFailedTaskList(task['TaskName'], params, e.msg, opStatus)

    # ===========================================================================
    # Disconnect Vcenter
    # ===========================================================================
    Disconnect(si)

    return opStatus
示例#5
0
def main():
    capture_host_info = []
    for vm_host in ip_vm_host_list:
        print(vm_host)

        capture_vm_host_info = dict()

        capture_vm_host_info.update({'HOST IP': vm_host})

        ServiceInstance = Connect_VM_Host(vm_host, vm_user, vm_pwd)

        ## ServiceInstance

        if ServiceInstance is None:
            capture_host_info.append(capture_vm_host_info)
        else:
            capture_vm_host_info.update(
                {'vim.AboutInfo': Capture_ServiceInstance(ServiceInstance)})

            ## Datacenter

            for datacenter in ServiceInstance.content.rootFolder.childEntity:
                ## print(datacenter.hostFolder.childEntity)
                ## print(dir(datacenter))

                # vim.Datastore
                capture_vm_host_info.update(
                    {'vim.Datastore': Capture_Datastore(datacenter)})

                # vim.VirtualMachine
                capture_vm_host_info.update(
                    {'vim.VirtualMachine': Capture_VirtualMachine(datacenter)})

                # hostFolder
                for hostFolder in datacenter.hostFolder.childEntity:
                    # vim.ComputeResource

                    print("HOST", hostFolder.name)
                    capture_vm_host_info.update({
                        'vim.ComputeResource':
                        Capture_ComputeResource(hostFolder)
                    })

                    for HostSystem in hostFolder.host:
                        # vim.HostSystem

                        ## print(HostSystem)
                        ## print(host.config.storageDevice)
                        ## print(dir(HostSystem.config))
                        capture_vm_host_info.update(
                            {'Network': Capture_Network(HostSystem)})

                #for networkFolder in datacenter.networkFolder.childEntity:
                # vim.Network

            capture_host_info.append(capture_vm_host_info)

            Disconnect(ServiceInstance)

    return capture_host_info
示例#6
0
def PowerOffVmFn(Properties):
    task = Properties['task']
    params = getParameters(task['Parameters'])
    opStatus = {}

    # ===========================================================================
    # Connect to Vcenter
    # ===========================================================================
    si = connectVcenter(Properties)

    obj = getObjRef(si.content, vim.VirtualMachine, params['VmName'])
    if obj is None:
        msg = "A object named " + params['VmName'] + " could not be found"
        updateFailedTaskList(task['TaskName'], params, msg, opStatus)

    else:
        print(" Powering off the VM %s" % obj.name)


        try:
            WaitForTask(obj.PowerOff())
            print(" PowerOffVm successful")
            opStatus['ObjectName'] = getObjName(obj)
            opStatus['Status'] = 'Passed'
        except Exception as e:
            updateFailedTaskList(task['TaskName'], params, e.msg, opStatus)

    # ===========================================================================
    # Disconnect Vcenter
    # ===========================================================================
    Disconnect(si)

    return opStatus
示例#7
0
 def disconnect(self):
     """Close connection with VCenter."""
     if self.si:
         Disconnect(self.si)
         self.si = None
         logging.info(f'Disconnected from {self._address}')
     return 0
def main():
    esxi_hosts = []
    for vsphere_host in vsphere_hosts:
        serviceInstance = SmartConnectNoSSL(host=vsphere_host,
                                            user=vsphere_username,
                                            pwd=vsphere_password)
        content = serviceInstance.RetrieveContent()

        host_view = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.HostSystem], True)

        hosts = [host for host in host_view.view]
        for host in hosts:
            host_info = dict()
            host_pnics = capture_host_pnics(host)
            host_vnics = capture_host_vnics(host)
            host_vswitches = capture_host_vswitches(host)
            host_portgroups = capture_host_portgroups(host)
            host_info.update({
                'host': vsphere_host,
                'hostname': host.name,
                'pnics': host_pnics,
                'vswitches': host_vswitches,
                'portgroups': host_portgroups,
                'vnics': host_vnics
            })
            esxi_hosts.append(host_info)

        Disconnect(serviceInstance)

    print(json.dumps(esxi_hosts, indent=4))
示例#9
0
def power_control(
    vcenter_host, vcenter_user, vcenter_password, vcenter_action, pattern
):
    """Connect to vcenter and perform action on all sonar machines."""
    try:
        c = SmartConnect(host=vcenter_host, user=vcenter_user, pwd=vcenter_password)
    except ssl.SSLError:
        c = SmartConnect(
            host=vcenter_host,
            user=vcenter_user,
            pwd=vcenter_password,
            sslContext=ssl._create_unverified_context(),
        )

    pattern_matcher = re.compile(pattern)
    for vm in get_vcenter_vms(c):
        if pattern_matcher.findall(vm.name):
            if vcenter_action == "ON":
                if vm.runtime.powerState == "poweredOff":
                    vm.PowerOnVM_Task()
            if vcenter_action == "OFF":
                if vm.runtime.powerState == "poweredOn":
                    vm.PowerOffVM_Task()

    Disconnect(c)
示例#10
0
def shutdown():
    global VCENTERS
    """stop the module"""
    verbose("Stop the module")
    for vcenter in VCENTERS:
        Disconnect(vcenter["si"])
        verbose("disconnected from vcenter %s" % vcenter["name"])
示例#11
0
 def discover_clusters_vcenter(address, username, password, ret):
   """
   Args:
     address (str): Address of the management server.
     username (str): Name of user of the management server.
     password (str): Password of user of the management server
     ret (DiscoverClustersV2Ret): Return proto to be populated.
   """
   conn = None
   try:
     conn = SmartConnectNoSSL(host=address, user=username, pwd=password)
     log.debug("Connected to vCenter %s", address)
     vim_inventory_map = \
         DiscoveryUtil.compute_vcenter_cluster_inventory(conn.content.rootFolder)
     DiscoveryUtil._fill_vcenter_cluster_inventory_v2(
       vim_inventory_map, ret)
     for cluster_collection in ret.cluster_inventory.cluster_collection_vec:
       for cluster in cluster_collection.cluster_vec:
         cluster.management_server.type = cluster.management_server.kVcenter
         cluster.management_server.version = conn.content.about.version
   except socket.error:
     # The plain old socket errors don't indicate which connection.
     raise CurieException(CurieError.kInternalError,
       "Could not connect to vCenter at %s" % address)
   except vim.fault.InvalidLogin:
     # The failures back from vSphere don't provide the best experience.
     raise CurieException(CurieError.kInternalError,
       "Incorrect username or password for vCenter at %s" %address)
   finally:
     if conn is not None:
       Disconnect(conn)
示例#12
0
文件: TestAnon.py 项目: free-Zen/pvc
   def setUp(self):
       """
       Setting test suite
       """
       self.si = SmartConnect(host=self.options.host,
                              user=self.options.user,
                              pwd=self.options.pwd,
                              port=self.options.port)
       self.authenticated = 1

       print("Retriving some MOs while authenticated:")
       self.content = self.si.RetrieveContent()
       rootFolder = self.content.GetRootFolder()
       dataCenter = rootFolder.GetChildEntity()[0]
       hostFolder = dataCenter.hostFolder
       host = hostFolder.childEntity[0]
       self.hostSystem = host.host[0]
       self.vmFolder = dataCenter.vmFolder
       self.configManager = self.hostSystem.GetConfigManager()

       internalContent = self.si.RetrieveInternalContent()
       hostProfileEngine = internalContent.hostProfileEngine
       self.hostProfileManager = hostProfileEngine.hostProfileManager

       self.storageResourceManager = self.content.storageResourceManager
       self.dvsManager = self.si.RetrieveInternalContent().hostDistributedVirtualSwitchManager

       print(repr(self.hostProfileManager))
       print(repr(self.storageResourceManager))
       print(repr(self.dvsManager))
       print(repr(self.vmFolder))

       Disconnect(self.si)
       self.authenticated = 0
       self.si = None
def main():
    args = setup_args()
    filter_key = "summary.config.guestId"
    value = "crxPod1Guest"
    memory_threshold_utilization = 0.5
    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=args.password,
                           port=args.port)
    # Start with all the VMs from container, which is easier to write than
    # PropertyCollector to retrieve them.
    vms = get_obj(si, si.content.rootFolder, [vim.VirtualMachine])

    pc = si.content.propertyCollector
    filter_spec = create_filter_spec(pc, vms, filter_key)
    options = vmodl.query.PropertyCollector.RetrieveOptions()
    result = pc.RetrievePropertiesEx([filter_spec], options)
    vms = filter_results(result, value)
    hpa_vms = hpa_algo(vms, memory_threshold_utilization)
    for vm in hpa_vms:
        #print(vm['pod_name'])
        deployment = vm['pod_name']
        replica_count = "--replicas=" + str(vm['desired_replicas'])
        subprocess.call(
            ["kubectl", "scale", "deployments", deployment, replica_count])

    Disconnect(si)
    def __run_on_vm(self, name: str, folder, action: Callable) -> None:
        connection = SmartConnect(host=self._config.vsphere_vcenter,
                                  user=self._config.vsphere_username,
                                  pwd=self._config.vsphere_password,
                                  disableSslCertValidation=True)
        content = connection.RetrieveContent()
        container = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.VirtualMachine], True)
        vm = None

        for managed_object_ref in container.view:
            if managed_object_ref.name == name:
                vm = managed_object_ref
                break

        container.Destroy()

        if vm is None:
            raise ValueError("Unable to locate VirtualMachine.")

        vm_task = action(vm)

        while vm_task.info.state not in [
                vim.TaskInfo.State.success, vim.TaskInfo.State.error
        ]:
            time.sleep(1)

        Disconnect(connection)
示例#15
0
    def reboot(self, irc, msg, args, vmname):
        """<vm>
        Reboots the vm
        Returns the status of migration
        """
        username = self.user
        password = self.password
        vcenter = self.vcenter

        try:
            si = SmartConnect(host=vcenter,
                              user=username,
                              pwd=password,
                              port=443)
        except:
            err_text = 'Error connecting to {0}'.format(vcenter)
            log.info(err_text)
            irc.reply(err_text)
            return

        # Finding source VM
        try:
            vm = vmutils.get_vm_by_name(si, vmname)
        except:
            irc.reply('{0} not found.'.format(vmname))
            return

        try:
            vm.RebootGuest()
        except:
            vm.ResetVM_Task()

        irc.reply('Rebooting {0}'.format(vmname))
        Disconnect(si)
示例#16
0
 def disconnect(self):
     #print "Trying to Disconnect Vcenter ......"
     try:   
         Disconnect(self.si)
         print "Disconeected to Vcenter Successfully"
     except Exception as err:
         print err.message
示例#17
0
文件: getvms.py 项目: zjs/dispatch
def handle(ctx, payload):
    host = payload.get("host")
    port = payload.get("port", 443)
    if host is None:
        raise Exception("Host required")
    secrets = ctx["secrets"]
    if secrets is None:
        raise Exception("Requires vsphere secrets")
    username = secrets["username"]
    password = secrets.get("password", "")
    context = None
    if hasattr(ssl, '_create_unverified_context'):
        context = ssl._create_unverified_context()
    si = SmartConnect(host=host,
                        user=username,
                        pwd=password,
                        port=port,
                        sslContext=context)
    if not si:
        raise Exception(
            "Could not connect to the specified host using specified "
            "username and password")
    try:
        content = si.RetrieveContent()
        info = []
        for child in content.rootFolder.childEntity:
            if hasattr(child, 'vmFolder'):
                datacenter = child
                vmFolder = datacenter.vmFolder
                vmList = vmFolder.childEntity
                for vm in vmList:
                    info.extend(PrintVmInfo(vm))
        return info
    finally:
        Disconnect(si)
示例#18
0
def load_vms_from_datacenter(server_auth_config):

    context = None
    if hasattr(ssl, '_create_unverified_context'):
        context = ssl._create_unverified_context()

    si = None
    try:
        port = server_auth_config.get('port', 443)
        si = SmartConnect(host=server_auth_config['hostname'],
                          port=port,
                          user=server_auth_config['username'],
                          pwd=server_auth_config['password'],
                          sslContext=context)

        if not si:
            print('error connecting to'
                  f' {server_auth_config["hostname"]}:{port}')
            return -1

        content = si.RetrieveContent()
        for datacenter in content.rootFolder.childEntity:
            if hasattr(datacenter, 'vmFolder'):
                yield {
                    'datacenter': datacenter.name,
                    'vms': vms_from_list(datacenter.vmFolder.childEntity)
                }

    finally:
        if si:
            Disconnect(si)
示例#19
0
    def run(self):
        """
        Start worker.

        :return: Dictionary of the hosts in the worker scope.
        """

        self.log.info("Connect to %s:%s as user %s", self.host, self.port,
                      self.user)
        try:
            connection = SmartConnect(host=self.host,
                                      user=self.user,
                                      pwd=self.password,
                                      port=int(self.port))
            atexit.register(Disconnect, connection)
        except IOError as ex:
            self.log.error(ex)
            connection = None
        if connection is None:
            self.log.error(
                "Could not connect to the specified host using specified "
                "username and password.")
            return

        content = connection.RetrieveContent()
        output = dict()
        for child in content.rootFolder.childEntity:
            self.__explore_nodes(child, output)
        Disconnect(connection)
        return output
示例#20
0
def main():
    # Get Security Tag ID.
    sectagid = getsectag(sectag)

    # Get all VM's for the folder.
    foldervm = []

    # The first method, the machines need to be detached in order to update the security tag w/ Updated folder members.
    print("Cleaning, Detaching VMs.")
    for i in vms:
        if str(i).split(".")[1].split(":")[0] == "VirtualMachine":
            try:
                vmoid = str(i).split(".")[1].split(":")[1][:-1]
                detach(sectagid, vmoid)
            except:
                print("Error Detaching Virtual Machine!")

    # Next the members of the folder are added to the whitelist.
        if i.name == folder:
            for j in i.childEntity:
                foldervm.append(str(j).split(":")[1][:-1])

    print("Have Members of the Folder: " + str(foldervm))
    print("Adding Members to Security Tag...")

    for i in foldervm:
        try:
            print("Adding Specific Member: " + i)
            applytag(sectagid, i)
        except:
            print("Failed to Add Members to Security Tag!")

    Disconnect(c)
示例#21
0
    def get_samples(self):
        ts = get_iso8601_timestamp()

        vcconn = SmartConnect(host=self.vchost, user=self.vcuser, pwd=self.vcpass, port=self.vcport)

        try:
            propspec = {
                'VirtualMachine': [
                    'name', 'runtime.powerState', 'summary.config.numCpu', 'summary.config.memorySizeMB', 'summary.storage.committed', 'runtime.host',
                    ],
                'HostSystem': [
                    'name', 'summary.hardware', 'datastore', 'network', 'vm',
                    ],
                'Datastore': [
                    'name', 'summary'
                ],
                'ClusterComputeResource': [
                    'name', 'host', 'summary.numCpuCores', 'summary.effectiveMemory', 'summary.totalMemory', 'datastore'
                ],
            }

            vcobjs = traversal.get_object_properties_by_propspec(vcconn, propspec=propspec)
        except:
            logger.exception('couldn\'t retrieve properties')
            raise
        finally:
            Disconnect(vcconn)

        logger.info('got %d objects from vmware' % len(vcobjs))

        return list(self.sample_gen(ts, vcobjs, propspec.keys()))
示例#22
0
def vspherelicense(hostip,vcuser,vcpassword):
    from api.config import settings
    from pyVim.connect import SmartConnect, Disconnect
    import ssl

    s = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    s.verify_mode = ssl.CERT_NONE

    c = SmartConnect(host=hostip, user=vcuser, pwd=vcpassword, sslContext=s)

    #print(c.content.licenseManager.AddLicense(licenseKey="1463P-09K1K-Q8J9A-02CA0-05GJM"))

    vclicensekey = settings['labvc']['vclicensekey']
    vcuuid = c.content.about.instanceUuid

    print("Installing And Activating VSPHERE:")
    print(c.content.licenseManager.AddLicense(licenseKey=vclicensekey))
    print(c.content.licenseManager.licenseAssignmentManager.UpdateAssignedLicense(vcuuid,vclicensekey))











    Disconnect(c)
示例#23
0
def info_VM(event):
    #f= sys.stdin.read()
    #sys.stdout.write('Received: %s'%f)

    # Disabling urllib3 ssl warnings
    requests.packages.urllib3.disable_warnings()

    # Disabling SSL certificate verification
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    context.verify_mode = ssl.CERT_NONE

    vc = None

    # Connecting to vCenter
    try:
        #print 'hello110'
        vc = SmartConnect(host=vcenter.get(),
                          user=uname.get(),
                          pwd=password.get(),
                          port=443,
                          sslContext=context)
        #print 'ello2'
        searcher = vc.content.searchIndex
        #print 'hello3'
        #print searcher
        about = vc.content.about
        #print 'ello1'
        ip_details = vc.content.ipPoolManager
        #print  ip_details

        # Find a VM
        content = vc.RetrieveContent()
        #print content
        lst = [
            '130.5.7.80', '210.5.7.90', '150.5.7.100', '160.5.7.110',
            '170.7.7.120', '180.7.7.130'
        ]
        for i in lst:
            print 'rebooting .....', i
            vm = searcher.FindByIp(ip=i, vmSearch=True)
            #print 'vm valule',vm

            vm.RebootGuest()
        Disconnect(vc)
        exit()

    except IOError as e:
        #print "I/O error({0}): {1}".format(e.errno, e.strerror)
        print 'vcenter ip is incorrect'
    except vim.fault.InvalidLogin:
        print "ERROR: Invalid login credentials '%s'"
        exit(1)
    except vim.fault as message:
        print("Error connecting to vSphere: %s" % str(message))
        exit(1)
    except:
        # forceably shutoff/on
        # need to do if vmware guestadditions isn't running
        vm.ResetVM_Task()
    def Extract(self, file=None, API_version=None):
        if (self.logger): self.logger.debug("%s: Extract(). IN" % (__name__))

        # Actual connection to V Center
        session = False
        try:
            session = self.VMW_Connect(self.host, self.username, self.password,
                                       self.port)
        except vim.fault.InvalidLogin:
            self.logger.error(
                "%s: %s: Invalid Login trying to connect '%s:%s@%s:%s'" %
                (__name__, 'Extract', self.username, '********', self.host,
                 self.port))
            return None
        except TimeoutError:
            self.logger.warning(
                "%s: %s: Timeout Error trying to connect %s:%s" %
                (__name__, 'Extract', self.host, self.port))
            return None
        except Exception as e:
            emtec_handle_general_exception(e,
                                           logger=self.logger,
                                           module=__name__,
                                           function='Extract')
            return None
        if not session:
            if (self.logger):
                self.logger.debug(
                    "%s: Could not connect to the specified host using specified username and password"
                    % (__name__))

        content = session.RetrieveContent(
        )  # Check if retrieves all content in V Center or can/need to be "sliced"

        # Created a container for V Center Data
        self.data = []
        # Loops for al V Center's children, LoadVMInfo is recurses into folder children
        for child in content.rootFolder.childEntity:
            if hasattr(child, 'vmFolder'):
                datacenter = child
                vmFolder = datacenter.vmFolder
                vmList = vmFolder.childEntity
                for vm in vmList:
                    #print("Extract: type vm=",type(vm),"vm=",vm)
                    self.LoadVmInfo(self.data, vm)
        status = 200

        # NOTE: VMWare considers all data is retrieved at once, not slicing
        self.total_matches = len(self.data)
        self.processed_vms += len(self.data)
        if self.processed_vms >= self.total_matches:
            self.has_more_data = False

        Disconnect(session)

        if (self.logger):
            self.logger.debug("%s: Extract(). OUT returns %s" %
                              (__name__, status))
        return status
示例#25
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     self.logger.info('disconnecting vCenter %s' % self.ip)
     try:
         Disconnect(self.si)
     except:
         self.logger('Exception during vCenter disconnect')
     self.content = None
     self.si = None
示例#26
0
 def vc_logout(self):
     """
     """
     if self.service_instance is None:
         Disconnect(self.service_instance)
     if self._atexit_func is not None:
         atexit.unregister(self._atexit_func)
         self._atexit_func = None
示例#27
0
 def logout(self):
     try:
         Disconnect(self.mysession)
         return True
     except Exception as e:
         print("Logout failed")
         self.mysession = None
         return False
示例#28
0
    def disconnect(self):

        if self.service_instance:
            LOG.debug(
                _("Disconnecting from vSphere host {}.").format(self.host))
            Disconnect(self.service_instance)

        self.service_instance = None
示例#29
0
def close():
    """ Close the session if exists """
    global _session_id, _connection_obj
    if _connection_obj:
        Disconnect(_connection_obj)
        print('Vcenter session with ID {} closed'.format(_session_id))
        _session_id = None
        _connection_obj = None
示例#30
0
 def cleanup(self):
     Disconnect(self.si)
     # the Disconnect Method does not close the tcp connection
     # is that so intentionally?
     # However, explicitly closing it works like this:
     self.si._stub.DropConnections()
     self.si = None
     self.log = None