Example #1
0
	def run(self, params, args):

		nodes = self.newdb.getNodesfromNames(args,
				preload = ['vm_defs'])

		(terminate, action) = self.fillParams( [
			('terminate', 'n'),
			('action', 'poweroff'),
			])

		terminate = self.str2bool(terminate)

		if len(nodes) < 1:
			self.abort('must supply host')

		plugins = self.loadPlugins()

		for node in nodes:

			if not terminate:
				#
				# the name of the physical host that will boot
				# this VM host
				#
				if not node.vm_defs:
					self.abort("host %s is not a virtual host" % node.name)

				if not node.vm_defs.physNode:
					self.abort("host %s does not have a physical host" % node.name)

				# get the physical node that houses this VM
				physhost = node.vm_defs.physNode.name

				import rocks.vmconstant
				hipervisor = libvirt.open(rocks.vmconstant.connectionURL 
									% physhost)
				libvirt.registerErrorHandler(handler, 'context')

				try:
					domU = hipervisor.lookupByName(node.name)
					if(action == 'poweroff'):
						domU.destroy()
						domU.undefine()
					elif(action == 'shutdown'):
						domU.shutdown()
						domU.undefine()
					elif(action == 'reset'):
						domU.reset(0)
					elif(action == 'reboot'):
						domU.reboot(0)
				except libvirt.libvirtError, m:
					pass

			if terminate:
				#
				# run the terminate plugins to deallocate the host resources
				#
				for plugin in plugins:
					syslog.syslog(syslog.LOG_INFO, 'run %s' % plugin)
					plugin.run(node)
Example #2
0
    def run(self, params, args):

        nodes = self.newdb.getNodesfromNames(args, preload=['vm_defs'])

        (terminate, action) = self.fillParams([
            ('terminate', 'n'),
            ('action', 'poweroff'),
        ])

        terminate = self.str2bool(terminate)

        if len(nodes) < 1:
            self.abort('must supply host')

        plugins = self.loadPlugins()

        for node in nodes:

            if not terminate:
                #
                # the name of the physical host that will boot
                # this VM host
                #
                if not node.vm_defs:
                    self.abort("host %s is not a virtual host" % node.name)

                if not node.vm_defs.physNode:
                    self.abort("host %s does not have a physical host" %
                               node.name)

                # get the physical node that houses this VM
                physhost = node.vm_defs.physNode.name

                import rocks.vmconstant
                hipervisor = libvirt.open(rocks.vmconstant.connectionURL %
                                          physhost)
                libvirt.registerErrorHandler(handler, 'context')

                try:
                    domU = hipervisor.lookupByName(node.name)
                    if (action == 'poweroff'):
                        domU.destroy()
                        domU.undefine()
                    elif (action == 'shutdown'):
                        domU.shutdown()
                        domU.undefine()
                    elif (action == 'reset'):
                        domU.reset(0)
                    elif (action == 'reboot'):
                        domU.reboot(0)
                except libvirt.libvirtError, m:
                    pass

            if terminate:
                #
                # run the terminate plugins to deallocate the host resources
                #
                for plugin in plugins:
                    syslog.syslog(syslog.LOG_INFO, 'run %s' % plugin)
                    plugin.run(node)
Example #3
0
    def __init__(self,
                 username,
                 password,
                 port,
                 address,
                 domain_name,
                 libvirt_uri,
                 libvirt_sasl_username=None,
                 libvirt_sasl_password=None):
        super(VirtualBMC, self).__init__({username: password},
                                         port=port,
                                         address=address)
        self.domain_name = domain_name
        self._conn_args = {
            'uri': libvirt_uri,
            'sasl_username': libvirt_sasl_username,
            'sasl_password': libvirt_sasl_password
        }

        self._domain = None
        self._state = None
        self._stream = None
        self._run_console = False
        self._sol_thread = None

        libvirt.virEventRegisterDefaultImpl()
        libvirt.registerErrorHandler(error_handler, None)
Example #4
0
def main(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('--libvirt-url', dest='libvirturl',
                        default="qemu:///system",
                        help='Set libvirt connection url - default is "qemu:///system"')
    parser.add_argument('cluster_description_file', type=argparse.FileType('r'),
                        help='File with cluster description')
    args = parser.parse_args()

    libvirt.registerErrorHandler(suppress_some_messages, None)

    with action("Connecting to libvirt at {}".format(args.libvirturl)):
        conn = libvirt.open(args.libvirturl)

    with action("Load cluster description from {}".format(args.cluster_description_file.name)):
        cluster = load_cluster_description(args.cluster_description_file.read())
    
    images_path = cluster.attrs['images_path']
    print "Will store images to", images_path

    cluster.fuel_vm.boot_network = False
    launch_vm(conn, cluster.fuel_vm, cluster.nets, images_path)
    wait_fuel_installed(cluster.fuel_vm)

    for vm_name, vm in cluster.vms.items():
        launch_vm(conn, vm, cluster.nets, images_path)
    return 0
Example #5
0
def main():
    parser = argparse.ArgumentParser(
        prog='virshbmc',
        description='Pretend to be a BMC and proxy to virsh',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument('--port',
                        dest='port',
                        type=int,
                        default=623,
                        help='(UDP) port to listen on')
    parser.add_argument('--connect',
                        dest='hypervisor',
                        default='qemu:///system',
                        help='The hypervisor to connect to')
    parser.add_argument('--domain',
                        dest='domain',
                        required=True,
                        help='The name of the domain to manage')
    args = parser.parse_args()

    libvirt.virEventRegisterDefaultImpl()
    libvirt.registerErrorHandler(error_handler, None)

    mybmc = LibvirtBmc({'admin': 'password'},
                       hypervisor=args.hypervisor,
                       domain=args.domain,
                       port=args.port)
    mybmc.listen()
Example #6
0
  def test(self):
    self.mox.StubOutWithMock(libvirt, 'registerErrorHandler')
    libvirt.registerErrorHandler(mox.IgnoreArg(), None)

    self.mox.ReplayAll()

    utils._clearLibvirtError()
Example #7
0
def __virtual__():
    '''
    Apply this module as the hyper module if the minion is a kvm hypervisor
    '''
    if 'virtual' not in __grains__:
        return False
    if __grains__['virtual'] != 'physical':
        return False
    if __grains__['kernel'] != 'Linux':
        return False
    if not os.path.exists('/proc/modules'):
        return False
    try:
        if 'kvm_' not in salt.utils.fopen('/proc/modules').read():
            return False
    except IOError:
        return False
    if not HAS_LIBVIRT:
        return False

    #Libvirt is very noisy. This will quiet it down
    def quiet_errors(ignored, err):
        log.debug(err[2])

    libvirt.registerErrorHandler(quiet_errors, None)
    try:
        libvirt_conn = libvirt.open('qemu:///system')
        libvirt_conn.close()
        return 'hyper'
    except libvirt.libvirtError:
        return False
Example #8
0
def main():
    # Ignore text error from libvirt
    libvirt.registerErrorHandler(lambda: 1, None)

    parser = argparse.ArgumentParser(
        description='Provide functions to create and manage VMs on KVM.',
        prog='vm')
    parser.add_argument('--version', action='version',
                        version=Configuration.VERSION)
    parser.add_argument('-v', '--verbose', action='store_true')
    parser.add_argument(
        '--fork',
        default=4,
        type=int,
        help='set how many tasks launch parallelly')

    add_subparsers(parser)

    args = parser.parse_args()

    if args.verbose:
        logger.setLevel(logging.DEBUG)

    Resources(Configuration.RESOURCE_CONFIG)

    if hasattr(args, 'func'):
        getattr(args, 'func')(args)
    else:
        parser.print_help()
        sys.exit(0)
Example #9
0
 def __init__(self, config):
     self.conn = None
     self.uri = config.get('main', 'libvirt-hypervisor-uri')
     self.logger = logging.getLogger('mom.libvirtInterface')
     libvirt.registerErrorHandler(self._error_handler, None)
     self._connect()
     self._setStatsFields()
Example #10
0
def register():
    ctx = 'just some information'
    libvirt.registerErrorHandler(error_handler, ctx)

    conn = libvirt.open('qemu://system')
    conn.close()
    exit(0)
Example #11
0
    def test(self):
        self.mox.StubOutWithMock(libvirt, 'registerErrorHandler')
        libvirt.registerErrorHandler(mox.IgnoreArg(), None)

        self.mox.ReplayAll()

        utils._clearLibvirtError()
Example #12
0
    def libvirt_worker_loop(loop, start_websockets_server, hypervisors):
        def _err_handler(self, ctxt, err):
            print("Error from libvirt : %s", err[2])

        print("[{}] entering libvirt_worker_loop".format(
            threading.get_ident()))

        prctl.set_name('libvirt_loop')

        asyncio.set_event_loop(loop)
        libvirtaio.virEventRegisterAsyncIOImpl()
        libvirt.registerErrorHandler(_err_handler, '_virt_event')

        for id_, h in hypervisors.items():
            monitor_tasks.append(
                loop.create_task(h['monitor_instance'].watchdog_loop()))

        loop.run_until_complete(start_websockets_server)

        try:
            loop.run_until_complete(asyncio.gather(*monitor_tasks))
        except asyncio.CancelledError:
            loop.stop()
        finally:
            loop.run_until_complete(loop.shutdown_asyncgens())
            loop.close()
Example #13
0
File: utils.py Project: tinez/lago
def get_libvirt_connection(name):
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
            auth_callback, None]
    libvirt_url = config.get('libvirt_url', 'qemu:///system')

    libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
    return libvirt.openAuth(libvirt_url, auth)
Example #14
0
 def __init__(self, config):
     self.conn = None
     self.uri = config.get('main', 'libvirt-hypervisor-uri')
     self.interval = config.getint('main', 'guest-monitor-interval')
     self.logger = logging.getLogger('mom.libvirtInterface')
     libvirt.registerErrorHandler(self._error_handler, None)
     self._connect()
     self._setStatsFields()
Example #15
0
def register_libvirt_error_handler():
    """
    Ignore libvirt error reporting, we just use exceptions
    """
    def libvirt_callback(userdata, err):
        ignore = userdata
        ignore = err
    libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
Example #16
0
def register_libvirt_error_handler():
    """
    Ignore libvirt error reporting, we just use exceptions
    """
    def libvirt_callback(userdata, err):
        ignore = userdata
        ignore = err
    libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
Example #17
0
def _clearLibvirtError():
    """Disable libvirt error messages.

  _clearLibvirtError is a helper function to withoutLibvirtError,
  designed to make mocks and testing easy. It simply registers NOOP
  error handler for libvirt.
  """
    libvirt.registerErrorHandler((lambda ctx, err: 1), None)
Example #18
0
 def __init__(self, logger, config, registerEvents=True):
     super(Libvirtd, self).__init__(logger, config)
     self.changedCallback = None
     self.registerEvents = registerEvents
     self._host_uuid = None
     self._host_name = None
     self.eventLoopThread = None
     libvirt.registerErrorHandler(lambda ctx, error: None, None)
Example #19
0
 def __init__(self, logger, config, registerEvents=True):
     super(Libvirtd, self).__init__(logger, config)
     self.changedCallback = None
     self.registerEvents = registerEvents
     self._host_uuid = None
     self._host_name = None
     self.eventLoopThread = None
     libvirt.registerErrorHandler(lambda ctx, error: None, None)
Example #20
0
def _clearLibvirtError():
    """Disable libvirt error messages.

  _clearLibvirtError is a helper function to withoutLibvirtError,
  designed to make mocks and testing easy. It simply registers NOOP
  error handler for libvirt.
  """
    libvirt.registerErrorHandler((lambda ctx, err: 1), None)
def main():
    module = AnsibleModule(argument_spec=dict(
        pool=dict(required=True),
        name=dict(aliases=['vol'], required=True),
        state=dict(choices=all_states, default='present'),
        uri=dict(default='qemu:///system'),
        capacity=dict(aliases=['size']),
        allocation=dict(choices=['thin', 'fat'], default='thin'),
    ),
                           supports_check_mode=True)
    result = dict(changed=False, message='')

    if not installed_libvirt_py:
        module.fail_json(msg="'libvirt' python library is missing on host.")
    libvirt.registerErrorHandler(eh_dummy, 'ctx')  # apply dummy error handler

    # connect to libvirt host
    conn = libvirt.open(module.params['uri']) if not module.check_mode else \
        libvirt.openReadOnly(module.params['uri'])
    if not conn:
        module.fail_json(msg="connection to libvirt failed.")

    pool_handle = None
    disk_handle = None

    # look for volume
    try:
        pool_handle = conn.storagePoolLookupByName(module.params['pool'])
        disk_handle = pool_handle.storageVolLookupByName(module.params['name'])
    except libvirt.libvirtError as e:
        if e.get_error_code() == libvirt.VIR_ERR_NO_STORAGE_POOL:
            module.fail_json(msg="no such pool",
                             debug=(e.get_error_code(), str(e)))
        elif e.get_error_code() != libvirt.VIR_ERR_NO_STORAGE_VOL:
            module.fail_json(msg=str(e), debug=e.get_error_code())

    # apply state
    if not disk_handle and module.params['state'] == 'present':
        result['changed'] = True

        # determine capacity first
        if not 'capacity' in module.params:
            module.fail_json(msg="you should define a capacity")
        capacity = get_capacity(module.params['capacity'])
        if not capacity:
            module.fail_json(msg="invalid capacity format")

        if not module.check_mode:
            define_vol(pool_handle,
                       module.params['name'],
                       capacity,
                       thin=(module.params['allocation'] == 'thin'))
    elif disk_handle and module.params['state'] == 'absent':
        result['changed'] = True
        if not module.check_mode:
            undefine_vol(disk_handle)

    module.exit_json(**result)
Example #22
0
 def __init__(self, vm_name):
     """Get config and setup logging."""
     self.config = config.setup()
     self.log = logging.getLogger(__name__)
     def _error_handler(self, err):
         msg = "Ignoring Libvirt error %s)" % err
         pass
     # Prevent libvirt errors from reaching the console
     libvirt.registerErrorHandler(_error_handler, None)
Example #23
0
 def close(self):
     libvirt.registerErrorHandler(None, None)
     if self._xs:
         self._xs.close()
         self._xs = None
     if self._libvirt_conn:
         self._libvirt_conn.close()
         self._libvirt_conn = None
     self._xc = None  # and pray it will get garbage-collected
Example #24
0
 def close(self):
     libvirt.registerErrorHandler(None, None)
     if self._xs:
         self._xs.close()
         self._xs = None
     if self._libvirt_conn:
         self._libvirt_conn.close()
         self._libvirt_conn = None
     self._xc = None  # and pray it will get garbage-collected
Example #25
0
def main():
    args = parser.parse_args()
    if args.debug:
        LOG.setLevel(logging.DEBUG)

    nova_config = []
    if args.nova_config:
        nova_config = [args.nova_config]
    config.parse_args([], default_config_files=nova_config)
    if args.mysql_connection:
        config.CONF.set_override('connection', args.mysql_connection,
                                 'database')

    ctx = context.get_admin_context()
    instance = objects.instance.Instance.get_by_uuid(ctx, args.instance)
    compute_node = objects.compute_node.ComputeNode.get_by_host_and_nodename(
        ctx, instance.host, instance.node)

    if args.action not in ALLOWED_ACTIONS:
        raise Exception("Allowed action are: %s" % ', '.join(ALLOWED_ACTIONS))
    action = 'do_{}'.format(args.action)
    eval(action)(instance, compute_node)

    instance = objects.instance.Instance.get_by_uuid(ctx, args.instance)
    compute_node = objects.compute_node.ComputeNode.get_by_host_and_nodename(
        ctx, instance.host, instance.node)
    print_status(instance, compute_node, "Current status:")
    raw_input("Press ENTER to continue")

    # NOTE(aostapenko) handling libvirt verbosity
    def _error_handler(ctx, err):
        pass

    libvirt.registerErrorHandler(_error_handler, None)
    libvirt.virEventRegisterDefaultImpl()

    libvirt_host = host.Host('qemu:///system')
    domain = libvirt_host.get_domain(instance)
    total_pcpus = libvirt_host.get_connection().getInfo()[2]
    vcpu_pcpu_map = calculate_vcpu_pcpu_map(instance, compute_node,
                                            total_pcpus)

    current_vcpu_pcpu_map = get_vcpu_pcpu_map_from_domain(domain)
    print("Current libvirt pinnings:")
    print_vcpu_pcpu_data(current_vcpu_pcpu_map)
    print("Proposed libvirt pinnings, based on current pinning data from DB:")
    print_vcpu_pcpu_data(vcpu_pcpu_map)

    if (raw_input("Write 'apply' to apply proposed pinnings to domain: ") ==
            'apply'):
        apply_to_domain(domain, vcpu_pcpu_map)
        print("Changes were applied to domain")
    else:
        print("Changes were NOT applied to domain")
    print("Current libvirt pinnings:")
    current_vcpu_pcpu_map = get_vcpu_pcpu_map_from_domain(domain)
    print_vcpu_pcpu_data(current_vcpu_pcpu_map)
Example #26
0
def setup_libvirt():
    import libvirt

    # Check libvirt version
    assert (libvirt.getVersion() >= 9008)  # 0.9.8

    # Squash redundant reporting of libvirt errors to stderr.  This modifies
    # global state, since the Python bindings don't provide a way to do this
    # per-connection.
    libvirt.registerErrorHandler(lambda _ctx, _error: None, None)
Example #27
0
File: util.py Project: cDoru/vmnetx
def setup_libvirt():
    import libvirt

    # Check libvirt version
    assert(libvirt.getVersion() >= 9008) # 0.9.8

    # Squash redundant reporting of libvirt errors to stderr.  This modifies
    # global state, since the Python bindings don't provide a way to do this
    # per-connection.
    libvirt.registerErrorHandler(lambda _ctx, _error: None, None)
Example #28
0
def libvirt_connect(url):
    def _error_handler(_, err):
        pytest.fail("!!! {}".format(err[2]), pytrace=False)

    libvirt.registerErrorHandler(_error_handler, ctx=None)
    virt = libvirt.open(url)

    if not virt:
        pytest.fail("Could not establish libvirt connection")
    return virt
Example #29
0
File: runner.py Project: xii/xii
def libvirt_connect(url):
        def _error_handler(_, err):
            pytest.fail("!!! {}".format(err[2]), pytrace=False)

        libvirt.registerErrorHandler(_error_handler, ctx=None)
        virt = libvirt.open(url)

        if not virt:
            pytest.fail("Could not establish libvirt connection")
        return virt
Example #30
0
    def disable_libvirt_error_logging():
        def libvirt_errorhandler(userdata, error):
            # A libvirt error handler to ignore annoying messages in stderr
            pass

        # Filter functions are enable only in production env
        if cherrypy.config.get('environment') != 'production':
            return
        # Register the error handler to hide libvirt error in stderr
        libvirt.registerErrorHandler(f=libvirt_errorhandler, ctx=None)
Example #31
0
    def disable_libvirt_error_logging():
        def libvirt_errorhandler(userdata, error):
            # A libvirt error handler to ignore annoying messages in stderr
            pass

        # Filter functions are enable only in production env
        if cherrypy.config.get('environment') != 'production':
            return
        # Register the error handler to hide libvirt error in stderr
        libvirt.registerErrorHandler(f=libvirt_errorhandler, ctx=None)
Example #32
0
    def disable_screen_error_logging():
        def libvirt_errorhandler(userdata, error):
            # A libvirt error handler to ignore annoying messages in stderr
            pass

        # Register the error handler to hide libvirt error in stderr
        libvirt.registerErrorHandler(f=libvirt_errorhandler, ctx=None)
        # Disable cherrypy screen logging, in order to log errors on kimchi
        # file without displaying them on screen
        cherrypy.log.screen = False
Example #33
0
    def disable_screen_error_logging():
        def libvirt_errorhandler(userdata, error):
            # A libvirt error handler to ignore annoying messages in stderr
            pass

        # Register the error handler to hide libvirt error in stderr
        libvirt.registerErrorHandler(f=libvirt_errorhandler, ctx=None)
        # Disable cherrypy screen logging, in order to log errors on kimchi
        # file without displaying them on screen
        cherrypy.log.screen = False
Example #34
0
    def __init__(self, vm_name):
        """Get config and setup logging."""
        self.config = config.setup()
        self.log = logging.getLogger(__name__)

        def _error_handler(self, err):
            msg = "Ignoring Libvirt error %s)" % err
            pass

        # Prevent libvirt errors from reaching the console
        libvirt.registerErrorHandler(_error_handler, None)
Example #35
0
    def main(self):
        """Main method.

        Set the URI, error handler, and executes event loop processing.
        """
        uri = CONF.libvirt.connection_uri
        LOG.debug("Using uri:" + uri)

        # set error handler & do event loop
        libvirt.registerErrorHandler(self._err_handler, '_virt_event')
        self._virt_event(uri)
Example #36
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(aliases=['net'], required=True),
            state=dict(choices=all_states, default='present'),
            uri=dict(default='qemu:///system'),
            autostart=dict(
                type='bool',
                default=True),  # FIXME: change is not implemented yet
            xml=dict(),
        ),
        supports_check_mode=True)
    result = dict(changed=False, message='')

    if not installed_libvirt_py:
        module.fail_json(msg="'libvirt' python library is missing on host.")
    libvirt.registerErrorHandler(eh_dummy, 'ctx')  # apply dummy error handler

    # connect to libvirt host
    conn = libvirt.open(module.params['uri']) if not module.check_mode else \
        libvirt.openReadOnly(module.params['uri'])
    if not conn:
        module.fail_json(msg="connection to libvirt failed.")

    net_handle = None

    # look for network
    try:
        net_handle = conn.networkLookupByName(module.params['name'])
    except libvirt.libvirtError as e:
        if e.get_error_code() != libvirt.VIR_ERR_NO_NETWORK:
            module.fail_json(msg=str(e), debug=(e.get_error_code(), str(e)))

    # apply state
    if not net_handle and module.params['state'] == 'present':
        result['changed'] = True

        if not 'xml' in module.params or not module.params['xml']:
            module.fail_json(msg="you should define a xml")

        if not module.check_mode:
            define_net(conn, module.params['name'], module.params['xml'],
                       module.params['autostart'])
    elif net_handle and module.params['state'] == 'absent':
        result['changed'] = True
        if not module.check_mode:
            undefine_net(net_handle)
    elif module.params['state'] == 'leases':
        if not net_handle:
            module.fail_json(msg="net does not exist")
        result['changed'] = False
        result['leases'] = net_handle.DHCPLeases()

    module.exit_json(**result)
Example #37
0
    def __init__(self, uri=None):
        """Creates a read only connection to libvirt"""
        self.conn = libvirt.openReadOnly(uri)
        if self.conn is None:
            raise LibvirtConnectionError(
                "Failed to open connection to the hypervisor: " + str(uri))

        # We set this because when libvirt errors are raised, they are still
        # printed to console (stderr) even if you catch them.
        # This is a problem with libvirt API.
        # See https://stackoverflow.com/questions/45541725/avoiding-console-prints-by-libvirt-qemu-python-apis
        libvirt.registerErrorHandler(f=self.libvirt_callback, ctx=None)
Example #38
0
def main(args):
    ended = False
    libvirt.registerErrorHandler(lambda x, y: None, None)
    VirtuiConfig.loadconfig('~/.virtui.conf')
    _change_terminal_title(VirtuiConfig.general('virtui_terminal_title'))
    conn = Connection(VirtuiConfig.general('LIBVIRT_URI'))
    while not ended:
        domain = select_domain(conn)
        if domain == None:
            ended = True
            break
        manage_domain(domain)
Example #39
0
def _set_libvirt_error_handler():
    """
    Ignore libvirt error reporting, we just use exceptions
    """
    import libvirt

    def libvirt_callback(userdata, err):
        ignore = userdata
        ignore = err

    ctx = None
    libvirt.registerErrorHandler(libvirt_callback, ctx)
Example #40
0
def main(args):
    ended = False
    libvirt.registerErrorHandler(lambda x, y: None, None)
    VirtuiConfig.loadconfig('~/.virtui.conf')
    _change_terminal_title(VirtuiConfig.general('virtui_terminal_title'))
    conn = Connection(VirtuiConfig.general('LIBVIRT_URI'))
    while not ended:
        domain = select_domain(conn)
        if domain == None:
            ended = True
            break
        manage_domain(domain)
Example #41
0
File: utils.py Project: nirs/lago
def get_libvirt_connection(name):
    if name not in LIBVIRT_CONNECTIONS:
        auth = [
            [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
            auth_callback, None
        ]
        libvirt_url = config.get('libvirt_url', 'qemu:///system')

        libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
        LIBVIRT_CONNECTIONS[name] = libvirt.openAuth(libvirt_url, auth)

    return LIBVIRT_CONNECTIONS[name]
Example #42
0
    def run(self):
        loop.virEventLoopPureRegister()
        libvirt.registerErrorHandler(error_handler, self)

        while True:
            try:
                with self._conn as conn:
                    conn.registerCloseCallback(connection_close_callback, self)
                    conn.domainEventRegister(lifecycle_callback, self)
                loop.virEventLoopPureRun()
            except Exception as e:
                error(e)
                sleep(5)
Example #43
0
    def run(self):
        loop.virEventLoopPureRegister()
        libvirt.registerErrorHandler(error_handler, self)

        while True:
            try:
                with self._conn as conn:
                    conn.registerCloseCallback(connection_close_callback, self)
                    conn.domainEventRegister(lifecycle_callback, self)
                loop.virEventLoopPureRun()
            except Exception as e:
                error(e)
                sleep(5)
Example #44
0
        def _create_connection():
            libvirt.registerErrorHandler(_error_handler, ctx=None)

            url = self.get_virt_url()

            if not url:
                raise error.ConnError("[libvirt] No connection url supplied")

            virt = libvirt.open(url)

            if not virt:
                raise error.ConnError("[libvirt] Could not connect "
                                      "to {}".format(url))
            return virt
Example #45
0
 def __init__(self, logger, registerEvents=True):
     self.changedCallback = None
     self.logger = logger
     self.virt = None
     # Log libvirt errors
     libvirt.registerErrorHandler(lambda ctx, error: None, None) #self.logger.exception(error), None)
     try:
         self.virt = libvirt.openReadOnly("")
         # Register listener for domain changes if we are not in oneshot mode
         if registerEvents:
             self.virt.domainEventRegister(self.changed, None)
             event.virtType = self.virt.getType()
     except libvirt.libvirtError, e:
         raise VirtError(str(e))
Example #46
0
        def _create_connection():
            libvirt.registerErrorHandler(_error_handler, ctx=None)

            url = self.get_virt_url()

            if not url:
                raise error.ConnError("[libvirt] No connection url supplied")

            virt = libvirt.open(url)

            if not virt:
                raise error.ConnError("[libvirt] Could not connect "
                                      "to {}".format(url))
            return virt
Example #47
0
 def connect(self):
     """
     Connect to the hypervisor.
     """
     if self.connected is False:
         try:
             libvirt.registerErrorHandler(self.handler, 'context')
             self.connection = libvirt.open(self.uri)
         except libvirt.libvirtError:
             self.connected = False
             return None
         else:
             self.connected = True
     return self.connection
Example #48
0
 def __init__(self, logger, config, dest, terminate_event=None,
              interval=None, oneshot=False, registerEvents=True):
     super(Libvirtd, self).__init__(logger, config, dest,
                                    terminate_event=terminate_event,
                                    interval=interval,
                                    oneshot=oneshot)
     self.changedCallback = None
     self.registerEvents = registerEvents
     self._host_capabilities_xml = None
     self._host_socket_count = None
     self._host_uuid = None
     self._host_name = None
     self.eventLoopThread = None
     libvirt.registerErrorHandler(lambda ctx, error: None, None)
Example #49
0
def main():
    libvirt.virEventRegisterDefaultImpl()
    libvirt.registerErrorHandler(handleLibvirtLibraryError, None)

    worker = threading.Thread(target=work)
    worker.setDaemon(True)
    worker.start()

    eventLoop = threading.Thread(target=virEventLoopNativeRun)
    eventLoop.setDaemon(True)
    eventLoop.start()

    while True:
       time.sleep(1)
Example #50
0
 def __init__(self, logger, config, dest, terminate_event=None,
              interval=None, oneshot=False, registerEvents=True):
     super(Libvirtd, self).__init__(logger, config, dest,
                                    terminate_event=terminate_event,
                                    interval=interval,
                                    oneshot=oneshot)
     self.changedCallback = None
     self.registerEvents = registerEvents
     self._host_capabilities_xml = None
     self._host_socket_count = None
     self._host_uuid = None
     self._host_name = None
     self.eventLoopThread = None
     libvirt.registerErrorHandler(lambda ctx, error: None, None)
Example #51
0
 def __init__(self, logger, registerEvents=True):
     self.changedCallback = None
     self.logger = logger
     self.virt = None
     # Log libvirt errors
     libvirt.registerErrorHandler(lambda ctx, error: None, None) #self.logger.exception(error), None)
     try:
         self.virt = libvirt.openReadOnly("")
         # Register listener for domain changes if we are not in oneshot mode
         if registerEvents:
             self.virt.domainEventRegister(self.changed, None)
             event.virtType = self.virt.getType()
     except libvirt.libvirtError, e:
         raise VirtError(str(e))
Example #52
0
 def connect(self):
     """
     Connect to the hypervisor.
     """
     if self.connected is False:
         try:
             libvirt.registerErrorHandler(self.handler, 'context')
             self.connection = libvirt.open(self.uri)
         except libvirt.libvirtError:
             self.connected = False
             return None
         else:
             self.connected = True
     return self.connection
Example #53
0
    def initialize(self):
        # prepare libvirt
        libvirt.registerErrorHandler(self._native_libvirt_error_handler, None)
        libvirt.virEventRegisterDefaultImpl()

        # start native listening thread
        self._native_event_queue = native_queue.Queue()
        self._event_thread = native_threading.Thread(
            target=self._native_thread)
        self._event_thread.setDaemon(True)
        self._event_thread.start()

        # prepare dispatching greenthread
        eventlet.spawn_n(self._dispatch_event)
Example #54
0
 def __init__(self):
     """Get config and setup loggings."""
     self.config = config.setup()
     self.log = logging.getLogger(__name__)
     #This block gets interface and interface type from config file
     self._lookupInterfaces()
     #And this one does the same for disks.
     self._lookupDisks()
     self.search_headers = self.config.get('VM', 'search_headers', 'name,uuid')
     self.headers = self.search_headers.split(',')
     def _error_handler(self, err):
         msg = "Ignoring Libvirt error %s)" % err
         pass
     # Prevent libvirt errors from reaching the console
     libvirt.registerErrorHandler(_error_handler, None)
Example #55
0
def register_libvirt_error_handler():
    """
    Ignore libvirt error reporting, we just use exceptions
    """
    def libvirt_callback(userdata, err):
        ignore = userdata
        ignore = err

    def libxml2_callback(userdata, err):
        ignore = userdata
        logging.debug("libxml2 callback error: %s", err)

    libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
    import libxml2
    libxml2.registerErrorHandler(f=libxml2_callback, ctx=None)
Example #56
0
    def init_vmm_connection(self):
        if self._libvirt_conn is not None:
            # Already initialized
            return
        if self._offline_mode:
            # Do not initialize in offline mode
            return

        if 'xen.lowlevel.xs' in sys.modules:
            self._xs = xen.lowlevel.xs.xs()
        self._libvirt_conn = libvirt.open(defaults['libvirt_uri'])
        if self._libvirt_conn == None:
            raise QubesException("Failed connect to libvirt driver")
        libvirt.registerErrorHandler(self._libvirt_error_handler, None)
        atexit.register(self._libvirt_conn.close)
Example #57
0
	def run(self, params, args):
		if not len(args):
			self.abort('must supply at least one host')

		for node in self.newdb.getNodesfromNames(args,
				preload=['vm_defs', 'vm_defs.disks']):
			self.runPlugins(node)
			vmnodeid = None
			mem = None
			cpus = None
			macs = None
			disks = None

			#
			# get the name of the physical node that hosts
			# this VM
			#

			if node.vm_defs and node.vm_defs.physNode:

				#
				# try to undefine the domain in libvirt
				#
				libvirt.registerErrorHandler(handler, 'context')
				try:
					hipervisor = libvirt.open(rocks.vmconstant.connectionURL \
							% node.vm_defs.physNode.name)
					dom = hipervisor.lookupByName(node.name)
					dom.undefine()
				except libvirt.libvirtError, m:
					if 'unable to connect' in str(m):
						# connection problem just report it do not fail
						print "Warning (libvirt): ", m
					# the domain was not defined, no big deal
					pass

			#
			# now remove the relevant rows in the database for
			# this VM
			#
			if node.vm_defs:
				s = self.newdb.getSession()
				s.delete(node.vm_defs)
				for disk in node.vm_defs.disks:
					s.delete(disk)
Example #58
0
    def init_vmm_connection(self):
        '''Initialise connection

        This method is automatically called when getting'''
        if self._libvirt_conn is not None:
            # Already initialized
            return
        if self._offline_mode:
            # Do not initialize in offline mode
            raise qubes.exc.QubesException(
                'VMM operations disabled in offline mode')

        if 'xen.lowlevel.xs' in sys.modules:
            self._xs = xen.lowlevel.xs.xs()
        if 'xen.lowlevel.xc' in sys.modules:
            self._xc = xen.lowlevel.xc.xc()
        self._libvirt_conn = VirConnectWrapper(
            qubes.config.defaults['libvirt_uri'])
        libvirt.registerErrorHandler(self._libvirt_error_handler, None)
Example #59
0
    def __init__(self):
        self.lock = threading.RLock()
        try:
            # try to use libvirt
            import libvirt
            libvirt.virInitialize()
            globals()["libvirt"] = libvirt
            
            # register an ErrorCallback
            def errHandler(ctx, error):
                # log.debug("backend error: %s" % (error,))
                pass
            libvirt.registerErrorHandler(errHandler, None)

            self.con = libvirt.open(None)
            log.info("backend connected to libvirt")
        except:
            log.error("could not connect to xen backend!")
            raise