• Stars
    star
    815
  • Rank 54,426 (Top 2 %)
  • Language
    Go
  • License
    Other
  • Created about 8 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Package libvirt provides a pure Go interface for interacting with Libvirt. Apache 2.0 Licensed.

libvirt GoDoc Build Status Report Card

Package go-libvirt provides a pure Go interface for interacting with libvirt.

Rather than using libvirt's C bindings, this package makes use of libvirt's RPC interface, as documented here. Connections to the libvirt server may be local, or remote. RPC packets are encoded using the XDR standard as defined by RFC 4506.

libvirt's RPC interface is quite extensive, and changes from one version to the next, so this project uses a pair of code generators to build the go bindings. The code generators should be run whenever you want to build go-libvirt for a new version of libvirt. See the next section for directions on re-generating go-libvirt.

Pull requests are welcome!

Feel free to join us in #go-libvirt on libera chat if you'd like to discuss the project.

Running the Code Generators

The code generator doesn't run automatically when you build go-libvirt. It's meant to be run manually any time you change the version of libvirt you're using. When you download go-libvirt it will come with generated files corresponding to a particular version of libvirt. You can use the library as-is, but the generated code may be missing libvirt functions, if you're using a newer version of libvirt, or it may have extra functions that will return 'unimplemented' errors if you try to call them. If this is a problem, you should re-run the code generator. To do this, follow these steps:

  • First, download a copy of the libvirt sources corresponding to the version you want to use.
  • Change directories into where you've unpacked your distribution of libvirt.
  • The second step depends on the version of libvirt you'd like to build against. It's not necessary to actually build libvirt, but it is necessary to run libvirt's "configure" step because it generates required files.
    • For libvirt < v6.7.0:
      • $ mkdir build; cd build
      • $ ../autogen.sh
    • For libvirt >= v6.7.0:
      • $ meson setup build
  • Finally, set the environment variable LIBVIRT_SOURCE to the directory you put libvirt into, and run go generate ./... from the go-libvirt directory. This runs both of the go-libvirt's code generators.

How to Use This Library

Once you've vendored go-libvirt into your project, you'll probably want to call some libvirt functions. There's some example code below showing how to connect to libvirt and make one such call, but once you get past the introduction you'll next want to call some other libvirt functions. How do you find them?

Start with the libvirt API reference. Let's say you want to gracefully shutdown a VM, and after reading through the libvirt docs you determine that virDomainShutdown() is the function you want to call to do that. Where's that function in go-libvirt? We transform the names slightly when building the go bindings. There's no need for a global prefix like "vir" in Go, since all our functions are inside the package namespace, so we drop it. That means the Go function for virDomainShutdown() is just DomainShutdown(), and sure enough, you can find the Go function DomainShutdown() in libvirt.gen.go, with parameters and return values equivalent to those documented in the API reference.

Suppose you then decide you need more control over your shutdown, so you switch over to virDomainShutdownFlags(). As its name suggests, this function takes a flag parameter which has possible values specified in an enum called virDomainShutdownFlagValues. Flag types like this are a little tricky for the code generator, because the C functions just take an integer type - only the libvirt documentation actually ties the flags to the enum types. In most cases though we're able to generate a wrapper function with a distinct flag type, making it easier for Go tooling to suggest possible flag values while you're working. Checking the documentation for this function:

godoc github.com/digitalocean/go-libvirt DomainShutdownFlags

returns this:

func (l *Libvirt) DomainShutdownFlags(Dom Domain, Flags DomainShutdownFlagValues) (err error)

If you want to see the possible flag values, godoc can help again:

$ godoc github.com/digitalocean/go-libvirt DomainShutdownFlagValues

type DomainShutdownFlagValues int32
    DomainShutdownFlagValues as declared in libvirt/libvirt-domain.h:1121

const (
    DomainShutdownDefault      DomainShutdownFlagValues = iota
    DomainShutdownAcpiPowerBtn DomainShutdownFlagValues = 1
    DomainShutdownGuestAgent   DomainShutdownFlagValues = 2
    DomainShutdownInitctl      DomainShutdownFlagValues = 4
    DomainShutdownSignal       DomainShutdownFlagValues = 8
    DomainShutdownParavirt     DomainShutdownFlagValues = 16
)
    DomainShutdownFlagValues enumeration from libvirt/libvirt-domain.h:1121

One other suggestion: most of the code in go-libvirt is now generated, but a few hand-written routines still exist in libvirt.go, and wrap calls to the generated code with slightly different parameters or return values. We suggest avoiding these hand-written routines and calling the generated routines in libvirt.gen.go instead. Over time these handwritten routines will be removed from go-libvirt.

Warning

While these package are reasonably well-tested and have seen some use inside of DigitalOcean, there may be subtle bugs which could cause the packages to act in unexpected ways. Use at your own risk!

In addition, the API is not considered stable at this time. If you would like to include package libvirt in a project, we highly recommend vendoring it into your project.

Example

package main

import (
	"fmt"
	"log"
	"net"
	"time"

	"github.com/digitalocean/go-libvirt"
)

func main() {
	// This dials libvirt on the local machine, but you can substitute the first
	// two parameters with "tcp", "<ip address>:<port>" to connect to libvirt on
	// a remote machine.
	c, err := net.DialTimeout("unix", "/var/run/libvirt/libvirt-sock", 2*time.Second)
	if err != nil {
		log.Fatalf("failed to dial libvirt: %v", err)
	}

	l := libvirt.New(c)
	if err := l.Connect(); err != nil {
		log.Fatalf("failed to connect: %v", err)
	}

	v, err := l.Version()
	if err != nil {
		log.Fatalf("failed to retrieve libvirt version: %v", err)
	}
	fmt.Println("Version:", v)

	domains, err := l.Domains()
	if err != nil {
		log.Fatalf("failed to retrieve domains: %v", err)
	}

	fmt.Println("ID\tName\t\tUUID")
	fmt.Printf("--------------------------------------------------------\n")
	for _, d := range domains {
		fmt.Printf("%d\t%s\t%x\n", d.ID, d.Name, d.UUID)
	}

	if err := l.Disconnect(); err != nil {
		log.Fatalf("failed to disconnect: %v", err)
	}
}
Version: 1.3.4
ID	Name		UUID
--------------------------------------------------------
1	Test-1		dc329f87d4de47198cfd2e21c6105b01
2	Test-2		dc229f87d4de47198cfd2e21c6105b01

Example (Connect to libvirt via TLS over TCP)

package main

import (
        "crypto/tls"
        "crypto/x509"

        "fmt"
        "io/ioutil"
        "log"

        "github.com/digitalocean/go-libvirt"
)

func main() {
        // This dials libvirt on the local machine
        // It connects to libvirt via TLS over TCP
        // To connect to a remote machine, you need to have the ca/cert/key of it.
        keyFileXML, err := ioutil.ReadFile("/etc/pki/libvirt/private/clientkey.pem")
        if err != nil {
                log.Fatalf("%v", err)
        }

        certFileXML, err := ioutil.ReadFile("/etc/pki/libvirt/clientcert.pem")
        if err != nil {
                log.Fatalf("%v", err)
        }

        caFileXML, err := ioutil.ReadFile("/etc/pki/CA/cacert.pem")
        if err != nil {
                log.Fatalf("%v", err)
        }
        cert, err := tls.X509KeyPair([]byte(certFileXML), []byte(keyFileXML))
        if err != nil {
                log.Fatalf("%v", err)
        }

        roots := x509.NewCertPool()
        roots.AppendCertsFromPEM([]byte(caFileXML))

        config := &tls.Config{
                Certificates: []tls.Certificate{cert},
                RootCAs:      roots,
        }

        // Use host name or IP which is valid in certificate
        addr := "10.10.10.10"
        port := "16514"
        c, err := tls.Dial("tcp", addr + ":" + port, config)
        if err != nil {
                log.Fatalf("failed to dial libvirt: %v", err)
        }

        // Drop a byte before libvirt.New(c)
        // More details at https://github.com/digitalocean/go-libvirt/issues/89
        // Remove this line if the issue does not exist any more
        c.Read(make([]byte, 1))

        l := libvirt.New(c)
        if err := l.Connect(); err != nil {
                log.Fatalf("failed to connect: %v", err)
        }

        v, err := l.Version()
        if err != nil {
                log.Fatalf("failed to retrieve libvirt version: %v", err)
        }
        fmt.Println("Version:", v)

        // Return both running and stopped VMs
        flags := libvirt.ConnectListDomainsActive | libvirt.ConnectListDomainsInactive
        domains, _, err := l.ConnectListAllDomains(1, flags)
        if err != nil {
                log.Fatalf("failed to retrieve domains: %v", err)
        }

        fmt.Println("ID\tName\t\tUUID")
        fmt.Println("--------------------------------------------------------")
        for _, d := range domains {
                fmt.Printf("%d\t%s\t%x\n", d.ID, d.Name, d.UUID)
        }

        if err := l.Disconnect(); err != nil {
                log.Fatalf("failed to disconnect: %v", err)
        }
}

Running the Integration Tests

GitHub actions workflows are defined in .github/workflows and can be triggered manually in the GitHub UI after pushing a branch. There are not currently convenient scripts for setting up and running integration tests locally, but installing libvirt and defining only the artifacts described by the files in testdata should be sufficient to be able to run the integration test file against.

More Repositories

1

nginxconfig.io

⚙️ NGINX config generator on steroids 💉
JavaScript
27,244
star
2

doctl

The official command line interface for the DigitalOcean API.
Go
3,155
star
3

godo

DigitalOcean Go API client
Go
1,328
star
4

do_user_scripts

Shell
804
star
5

Kubernetes-Starter-Kit-Developers

Hands-on tutorial and Automation stack for an operations-ready DigitalOcean Kubernetes (DOKS) cluster.
HCL
705
star
6

firebolt

Golang framework for streaming ETL, observability data pipeline, and event processing apps
Go
688
star
7

go-qemu

Go packages to interact with QEMU using the QEMU Machine Protocol (QMP). Apache 2.0 Licensed.
Go
684
star
8

do-agent

Collects system metrics from DigitalOcean Droplets
Go
586
star
9

csi-digitalocean

A Container Storage Interface (CSI) Driver for DigitalOcean Block Storage
Go
565
star
10

clusterlint

A best practices checker for Kubernetes clusters. 🤠
Go
536
star
11

vulcan

Vulcan extends Prometheus adding horizontal scalability and long-term storage
Go
531
star
12

digitalocean-cloud-controller-manager

Kubernetes cloud-controller-manager for DigitalOcean (beta)
Go
517
star
13

hacktoberfest

Hacktoberfest - App to manage the annual open-source challenge, used for the 2019 & 2020 seasons.
Ruby
510
star
14

droplet_kit

DropletKit is the official DigitalOcean API client for Ruby.
Ruby
507
star
15

terraform-provider-digitalocean

Terraform DigitalOcean provider
Go
487
star
16

action-doctl

GitHub Actions for DigitalOcean - doctl
JavaScript
454
star
17

ceph_exporter

Prometheus exporter that scrapes meta information about a ceph cluster.
Go
396
star
18

engineering-code-of-conduct

Code of Conduct for DigitalOcean's Engineering Team
289
star
19

go-openvswitch

Go packages which enable interacting with Open vSwitch and related tools. Apache 2.0 Licensed.
Go
282
star
20

kubernetes-sample-apps

Example DigitalOcean Kubernetes workload with service exposed through a DO load-balancer.
Python
252
star
21

marketplace-partners

Image validation, automation, and other tools for DigitalOcean Marketplace Vendors and Custom Image users
Shell
190
star
22

gta

gta: do transitive analysis to find packages whose dependencies have changed
Go
182
star
23

heartbot

A shot of love for your favorite chat client.
CoffeeScript
178
star
24

prometheus-client-c

A Prometheus Client in C
C
154
star
25

marketplace-kubernetes

This repository contains the source code and deployment scripts for Kubernetes-based applications listed in the DigitalOcean Marketplace.
Shell
154
star
26

go-smbios

Package smbios provides detection and access to System Management BIOS (SMBIOS) and Desktop Management Interface (DMI) data and structures. Apache 2.0 Licensed.
Go
152
star
27

kartograph

Kartograph makes it easy to generate and convert JSON. It's intention is to be used for API clients.
Ruby
147
star
28

OpenVPN-Pihole

https://marketplace.digitalocean.com/apps/openvpn-pihole
Shell
146
star
29

captainslog

A Syslog Protocol Parser
Go
136
star
30

resource_kit

Resource Kit provides tools to aid in making API Clients. Such as URL resolving, Request / Response layer, and more.
Ruby
134
star
31

go-workers2

better-go-workers
Go
121
star
32

doks-debug

A Docker image with Kubernetes manifests for investigation and troubleshooting.
Dockerfile
109
star
33

droplet-1-clicks

Packer build scripts for DigitalOcean Marketplace 1-clicks.
Shell
105
star
34

supabase-on-do

HCL
98
star
35

openapi

The OpenAPI v3 specification for DigitalOcean's public API.
JavaScript
97
star
36

container-blueprints

DigitalOcean Kubernetes(DOKS) Solution Blueprints
HCL
92
star
37

sample-dockerfile

⛵ App Platform sample Docker application.
Go
90
star
38

DOKS

Managed Kubernetes designed for simple and cost effective container orchestration.
80
star
39

app_action

Deploy to DigitalOcean Container Registry and App Platform
Go
78
star
40

navigators-guide

Book and code examples that help to build infrastructure on DigitalOcean
Shell
76
star
41

do-operator

The Kubernetes Operator for DigitalOcean
Go
76
star
42

pydo

Official DigitalOcean Python Client based on the DO OpenAPIv3 specification
Python
75
star
43

sample-django

Django sample app for DigitalOcean App Platform
Python
74
star
44

logtalez

logtalez is a minimal command line client (and API) for retrieving log streams from the rsyslog logging daemon over zeromq.
Go
73
star
45

do-markdownit

Markdown-It plugin for the DigitalOcean Community.
JavaScript
71
star
46

databases

66
star
47

sample-nodejs

⛵ App Platform sample Node.js application.
JavaScript
60
star
48

debian-sys-maint-roll-passwd

Script to update password for MySQL user "debian-sys-maint"
Shell
58
star
49

sample-nextjs

⛵ App Platform sample Next.js application.
JavaScript
57
star
50

sample-python

⛵ App Platform sample Python application.
Python
52
star
51

vmtop

Real-time monitoring of KVM/Qemu VMs
Python
52
star
52

kubecon-2022-doks-workshop

HCL
48
star
53

sample-flask

Sample Flask Application to be deployed on DigitalOcean's App Platform
HTML
45
star
54

sample-laravel

⛵ App Platform sample Laravel application.
PHP
43
star
55

pgremapper

CLI tool for manipulating Ceph's upmap exception table.
Go
43
star
56

k8s-staticroute-operator

Create static routes for your k8s nodes using CRDs.
Python
42
star
57

sample-functions-nodejs-qrcode

HTML
39
star
58

tos

DigitalOcean's Terms of Service agreement
37
star
59

sample-monorepo

Sample mono repo app (with multiple components) on the DigitalOcean App Platform.
Go
36
star
60

sample-golang

⛵ App Platform sample Golang application.
Go
36
star
61

droplet-agent

Droplet Agent is the daemon that runs on customer droplets to enable some features such as web console access.
Go
36
star
62

openvswitch_exporter

Command openvswitch_exporter implements a Prometheus exporter for Open vSwitch.
Go
32
star
63

sample-php

⛵ App Platform sample PHP application.
PHP
32
star
64

mastodon-on-kubernetes

Setting up Mastodon on DigitalOcean Kubernetes
HCL
30
star
65

sample-html

⛵ App Platform sample HTML application.
HTML
30
star
66

sample-functions-nodejs-helloworld

JavaScript
30
star
67

sample-functions-python-jokes

Python
30
star
68

flipop

Floating IP Controller for Kubernetes
Go
29
star
69

ansible-collection

DigitalOcean Ansible Collection
Python
28
star
70

sample-functions-golang-helloworld

Go
28
star
71

go-metadata

Go client for the metadata API.
Go
27
star
72

sample-react

⛵ App Platform sample React application.
JavaScript
27
star
73

marketplace-pi-hole-vpn

Pi-hole VPN image for Marketplace with Unbound & Wireguard
Shell
26
star
74

omniauth-digitalocean

DigitalOcean OAuth2 Strategy for OmniAuth
Ruby
26
star
75

github-changelog-generator

A tool to generate changelog entries from GitHub repositories.
Go
25
star
76

sample-functions-python-helloworld

Python
22
star
77

terraform-vault-github-oidc

Terraform module to configure Vault for GitHub OIDC authentication from Action runners.
HCL
22
star
78

sample-push-to-deploy-doks

Push-to-deploy example using DOCR and DOKS
Python
21
star
79

netbox-ip-controller

A Kubernetes controller to import the IP addresses and metadata of pods and services into NetBox.
Go
20
star
80

sample-expressjs

⛵ App Platform sample Express.js application.
19
star
81

terraform-provider-sendgrid

Sendgrid Terraform Provider
Go
19
star
82

sample-nuxtjs

⛵ App Platform sample Nuxt.js application.
Vue
19
star
83

sample-vuejs

⛵ App Platform sample Vue.js application.
Vue
17
star
84

production-ready-kubernetes-workshop

The repository for DigitalOcean's Production Ready Kubernetes Workshop
Python
16
star
85

sample-functions-python-twilio-sms

Sending sms via Twilio
Python
16
star
86

sample-rails

⛵ App Platform sample Ruby on Rails application.
Ruby
15
star
87

sample-functions-php-numberstowords

PHP
15
star
88

sample-functions-php-helloworld

A PHP helloworld sample function for Cloud Functions
PHP
14
star
89

sample-hugo

⛵ App Platform sample Hugo application.
14
star
90

github-pr-resource

Github pull request resource for Concourse
Go
13
star
91

sample-functions-python-sendgrid-email

Sending emails via Sendgrid API
Python
13
star
92

icingaweb2-module-netboximport

Icinga2 Director integration for Netbox
PHP
12
star
93

docker-shipit-engine

Docker image for https://github.com/Shopify/shipit-engine
Ruby
11
star
94

sample-functions-golang-presigned-url

Creating a presigned url for DO's Spaces
Go
10
star
95

digitalocean-ceph-lab

Terraform and Ansible automation to provision and configure a Ceph test environment on DigitalOcean.
HCL
10
star
96

k8s-adoption-journey

Hands-on tutorial for going from Day-1 to production on DigitalOcean Kubernetes. Goes with "Kubernetes Adoption Journey" document.
Python
9
star
97

sample-laravel-api

⛵ App Platform sample Laravel API application.
PHP
9
star
98

gnulib

A mirror of the gnulib portability and testing suite for internal builds that use it as a submodule
C
8
star
99

serverless-jamstack

Contains sample code for a serverless Jamstack tutorial published on docs.digitalocean.com
JavaScript
8
star
100

sample-gatsby

⛵ App Platform sample Gatsby application.
CSS
8
star