Giter VIP home page Giter VIP logo

virt-lightning's Introduction

๐Ÿ—ฒ spawn Cloud instances on libvirt!๐Ÿ—ฒ

Build Status PyPI version Documentation

Logo

You want to spawn local VM quickly.. Like... really quickly. You want them to be as generical as possible. Actually you would like to reuse some existing cloud images!

This is the right tool for you.

Virt-Lightning exposes a CLI inspired by the Cloud and Vagrant. It can also prepare the Ansible inventory file.

This is handy to quickly validate a new Ansible playbook, or a role on a large number of environments.

example: less than 30 seconds to spawn an instance โšก

In a nutshell:

echo "- distro: centos-7" > virt-lightning.yaml
vl up
vl ansible_inventory > inventory
ansible all -m ping -i inventory

example: or 75 seconds for 10 nodes lab โšก

During this recording, we:

  1. use the list of distribution to generate a virt-lightning.yaml file.
  2. we then create a environment based on this file
  3. once the environment is ready, we generate an Ansible inventory file
  4. and we use it to call Ansible's ping module on all the host.

demo

Requirements

  • Python 3.8 or greater
  • The Python3 binding for libvirt, the package is probably called python3-libvirt or 'libvirt-python' according to pip.
  • Libvirt must be running, most of the time you just need to run: sudo systemctl start --now libvirtd
  • Finally, be sure your user can access the system libvirt daemon, e.g with: virsh -c qemu:///system

Optional

  • You make also want to install python3-urwid if you want to get the fancy list of VM. This dependency is optional.

Installation (Fedora/RHEL)

sudo dnf install libvirt-devel gcc python3-devel pipx
pipx ensurepath
pipx install virt-lightning

Installation (Debian/Ubuntu)

sudo apt install python3-venv pkg-config gcc libvirt-dev python3-dev pipx
pipx ensurepath
pipx install virt-lightning

Post Installation

virt-lightning will be installed in ~/.local/bin/. Add it in your $PATH if it's not already the case. For instance if you use:

echo "export PATH=$PATH:~/.local/bin/" >> ~/.bashrc
source ~/.bashrc

Fetch some images

Before you start your first VM, you need to fetch the images. To do so, you just use the vl fetch command:

$ vl fetch fedora-32

Actions

vl is an alias for virt-lightning, you can us both. In the rest of the document we use the shortest version.

vl distro_list

List the distro images that can be used. Its output is compatible with vl up. You can initialize a new configuration with: vl distro_list > virt-lightning.yaml.

vl up

virt-lightning will read the virt-lightning.yaml file from the current directory and prepare the associated VM.

vl down

Destroy all the VM managed by Virt-Lightning.

vl start

Start a specific VM, without reading the virt-lightning.yaml file.

vl stop

Stop just one VM.

vl status

List the VM, their IP and if they are reachable.

vl ansible_inventory

Export an inventory in the Ansible format.

vl ssh

Show up a menu to select a host and open a ssh connection.

vl ssh

vl console

Like vl ssh but with the serial console of the VM.

vl ssh

vl viewer

Like vl console but with the SPICE console of the VM. Requires virt-viewer.

vl fetch

Fetch a VM image. You can find here a list of the available images. You can also update the custom configuration to add a private image hub.

Configuration

Global configuration

If ~/.config/virt-lightning/config.ini exists, Virt-Lightning will read its configuration there.

[main]
network_name = virt-lightning
root_password = root
storage_pool = virt-lightning
network_auto_clean_up = True
ssh_key_file = ~/.ssh/id_rsa.pub

network_name: if you want to use an alternative libvirt network

root_password: the root password

storage_pool: if you want to use an alternative libvirt storage pool

network_auto_clean_up: if you want to automatically remove a network when running virt-lightning down

ssh_key_file: if you want to use an alternative public key

private_hub: if you need to set additional url from where images should be retrieved, update the configuration file ~/.config/virt-lightning/config.ini adding the following

[main]
private_hub=url1,url2

VM configuration keys

A VM can be tuned at two different places with the following keys:

  • distro: the name of the base distro image to use, it's the only mandatory parameter.
  • name: the VM name
  • memory: the amount of memory to dedicate to the VM
  • vcpus: the number of vcpu to dedicate to the VM
  • root_password: the root password in clear text
  • ssh_key_file: the path of the public key for connecting to the VM
  • groups: this list of groups will be used if you generate an Ansible inventory.
  • disks: a list of disks to create and attach to the VM. The first one is used as the root disk. Default to [{"size": 15}]
    • size the size of the disk in GB. Default is 1.
  • networks: a list of network to attach to the VM. The default is: one virtio interface attached to virt-lightning network.
    • network: the name of the libvirt network. Default is the key network_name from the configuration (virt-lightning by default). The key cannot be used with bridge.
    • ipv4: a static IPv4. Default is a dynamic IPv4 address.
    • nic_model: the libvirt driver to use. Default is virtio
    • mac: an optional static MAC address, e.g: '52:54:00:71:b1:b6'
    • bridge: optional, the name of a bridge to connect too. This key replace the network key.
    • virtualport_type: The type of the virtualport, currently, this is can be used with bridge.

Example: a virt-lightning.yaml file:

- name: esxi-vcenter
  distro: esxi-6.7
  memory: 12000
  root_disk_size: 30
  vcpus: 2
  root_password: '!234AaAa56'
  groups: ['all_esxi']
- name: esxi1
  distro: esxi-6.7
  memory: 4096
  vcpus: 1
  root_password: '!234AaAa56'
  groups: ['all_esxi', 'esxi_lab']
- name: esxi2
  distro: esxi-6.7
  memory: 4096
  vcpus: 1
  root_password: '!234AaAa56'
  groups: ['all_esxi', 'esxi_lab']
- name: centos-7
  distro: centos-7
  networks:
    - network: default
      ipv4: 192.168.122.50
  bootcmd:
    - yum update -y

Example: connect to an OpenvSwitch bridge

- name: controller
  distro: fedora-35
  - bridge: my-ovs-bridge-name
    virtualport_type: openvswitch

You can also associate some parameters to the distro image itself

cat /var/lib/virt-lightning/pool/upstream/esxi-6.7.yaml
username: root
python_interpreter: /bin/python
memory: 4096
networks:
  - network: virt-lightning
    nic_model: virtio
  - network: default
    nic_model: e1000

Example: working with snapshots

User can create a snapshot of VM to restore it later. Default configuration of virt-lightning supports snapshots both for running and powered off VMs. qcow2 disk format used allows diskspace-wise incremental snapshotting, keeping only updated storage blocks. virsh tool supports it by CLI, virt-manager provides a neat GUI supporting the most of the features

# create first snapshot of running machine
virsh snapshot-create-as --domain vm_name --name snapshot_1
# create second snapshot
virsh snapshot-create-as --domain vm_name --name snapshot_2
# validate that both of them were saved
virsh snapshot-list vm_name
# and revert to the first one
virsh snapshot-revert vm_name --snapshotname snapshot_1

Development

install libvirt-dev package:

Debian/Ubuntu:

apt install python3-venv pkg-config gcc libvirt-dev python3-dev

Fedora/RHEL:

dnf install python3-devel gcc libvirt-devel

You can run a development copy in a virtual env:

python3 -m venv /tmp/vl-dev-venv
. /tmp/vl-dev-venv/bin/activate
pip3 install -r requirements.txt
pip3 install -e /path/to/my-virt-lightning-copy
vl

The changes that are introduce in /path/to/my-virt-lightning-copy should be visible when you run vl from within the virtual env. running test will require:

pip3 install -r test-requirements.txt

virt-lightning's People

Contributors

abikouo avatar bubavv avatar dogukancagatay avatar eclipseo avatar ekohl avatar goneri avatar hguemar avatar jerzerisz avatar jpic avatar lgtm-com[bot] avatar lgtm-migrator avatar mksh avatar mscherer avatar musicinmybrain avatar ooraini avatar pilou- avatar rgoncalvesse avatar sperreault avatar themr0c avatar zdykstra avatar zloidemon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

virt-lightning's Issues

genisoimage not available on some systems

I'm running virt-lightning on Void Linux, which does not package genisoimage. It does package makeisofs which seems to be fully compatible with the arguments passed to genisoimage. I can just duplicate the solution used to find the KVM binary, unless you'd like this as a configuration option.

We need support of qemu:///system URI

Ubuntu 18.04 does not allow qemu:///session URI unless we do intensive system reconfiguration. Since we want virt-lightning to be as simple as possible, we need to try another option.

  • Use Libvirt storage pool, do not hard code the path
  • The images scripts use dynamically the correct path
  • Use qemu:///session

Use python2 in inventory for Trusty VM

Doing some tinkering with Trusty VM and found that it has ansible_python_interpreter=/usr/bin/python3 in inventory file, which is incorrect. Trusty python3 is 3.4, and current ansible 2.9 wants at least 3.5 on client host. Alternative is to change it to python2 in inventory. Could we create inventory distro-wise and ensure, that correct python version is defined?

logging system

We don't have any logging system in place. As a result, we flood the terminal with print() output.

It would be nice to have a debug system. It should allow us to redirect the log to a file and filter the messages depending on the severity:

sl --debug up
sl --log-file ~/tmp/somewhere.log down

Add support for forwarded SSH key

I think that support of public keys extracted from ssh-add -L output would be nice. It will help a bit to run vl on some cloud VM accessed via ssh -A user@vm command. Currently, i need to copy id_rsa.pub from localhost to VM. Also, unrelated, but somewhat related issue: ssh_key_file config option is not documented yet

Libvirt network config doesn't handle DHCP section

IP address defined in yaml file hasn't saved to libvirt network config. In case of VM stopped by some reason (e.g. host reboot) it loses IP lease after some time. If request address by DHCP service, it will be random from network range. Alternative to it is some universal way to define static IP

Deeper context/username support

First, I'd like to thank everybody involved with this project!

I'd like to use this on a hypervisor with multiple users. With use of the --context argument, this is generally possible. However, there are a few gotchas that I'd like to smooth over, if patches for these would be accepted.

  • Allow context to be more easily set. If I create two project directories, with two different virt-lightning.yaml configs in them, they both end up in the same default context, unless I explicitly pass --context to all operations. This means that if I'm not careful some day, I'll vl down in the wrong place and nuke the wrong project. I'd like to add support to set context as a top-level key in virt-lightning.yaml, and use that to help limit the scope of operations more easily.

  • Possibly update the output of vl status to show the context, since it can now be read from a config file.

  • Add a config option to enable operating only on VMs that match our username, via vl:username. This way, even if I'm in the same context as another user, I won't be able to see their VMs. By default this would be disabled, but could be enabled via a config.ini flag.

Any additions would keep the current behavior as the default - you'd have to opt-in to these modifications via config.ini adjustments. Let me know your thoughts on this.

Configuration file

We don't use any configuration file yet. For now, the configuration structure is hardcoded at the top of shell.py. We should use something like configparser to handle that.

Allow specifiying the video model

I'm running CentOS 9 Stream locally, and I'm unable to run vl up due to an issue with the qxl video model.

โฏ vl up
โšก centos-9-stream 
Traceback (most recent call last):
  File "/home/ooraini/.local/bin/vl", line 8, in <module>
    sys.exit(main())
  File "/home/ooraini/.local/lib/python3.9/site-packages/virt_lightning/shell.py", line 362, in main
    action_func(configuration=configuration, **vars(args))
  File "/home/ooraini/.local/lib/python3.9/site-packages/virt_lightning/api.py", line 206, in up
    loop.run_until_complete(deploy())
  File "/usr/lib64/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/home/ooraini/.local/lib/python3.9/site-packages/virt_lightning/api.py", line 198, in deploy
    await f
  File "/usr/lib64/python3.9/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/ooraini/.local/lib/python3.9/site-packages/virt_lightning/api.py", line 122, in _start_domain
    domain = hv.create_domain(name=host["name"], distro=distro)
  File "/home/ooraini/.local/lib/python3.9/site-packages/virt_lightning/virt_lightning.py", line 111, in create_domain
    dom = self.conn.defineXML(ET.tostring(root).decode())
  File "/usr/lib64/python3.9/site-packages/libvirt.py", line 4414, in defineXML
    raise libvirtError('virDomainDefineXML() failed')
libvirt.libvirtError: unsupported configuration: domain configuration does not support video model 'qxl'

I think the issue is with the unavailable package qemu-ui-gtk. Is there any specific requirement for qxl?

The following lines are relevant:

virt-lightning and molecule

My initial thought was that VL could be used as backend for ansible-community/molecule-libvirt#13 implementation but after I realized that VL does not work on platforms like MacOS or Windows and it lacks remoting support, I decided that as pure libvirt implementation would be more appropriate. That does not mean that a molecule-vl driver should not be created.

In fact you can easily make the library itself expose a molecule driver entry-point, avoiding the need to create a new project for the driver project. The magic line is https://github.com/ansible-community/molecule-libvirt/blob/master/setup.cfg#L87-L88

In the end is up to you to decide if you want to do it as part of the same project or not, each approach has pros and cons. If you really want a new project created under https://github.com/ansible-community/ and had CI configured, just let me know and I will do it.

Explain how to use with qemu:///session

These days I'm used to gnome-boxes, which uses qemu:///session by default on Fedora 34, and provides all things I need. VMs have volumes, snapshots, network access...

It would be awesome to be able to automate all that stuff with vl, but it seems to be tied to qemu:///system. Is there a way to configure it to use qemu:///session?

integrate the image creation in the main command

At this point, the image creation is handled by a collection of shell scripts. The idea is to integrate that in the main command:

$ vl image-list
debian-8
debian-9
(etc)
$ vl image-prepare debian8
Downloading debian-8 master image
100%
Preparing the image for virt-lightning
blabla
blabal
Done, image is ready!

better support VM image file extensions for config.ini private_hub=

First noticed this trying FreeBSD-14 alpha, their images are compressed: https://download.freebsd.org/releases/VM-IMAGES/14.0-BETA5/amd64/Latest/FreeBSD-14.0-BETA5-amd64-zfs.qcow2.xz

I figured so be it, however Ubuntu feels the need to play file extensions:
[ ] mantic-server-cloudimg-amd64.img 2023-10-09 15:18 743M QCow2 UEFI/GPT Bootable disk image

It's simple enough to work around:
curl -o /var/lib/virt-lightning/pool/upstream/ubuntu-23-10.qcow2 https://cloud-images.ubuntu.com/mantic/current/mantic-server-cloudimg-amd64.img

Doesn't look like it would be terribly hard to adjust:

def fetch_from_url(progress_callback=None, url=None, **kwargs):
for some limited support (.img/.xz compressed) files.

Certainly a niche issue, but any thoughts?

vl doesn't seem to work with Python 3.10

โฏ vl up
Traceback (most recent call last):
  File "/home/thalin/.local/bin/vl", line 8, in <module>
    sys.exit(main())
  File "/home/thalin/.local/lib/python3.10/site-packages/virt_lightning/shell.py", line 378, in main
    action_func(configuration=configuration, **vars(args))
  File "/home/thalin/.local/lib/python3.10/site-packages/virt_lightning/api.py", line 183, in up
    _register_aio_virt_impl(loop)
  File "/home/thalin/.local/lib/python3.10/site-packages/virt_lightning/api.py", line 68, in _register_aio_virt_impl
    libvirtaio.virEventRegisterAsyncIOImpl(loop=loop)
  File "/usr/lib/python3/dist-packages/libvirtaio.py", line 477, in virEventRegisterAsyncIOImpl
    _current_impl = virEventAsyncIOImpl(loop=loop).register()
  File "/usr/lib/python3/dist-packages/libvirtaio.py", line 285, in __init__
    self._finished = asyncio.Event(loop=loop)
  File "/usr/lib/python3.10/asyncio/locks.py", line 168, in __init__
    super().__init__(loop=loop)
  File "/usr/lib/python3.10/asyncio/mixins.py", line 17, in __init__
    raise TypeError(
TypeError: As of 3.10, the *loop* parameter was removed from Event() since it is no longer necessary

ensure copy on write is turned off on btrfs drives

If, for the directory /var/lib/virt-lightning/pool/upstream, the underlying filesystem is BTRFS, then we should make sure the images are created with copy on write turned off.

There are several ways to do it:

  • make sure /var/lib/virt-lightning/pool/upstream is created with nocow option
  • chattr -C on the empty files

I am not sure which ways should be the most suitable for the project.
I am not sure other filesystems than BTRFS would be impacted.

References:

Enable Flake8-pyproject

In order to centralize the configuration at one single place, ot would be nice to move the Flake8 configuration from the tox.ini to the pyproject.toml file.

give the user a way to prepare the set-up

The users need a couple of pre-configuration before they can start using virt-lightning:

  • check if the dependency are installed
  • decide if they want to use qemu:///system or qemu:///session
  • ensure a SSH keypair is available
  • create the storage directory
  • create the libvirt storage pool
  • create the libvirt network (either default or a new network)
  • prepare the configuration file

Currently, these steps are either just documented in the README, or done during the run-time. I imagine a new action called vl config that would handle that for the user.

$ vl config --auto
Creating the storage directory in ~/.local/share/virt-lightning/pool/
Creating the libvirt storage pool
Ensure libvirt can use the virbr0 bridge
No ssh keypair found, generating on dedicated to virt-lighting
Generate the configuration file in ~/.config/virt-lightning/config.ini
$vl config
How do you want to use libvirt:
1) qemu:///session: does not require root privilege, the network features are limited
2) qemu:///system: requires extra privilege, but provide a full access to libvirt, including the creation of new network
-> 2
Checking the access to qemu:///system:
You need some extra configuration changes to be able to use qemu:///session:
Enable Polkit password-less authentication: **Yes**/No
Add the following groups (libvirt, qemu) to the current user (foobar): **Yes**/No
Where do you want to store your data (default: /var/lib/virt-lightning/pool):
Creating the storage directory in /var/lib/virt-lightning/pool
Do you want to use a dedicated network for your VM: **Yes**/No
Creating the virt-lightning libvirt network
No ssh keypair found, generating on dedicated to virt-lighting
Generate the configuration file in ~/.config/virt-lightning/config.ini

The storage pool should be created automatically

User story: John wants to use virt-lightning, but he still needs to create the pool storage and he don't want to read Libvirt documentation.

We should provide a vl init command that prepare the storage pool for the user.

Snapshots / restore?

Hi!

Maybe it would be interresting to be able to create our own boxes from VMs like vCenter does, except we do it via Python API / CLI.

What do you think?

Help command showing inaccurate information

Hi,

First of, wonderfull work :)

When using $ vl --help,I've noticed that the options up, down, status, and distro_list are showing inaccurate information:

$ vl --help
usage: vl [-h] [--debug] [--config CONFIG]
          {up,down,start,stop,status,distro_list,storage_dir,ansible_inventory,ssh_config,ssh,console,fetch}
          ...

optional arguments:
  -h, --help            show this help message and exit
  --debug               Print extra information (default: False)
  --config CONFIG       path to configuration file

action:
  {up,down,start,stop,status,distro_list,storage_dir,ansible_inventory,ssh_config,ssh,console,fetch}
    up                  first
    down                first
    start               Start a new VM
    stop                Stop a VM
    status              first
    distro_list         first
    storage_dir         Print the storage directory
    ansible_inventory   Print an ansible_inventory of the running environment
    ssh_config          Print a ssh config of the running environment
    ssh                 SSH to a given host
    console             Open the console of a given host
    fetch               Fetch a VM image

It is just showing first, not so helpful :)

I assume that is should be the information described in the README.md file.

Thank you!

Failed to connect socket to '/opt/homebrew/var/run/libvirt/virtqemud-sock'

Hi, first of all, thanks for your time and for sharing this library, I am trying to give it on macOS, I already installed libvirt:

brew install qemu gcc libvirt

Testing with:

virsh -c qemu:///system

return:

error: failed to connect to the hypervisor
error: Failed to connect socket to '/opt/homebrew/var/run/libvirt/virtqemud-sock': No such file or directory

libvirt is started, any ideas?

vl stop nonexistent-vm should not return an error

For idempotency purpose, I tried to run vl stop twice on the same virtual machine.

I expected the second run to do nothing, as the virtual machine has already been taken down by the first run, but I received this error:

+ vl stop fedora-34
No running VM.
Traceback (most recent call last):
  File "/home/remote/ffloreth/.local/bin/vl", line 8, in <module>
    sys.exit(main())
  File "/home/remote/ffloreth/.local/lib/python3.9/site-packages/virt_lightning/shell.py", line 378, in main
    action_func(configuration=configuration, **vars(args))
  File "/home/remote/ffloreth/.local/lib/python3.9/site-packages/virt_lightning/api.py", line 284, in stop
    raise VMNotFound(kwargs["name"])
virt_lightning.api.VMNotFound: fedora-34

setting staitc ip with ivp4 dosen't work

Hi,
I have a problem to set a static IP address to VMs.
this is my virt-lightning.yaml:

- name: ansible
  distro: debian-11-genericcloud-amd64
  networks:
    - ipv4: 192.168.150.1
    - network: virt-lightning
- name: debian11
  distro: debian-11-genericcloud-amd64
  networks:
    - ipv4: 192.168.150.10
    - network: virt-lightning
- name: rocky
  distro: Rocky-8-GenericCloud.latest.x86_64
  ipv4: 192.168.150.20
- name: suse
  distro: openSUSE-Leap-15.3.x86_64-1.0.1-NoCloud-Build2.186
  networks:
    - ipv4: 192.168.150.30
- name: ubuntu
  distro: ubuntu-20.04
  ipv4: 192.168.150.40

With this I tried something to show you the problems:
This is the output in the console after vl up:

โšก ansible 
โšก debian11 
โšก rocky 
โšก suse 
โšก ubuntu 
โŒ› ok Waiting...
๐Ÿ’ป ansible found at 192.168.150.1!
๐Ÿ›ƒ rocky QEMU agent found
๐Ÿ›ƒ suse QEMU agent found
๐Ÿ’ป ubuntu found at 192.168.150.6!
๐Ÿ’ป rocky found at 192.168.150.5!
๐Ÿ’ป suse found at 192.168.150.30!
๐Ÿ’ป debian11 found at 192.168.150.10!
๐Ÿ‘ You are all set

problem 1:
in this example ansible gets 192.168.150.1. But 1 is normally the IP of the host (same problem with vangrant, the reason I try your nice program here)
problem 2:
setting IP like with ubuntu dosen't work. Would be enough to give an example in the documentation.

Add delete function

Since we can start VMs with vl start, it would be nice to also delete them with vl delete, I'm also interested in the api.delete() function.

Would you like to see a patch? That's what I currently have, it comes from the api.down() function:

from virt_lightning import api as vl

def vm_delete(name):
    conn = vl._connect_libvirt(vlconf.libvirt_uri)
    hv = vl.vl.LibvirtHypervisor(conn)
    hv.init_network(vlconf.network_name, vlconf.network_cidr)
    hv.init_storage_pool(vlconf.storage_pool)
    for domain in hv.list_domains():
        if domain.name == name:
            hv.clean_up(domain)
    return 'deleted'

Support ovs bridge

Great software!!!

Can it support openvswitch bridge interfaces?

<interface type='bridge'>
 <mac address='52:54:00:71:b1:b6'/>
 <source bridge='ovsbr'/>
 <virtualport type='openvswitch'/>
 <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>

I can't make it work

I have done the following:

vl fetch centos-8

When I check:

vl distro_list
- centos-8

but not preceded by - distro: like in the gif.

So when I do

vl distro_list > virt-lightning.yaml
vl up

I get the following error:

Traceback (most recent call last):
  File "/usr/bin/vl", line 33, in <module>
    sys.exit(load_entry_point('virt-lightning==2.0.1', 'console_scripts', 'vl')())
  File "/usr/lib/python3.9/site-packages/virt_lightning/shell.py", line 328, in main
    action_func(configuration=configuration, **vars(args))
  File "/usr/lib/python3.9/site-packages/virt_lightning/api.py", line 149, in up
    _ensure_image_exists(hv, virt_lightning_yaml)
  File "/usr/lib/python3.9/site-packages/virt_lightning/api.py", line 117, in _ensure_image_exists
    distro = host.get("distro")
AttributeError: 'str' object has no attribute 'get'

No distro is found so it fails.

Ubuntu 18.04 not found /etc/qemu/bridge.conf on up

Not found /etc/qemu/bridge.conf

 %> vl up
Starting:centos7
Traceback (most recent call last):
  File "/home/vg/Devel/virt-lightning/tmp/.venv/bin/vl", line 11, in <module>
    load_entry_point('virt-lightning', 'console_scripts', 'vl')()
  File "/home/vg/Devel/virt-lightning/virt_lightning/shell.py", line 331, in main
    globals()[args.action](configuration=configuration, **vars(args))
  File "/home/vg/Devel/virt-lightning/virt_lightning/shell.py", line 61, in up
    hv.start(domain)
  File "/home/vg/Devel/virt-lightning/virt_lightning/virt_lightning.py", line 189, in start
    domain.dom.create()
  File "/home/vg/Devel/virt-lightning/tmp/.venv/lib/python3.6/site-packages/libvirt.py", line 1068, in create
    if ret == -1: raise libvirtError ('virDomainCreate() failed', dom=self)
libvirt.libvirtError: internal error: /usr/lib/qemu/qemu-bridge-helper --use-vnet --br=virbr0 --fd=25: failed to communicate with bridge helper: Transport endpoint is not connected
stderr=failed to parse default acl file `/etc/qemu/bridge.conf'

System:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:        18.04
Codename:       bionic

Also has installed bridge-utils.

pip 21.3 fails to resolve test requirements

Pip uses new dependency resolver since 20.3. It fixes some nasty bugs, but works very slow with unpinned dependencies. It affects tox testing - env build lasts at least tens of minutes
Steps to reproduce:

  1. Create virtualenv and activate it. Python >3.6 is good
  2. Update pip: pip install -U pip. Ensure that pip -V returns value greater then 20.3
  3. pip install -r test-requirements.txt
    It will run for some very long times trying to resolve all dependencies

Possible solution: pin exact versions of flake8 packages in test-requirements.txt

Live snapshot is not supported

In release 2.3.0, it is impossible to create snapshot of running VM. It is caused by cidata cdrom created as disk, generating such device XML:

<disk type="file" device="disk">
  <driver name="qemu" type="raw"/>
  <source file="/var/lib/virt-lightning/pool/vl_vm-cidata.qcow2" index="1"/>
  <backingStore/>
  <target dev="vdb" bus="virtio"/>
  <alias name="virtio-disk1"/>
  <address type="pci" domain="0x0000" bus="0x00" slot="0x07" function="0x0"/>
</disk>

Steps to reproduce:

  1. Startup the simplest VM. Here is example of yaml:
- name: vl_vm
  distro: ubuntu-20.04
  memory: 512
  root_disk_size: 5
  1. Try to create snapshot of running VM:
    virsh snapshot-create-as --domain vl_vm --name snapshot_1

As a result, we have such error message:
error: unsupported configuration: internal snapshot for disk vdb unsupported for storage type raw

Proposed PR #271 to fix an issue

py3.10: TypeError: As of 3.10, the *loop* parameter was removed from Event() since it is no longer necessary

โฏ vl up
Traceback (most recent call last):
  File "/home/jbpratt/.local/bin/vl", line 8, in <module>
    sys.exit(main())
  File "/home/jbpratt/.local/lib/python3.10/site-packages/virt_lightning/shell.py", line 362, in main
    action_func(configuration=configuration, **vars(args))
  File "/home/jbpratt/.local/lib/python3.10/site-packages/virt_lightning/api.py", line 168, in up
    _register_aio_virt_impl(loop)
  File "/home/jbpratt/.local/lib/python3.10/site-packages/virt_lightning/api.py", line 68, in _register_aio_virt_impl
    libvirtaio.virEventRegisterAsyncIOImpl(loop=loop)
  File "/home/jbpratt/.local/lib/python3.10/site-packages/libvirtaio.py", line 462, in virEventRegisterAsyncIOImpl
    _current_impl = virEventAsyncIOImpl(loop=loop).register()
  File "/home/jbpratt/.local/lib/python3.10/site-packages/libvirtaio.py", line 277, in __init__
    self._finished = asyncio.Event(loop=loop)
  File "/usr/lib/python3.10/asyncio/locks.py", line 167, in __init__
    super().__init__(loop=loop)
  File "/usr/lib/python3.10/asyncio/mixins.py", line 17, in __init__
    raise TypeError(
TypeError: As of 3.10, the *loop* parameter was removed from Event() since it is no longer necessary

Exception thrown in the virt-python dependency. Issue has been opened here https://gitlab.com/libvirt/libvirt-python/-/issues/10

vl crashes after successfully image download

Steps to reproduce:

  1. Create yaml requiring non-existing locally image, i.e. ubuntu-18.04
  2. do $ vl up
    vl crashes after successful image download:
$ vl up                                                                                                                                
downloading image from: https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64.img                                                                                                    
Image ubuntu-18.04 is ready!                                                                                                                                                                               
Traceback (most recent call last):                                                                                                                                                                         
  File "/home/vmarkov/.local/bin/vl", line 8, in <module>                                                                                                                                                  
    sys.exit(main())                                                                                                                                                                                       
  File "/home/vmarkov/.local/lib/python3.8/site-packages/virt_lightning/shell.py", line 362, in main                                                                                                       
    action_func(configuration=configuration, **vars(args))                                                                                                                                                 
  File "/home/vmarkov/.local/lib/python3.8/site-packages/virt_lightning/api.py", line 184, in up                                                                                                           
    _ensure_image_exists(hv, virt_lightning_yaml)                                                                                                                                                          
  File "/home/vmarkov/.local/lib/python3.8/site-packages/virt_lightning/api.py", line 150, in _ensure_image_exists                                                                                         
    if distro not in hv.distro_available():                                                                                                                                                                
  File "/home/vmarkov/.local/lib/python3.8/site-packages/virt_lightning/virt_lightning.py", line 639, in distro_available                                                                                  
    path = self.get_storage_dir() / "upstream"                                                                                                                                                             
  File "/home/vmarkov/.local/lib/python3.8/site-packages/virt_lightning/virt_lightning.py", line 195, in get_storage_dir                                                                                   
    xml = self.storage_pool_obj.XMLDesc(0)                                                                                                                                                                 
  File "/usr/lib/python3/dist-packages/libvirt.py", line 3490, in XMLDesc                                                                                                                                  
    if ret is None: raise libvirtError ('virStoragePoolGetXMLDesc() failed', pool=self)                                                                                                                    
libvirt.libvirtError: Cannot write data: Broken pipe
  1. run $ vl up one more time, it finishes successfully, and doesn't mention image download stage

Rename DEBUGING.md to DEBUGGING.md

This would correct a spelling error/typo.

See #209, which I closed because I did not want to play with GPG for the sake of a trivial drive-by contribution.

testing the app locally without installing it each time

Hi,

I am trying to run the app without packaging the it each time, I managed to do it by:

python -c "from shell import main;main()" status

the issue is it looks for the app's modules in .../venv/lib/python3.10/site-packages/virt_lightning/ path, which are the old changes

is there a way to achieve this without packaging/installing the app each time ?

Can not resolve hostname while use `vl ssh`

Issue with resolving hostname

(.venv) SSH|domik:[virt-lightning] %> vl status
[host]        [username@IP]
centos7       vg@waiting -
(.venv) SSH|domik:[virt-lightning] %> vl ssh
ssh: Could not resolve hostname none: Temporary failure in name resolution
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:        18.04
Codename:       bionic

Configuration ignores the default keys

I use the following config.ini that overwrite only one key:

[main]
libvirt_uri=qemu:///syste

When I try to run vl, I get the error below:

(venv) goneri@ubuntu1804:~$ vl storage_dir
Traceback (most recent call last):
  File "/usr/lib/python3.6/configparser.py", line 789, in get
    value = d[option]
  File "/usr/lib/python3.6/collections/__init__.py", line 883, in __getitem__
    return self.__missing__(key)            # support subclasses that define __missing__
  File "/usr/lib/python3.6/collections/__init__.py", line 875, in __missing__
    raise KeyError(key)
KeyError: 'storage_pool'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/goneri/venv/bin/vl", line 11, in <module>
    load_entry_point('virt-lightning', 'console_scripts', 'vl')()
  File "/home/goneri/virt-lightning/virt_lightning/shell.py", line 301, in main
    storage_dir(configuration)
  File "/home/goneri/virt-lightning/virt_lightning/shell.py", line 212, in storage_dir
    hv.init_storage_pool(configuration.storage_pool)
  File "/home/goneri/virt-lightning/virt_lightning/configuration.py", line 87, in storage_pool
    return self.__get("storage_pool")
  File "/home/goneri/virt-lightning/virt_lightning/configuration.py", line 58, in __get
    return self.data.get("main", key)
  File "/usr/lib/python3.6/configparser.py", line 792, in get
    raise NoOptionError(option, section)
configparser.NoOptionError: No option 'storage_pool' in section: 'main'

wrong resolve.conf values when using new libvirt network

Hi,

I created new libvirt network using this file:

<network>
  <name>new-network</name>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr011' stp='on' delay='0'/>
  <ip address='192.168.152.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='192.168.152.2' end='192.168.152.254'/>
    </dhcp>
  </ip>
</network>

and I added it to virt-lightning file:

- name: tmp
  distro: centos-8
  networks:
    - network: new-network
      ipv4: 192.168.152.12
  memory: 4028
  vcpus: 4 

Then I have noticed that I can't access the internet inside the vm, after some debugging I found that my host ip is not set in /etc/resolv.conf file

; Created by cloud-init on instance boot automatically, do not edit.
;
# Generated by NetworkManager
nameserver 192.168.122.1
nameserver 192.168.123.1

moreover, when I added new-network in ~/.config/virt-lightning/config.ini as default network

[main]
network_name = new-network

it works fine.

Multiple networks and static ipv4

First, let me thank a lot everyone for this handy tool. I am currently using it to run tests deployments of a k8s cluster and it really saves me a lot of time.

In my use case I need two network interfaces to simulate a 'public' network for apps and a 'private' one for k8s APIs. I also need static ipv4s for the private side of things. My virt-lightning.yml looks like that:

- name: whatever
  distro: debian-9
  networks:
    - network: virt-lightning
    - network: private
      ipv4: 10.1.1.10
[...]

vl up fails with the error "ipv4 already set!" as a network is already defined before the private one. Removing the exit(1) in virt-lightning.py allows the vms to boot up successfully (although without dhcp by default on the private interface but that's fine since the vm has connectivity with the first network).
I can/will work on a PR with a better approach than just commenting the exit call.

CLI confusion

I'm proposing to change the CLI to have this proposed action set, which I believe will be less confusing for users:

  • start: should start or create a VM
  • stop: should stop a VM by name
  • create: should create and start a VM
  • delete: should stop and delete a VM by name
  • list: would show the list of all VMs created by VL with their power state

What do you think?

asyncio.Event loop parameter removal in Python 3.10

When attempting to run Virtual Lightning (vl) on Ubuntu 22.4 with Python 3.10.6 and vl 2.3.0, users encounter a traceback error. The error originates from the virEventRegisterAsyncIOImpl function in the libvirtaio.py file, leading to a TypeError due to the removal of the loop parameter from the asyncio.Event() constructor starting from Python 3.10.
Steps to Reproduce:
1.
Install Ubuntu 22.4 and Python 3.10.6 on the system.
2.
Install Virtual Lightning (vl) version 2.3.0 using the command: pip install vl==2.3.0.
3.
Execute any vl command, such as vl up.
Expected Behavior:
Virtual Lightning (vl) should run without any errors and perform the intended actions without issues.
Actual Behavior:
Upon running any vl command, the following traceback error is encountered:
Traceback (most recent call last):
File "/home/ali/.local/bin/vl", line 8, in
sys.exit(main())
File "/home/ali/.local/lib/python3.10/site-packages/virt_lightning/shell.py", line 382, in main
action_func(configuration=configuration, **vars(args))
File "/home/ali/.local/lib/python3.10/site-packages/virt_lightning/api.py", line 180, in up
_register_aio_virt_impl(loop)
File "/home/ali/.local/lib/python3.10/site-packages/virt_lightning/api.py", line 67, in _register_aio_virt_impl
libvirtaio.virEventRegisterAsyncIOImpl(loop=loop)
File "/usr/lib/python3/dist-packages/libvirtaio.py", line 477, in virEventRegisterAsyncIOImpl
_current_impl = virEventAsyncIOImpl(loop=loop).register()
File "/usr/lib/python3/dist-packages/libvirtaio.py", line 285, in init
self._finished = asyncio.Event(loop=loop)
File "/usr/lib/python3.10/asyncio/locks.py", line 168, in init
super().init(loop=loop)
File "/usr/lib/python3.10/asyncio/mixins.py", line 17, in init
raise TypeError(
TypeError: As of 3.10, the loop parameter was removed from Event() since it is no longer necessary
Proposed Solution:
To resolve the issue, the Virtual Lightning (vl) codebase should be updated to accommodate the changes made to the asyncio.Event() constructor in Python 3.10. The usage of the loop parameter should be removed from the libvirtaio.py file, and the code should be modified to work seamlessly with Python 3.10 and later versions.
Workaround:
As a temporary workaround, users can consider downgrading their Python version to one that is compatible with Virtual Lightning (vl) until an updated version of vl is released to address the issue. Alternatively, they can use Python 3.9.x or any version that still supports the loop parameter in the asyncio.Event() constructor.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.