blksnap

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 11, 2026 License: MIT Imports: 11 Imported by: 0

README

go-blksnap — Pure Go Block Device Snapshot Library

Go Reference Go Version License

Pure Go ioctl-based client for the veeamblksnap standalone kernel module. Supports both API generations (VAL-6.x and VAL-13.x) with automatic version detection. No cgo, no C bindings.

Important: This library auto-detects the loaded kernel module version:

  • v2 (VAL-13.0 / VAL-13.0.1): /dev/veeamblksnap + /dev/bdevfilter
  • v1 (VAL-6.0 through VAL-6.3.2): /dev/veeamblksnap only

Features

  • Multi-version: Auto-detects v1 (VAL-6.x) or v2 (VAL-13.x) API
  • Snapshot lifecycle: Create, Take, Destroy, Collect via /dev/veeamblksnap
  • Change Block Tracking: Attach filter, read CBT bitmap, mark dirty blocks
  • Snapshot events: Wait for corrupted / low-free-space events with timeout
  • Session management: goroutine-based event monitor, automatic cleanup
  • Zero cgo: Only depends on golang.org/x/sys/unix

Requirements

  • Linux (amd64 or arm64)
  • Go 1.26+
  • veeamblksnap kernel module loaded (and bdevfilter for v2)
  • Root privileges (or CAP_SYS_ADMIN) for most operations

Kernel module installation

The veeamblksnap module must be installed and loaded before this library can be used. There are two ways to obtain it, depending on your distribution.

Veeam distributes pre-built blksnap packages through the Veeam software repository as part of Veeam Agent for Linux (free community edition available).

Add the repository
  1. Download the veeam-release package from the Veeam Agent for Linux download page (requires a free veeam.com account).

  2. Install the repository package:

    # Debian / Ubuntu
    sudo dpkg -i ./veeam-release* && sudo apt-get update
    
    # RHEL / Rocky / Alma
    sudo rpm -ivh ./veeam-release* && sudo dnf check-update
    
    # SLES / openSUSE
    sudo zypper in ./veeam-release* && sudo zypper refresh
    

Alternative: If you can't use the release package, add the key manually:

# Debian/Ubuntu
sudo curl -fsSL https://repository.veeam.com/keys/DEB-9BB5AC67.gpg \
  -o /usr/share/keyrings/veeam.gpg
echo "deb [signed-by=/usr/share/keyrings/veeam.gpg] https://repository.veeam.com/backup/linux/agent/dpkg/debian/public stable veeam" | \
  sudo tee /etc/apt/sources.list.d/veeam.list
sudo apt-get update
# RHEL/Rocky/Alma
sudo rpm --import https://repository.veeam.com/keys/RPM-EFDCEA77
Install the module
# Debian 11–13 / Ubuntu 22.04 / 24.04
sudo apt-get install blksnap

# RHEL 9 / Rocky 9 / Alma 9 — pre-built kmod
sudo dnf install kmod-blksnap

# RHEL 9 / Rocky 9 / Alma 9 — DKMS (builds from source for your kernel)
sudo dnf install epel-release dkms
sudo dnf install blksnap

# RHEL 8 / Rocky 8 / Alma 8 — pre-built kmod (veeamsnap)
sudo dnf install kmod-veeamsnap

# SLES 15 SP3–SP7 / SLES 16
sudo zypper install blksnap-kmp-default
Verify
lsmod | grep -E 'veeamblksnap|bdevfilter'
sudo modprobe veeamblksnap     # if not auto-loaded
sudo modprobe bdevfilter       # v2 only
ls -la /dev/veeamblksnap /dev/bdevfilter
Secure Boot

If Secure Boot is enabled, enroll the Veeam key:

sudo mokutil --import /path/to/blksnap.der
# Reboot and follow the MOK Manager prompt
Option 2: Build from source

For development or if pre-built packages don't support your kernel:

git clone https://github.com/veeam/blksnap.git -b VAL-13.0.1
cd blksnap/module
make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
sudo mkdir -p /lib/modules/$(uname -r)/extra
sudo install -m 0644 veeamblksnap.ko bdevfilter.ko /lib/modules/$(uname -r)/extra/
sudo depmod -a
sudo modprobe veeamblksnap bdevfilter

Note: Ensure linux-headers-$(uname -r) is installed. For kernel ≥ 6.17, use the VAL-13.0.1 branch.

Troubleshooting
Symptom Cause Solution
modprobe: FATAL: Module veeamblksnap not found Not installed Install package or build from source
DKMS build fails (kernel ≥ 6.17) Package too old Build from VAL-13.0.1 source
Failed to load module Kernel/headers mismatch kernel-devel/linux-headers must match uname -r
Secure Boot blocks module Unsigned Enroll key via mokutil or disable Secure Boot

Installation

go get github.com/pbs-plus/go-blksnap@latest

Quick start

package main

import (
	"log"

	"github.com/pbs-plus/go-blksnap"
)

func main() {
	session, err := blksnap.CreateSession(
		[]string{"/dev/sda1", "/dev/sda2"},
		"/var/lib/blksnap/diff_storage",
		1024*1024*1024, // 1 GB diff storage limit
	)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	cbt, _ := session.CBTHandle("/dev/sda1")
	info, _ := cbt.Info()
	log.Printf("device=%d blocks, block_size=%d", info.BlockCount, info.BlockSize)

	data, _ := cbt.Data()
	log.Printf("CBT map: %d bytes", len(data))

	img, _ := cbt.Image()
	log.Printf("snapshot image: %s", img)

	if errs, ok := session.Errors(); ok {
		for _, e := range errs {
			log.Printf("snapshot error: %s", e)
		}
	}
}

Architecture

The library auto-detects the API version on first use:

v, _ := blksnap.Detect() // returns APIV1 or APIV2

Two kernel interfaces are used depending on the version:

Interface API Go types Purpose
/dev/veeamblksnap v1 + v2 Service, Snapshot Snapshot lifecycle
/dev/bdevfilter v2 only Tracker CBT via path-based device IDs
/dev/veeamblksnap v1 only Tracker CBT via major:minor device IDs
Low-level API
// Version query (works on both v1 and v2)
svc, _ := blksnap.OpenService()
ver, _ := svc.Version()
fmt.Println(ver) // "7.0.0.0"

// List active snapshots
ids, _ := svc.Collect()

// CBT on v2 (path-based)
t, _ := blksnap.OpenTracker("/dev/sda1")
t.Attach()
info, _ := t.CBTInfo()
buf := make([]byte, info.BlockCount)
t.ReadCBTMap(0, info.BlockCount, buf)
t.Detach()
t.Close()

// Create and take a snapshot (v2)
snap, _ := blksnap.CreateSnapshot("/tmp/diff_storage", 1<<30)
t.SnapshotAdd(snap.ID())
snap.Take()

// Wait for events
for {
    ev, ok, _ := snap.WaitEvent(100)
    if !ok { continue }
    switch ev.Code {
    case blksnap.EventCorrupted:
        log.Printf("corrupted: dev=%d:%d code=%d",
            ev.Corrupted.OrigDevIDMajor,
            ev.Corrupted.OrigDevIDMinor,
            ev.Corrupted.ErrorCode)
    case blksnap.EventLowFreeSpace:
        log.Printf("low space: requested=%d sectors",
            ev.NoSpace.RequestedSectors)
    }
}

snap.Destroy()
snap.Close()
v1-specific API

In v1, devices are identified by major:minor numbers and added at snapshot creation time:

snap, _, _ := blksnap.CreateSnapshotV1([]blksnap.DevID{
    {Major: 8, Minor: 1},  // /dev/sda1
    {Major: 8, Minor: 2},  // /dev/sda2
})

// Get image device mappings
images, _ := snap.CollectImages()
for orig, img := range images {
    fmt.Printf("%d:%d → %d:%d\n", orig.Major, orig.Minor, img.Major, img.Minor)
}
High-level Session API
session, _ := blksnap.CreateSession(
    []string{"/dev/sda1"},
    "/tmp/diff_storage",
    1<<30,
    blksnap.WithLogger(slog.Default()),
    blksnap.WithEventTimeout(50*time.Millisecond),
)
defer session.Close()

Type reference

C struct (v2) Go type
struct blksnap_version ModuleVersion
struct blksnap_uuid UUID
struct blksnap_cbtinfo CBTInfo
struct blksnap_sectors SectorRange
struct blksnap_snapshotinfo SnapshotImageInfo
struct blksnap_snapshot_event SnapshotEvent
struct blksnap_event_corrupted SnapshotEventCorrupted
struct blksnap_event_no_space SnapshotEventLowFreeSpace
enum blksnap_event_codes SnapshotEventCode
struct blk_snap_dev_t (v1) DevID
enum blk_snap_ioctl (v1) (internal)
struct bdevfilter_attach/ctl (v2) (internal)

License

MIT — see LICENSE.


Based on the blksnap kernel module UAPI by Veeam Software Group GmbH. The ioctl protocol derives from kernel UAPI headers (veeamblksnap.h, bdevfilter.h, blk_snap.h) which are licensed under GPL-2.0 WITH Linux-syscall-note, permitting independent userspace implementations under any license.

Documentation

Overview

Package blksnap provides a pure Go interface to the veeamblksnap kernel module for block device snapshot management.

It auto-detects the loaded module version and supports both API generations:

  • v2 (VAL-13.x): Uses /dev/veeamblksnap + /dev/bdevfilter with path-based device identification. The ioctl protocol aligns with the VAL-13.0/13.0.1 standalone branches.

  • v1 (VAL-6.x): Uses /dev/veeamblksnap only with major:minor device identification. The ioctl protocol aligns with the VAL-6.x standalone branches.

Auto-detection

The first call to OpenService or OpenTracker probes the system and locks in the API version. No explicit version selection is needed.

Requirements

The veeamblksnap (and for v2, bdevfilter) kernel modules must be loaded. This package targets Linux only (linux/amd64, linux/arm64).

Index

Examples

Constants

View Source
const (
	V1ImagePrefix = "veeamblksnapimg" // VAL-6.x
	V2ImagePrefix = "vbsnap"          // VAL-13.x
)

Image prefixes used by the kernel module for snapshot image device names.

View Source
const ControlDevice = "/dev/veeamblksnap"

ControlDevice returns the control device path for snapshot management.

View Source
const FilterDevice = "/dev/bdevfilter"

FilterDevice is the bdevfilter path (v2 only).

Variables

View Source
var (
	ErrNotFound      = errors.New("blksnap: not found")
	ErrAlreadyExists = errors.New("blksnap: already exists")
	ErrInterrupted   = errors.New("blksnap: interrupted")
	ErrNoData        = errors.New("blksnap: no data available")
	ErrNoSpace       = errors.New("blksnap: no space left on device")
	ErrCorrupted     = errors.New("blksnap: snapshot corrupted")
)

Functions

func CreateSnapshotV1

func CreateSnapshotV1(devices []DevID) (*Snapshot, UUID, error)

CreateSnapshotV1 creates a snapshot with the given device IDs (v1 API). The devices are added to the snapshot at creation time.

Types

type APIVersion

type APIVersion int

APIVersion identifies the kernel module API generation.

const (
	// APIV1 is the VAL-6.x API. All operations use /dev/veeamblksnap only,
	// devices are identified by major:minor numbers, and the snapshot create
	// ioctl takes a device array directly.
	APIV1 APIVersion = 1

	// APIV2 is the VAL-13.x API. Snapshot control uses /dev/veeamblksnap,
	// block device filter operations use /dev/bdevfilter, and devices are
	// identified by filesystem path.
	APIV2 APIVersion = 2
)

func Detect

func Detect() (APIVersion, error)

Detect probes the system to determine which API version the loaded kernel module supports. It opens the control device and checks whether /dev/bdevfilter exists (v2) or not (v1). The result is cached.

func Detected

func Detected() APIVersion

Detected returns the detected API version. It calls Detect internally.

type CBTHandle

type CBTHandle struct {
	// contains filtered or unexported fields
}

CBTHandle provides a high-level interface to Change Block Tracking on a block device that has the blksnap filter attached (v2) or is tracked (v1).

func NewCBT

func NewCBT(devicePath string) (*CBTHandle, error)

NewCBT creates a CBT handle for the given block device.

func (*CBTHandle) Close

func (c *CBTHandle) Close() error

func (*CBTHandle) Data

func (c *CBTHandle) Data() ([]byte, error)

Data reads the full CBT bitmap.

func (*CBTHandle) DataChunked

func (c *CBTHandle) DataChunked(chunkSize uint32, fn func(offset uint32, data []byte) error) error

DataChunked reads the full CBT bitmap in chunks.

func (*CBTHandle) ErrorCode

func (c *CBTHandle) ErrorCode() (int32, error)

ErrorCode returns the snapshot error code (v2 only).

func (*CBTHandle) Image

func (c *CBTHandle) Image() (string, error)

Image returns the block device name of the snapshot image (v2 only).

func (*CBTHandle) Info

func (c *CBTHandle) Info() (CBTInfo, error)

type CBTInfo

type CBTInfo struct {
	DeviceCapacity uint64
	BlockSize      uint32
	BlockCount     uint32
	GenerationID   UUID
	ChangesNumber  uint8
}

CBTInfo holds change block tracking metadata for a block device.

type DevID

type DevID struct {
	Major uint32
	Minor uint32
}

DevID identifies a block device by major:minor (used in v1 API).

type ModuleVersion

type ModuleVersion struct {
	Major    uint16
	Minor    uint16
	Revision uint16
	Build    uint16
}

ModuleVersion represents the kernel module version.

Example
package main

import (
	"fmt"

	"github.com/pbs-plus/go-blksnap"
)

func main() {
	v := blksnap.ModuleVersion{Major: 1, Minor: 2, Revision: 3, Build: 4}
	fmt.Println(v.String())
}
Output:
1.2.3.4

func (ModuleVersion) String

func (v ModuleVersion) String() string

type SectorRange

type SectorRange struct {
	Offset uint64
	Count  uint64
}

SectorRange describes a region on a block device in sectors.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service provides low-level access to the blksnap control device.

func OpenService

func OpenService() (*Service, error)

OpenService opens a connection to the control device and auto-detects the API version.

func (*Service) Close

func (s *Service) Close() error

func (*Service) Collect

func (s *Service) Collect() ([]UUID, error)

Collect returns the UUIDs of all active snapshots.

func (*Service) FD

func (s *Service) FD() uintptr

FD returns the control device file descriptor.

func (*Service) Version

func (s *Service) Version() (ModuleVersion, error)

Version returns the kernel module version.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session manages a blksnap snapshot session across one or more block devices.

func CreateSession

func CreateSession(devices []string, diffStoragePath string, limitBytes uint64, opts ...SessionOption) (*Session, error)

CreateSession creates a new blksnap session.

For v2 (VAL-13.x): attaches bdevfilter, creates snapshot with diff storage, adds devices, starts event monitoring, takes snapshot.

For v1 (VAL-6.x): creates snapshot with device IDs, appends diff storage via low_free_space events, starts event monitoring, takes snapshot.

func (*Session) CBTHandle

func (s *Session) CBTHandle(devicePath string) (*CBTHandle, error)

func (*Session) Close

func (s *Session) Close() error

func (*Session) Errors

func (s *Session) Errors() ([]string, bool)

func (*Session) ID

func (s *Session) ID() UUID

type SessionOption

type SessionOption func(*sessionConfig)

func WithEventTimeout

func WithEventTimeout(d time.Duration) SessionOption

func WithLogger

func WithLogger(logger *slog.Logger) SessionOption

type Snapshot

type Snapshot struct {
	// contains filtered or unexported fields
}

Snapshot manages a single blksnap snapshot.

func CreateSnapshot

func CreateSnapshot(diffStorageFile string, limitBytes uint64) (*Snapshot, error)

CreateSnapshot creates a new snapshot with a difference storage file and limit. v2 only — v1 creates snapshots differently (via CreateSnapshotV1).

func OpenSnapshot

func OpenSnapshot(id UUID) (*Snapshot, error)

OpenSnapshot opens an existing snapshot by UUID.

func (*Snapshot) Close

func (s *Snapshot) Close() error

func (*Snapshot) CollectImages

func (s *Snapshot) CollectImages() (map[DevID]DevID, error)

CollectImages returns the snapshot image info for all devices in the snapshot (v1 only).

func (*Snapshot) Destroy

func (s *Snapshot) Destroy() error

Destroy releases and destroys the snapshot.

func (*Snapshot) ID

func (s *Snapshot) ID() UUID

func (*Snapshot) Take

func (s *Snapshot) Take() error

Take takes the snapshot.

func (*Snapshot) WaitEvent

func (s *Snapshot) WaitEvent(timeoutMs uint32) (SnapshotEvent, bool, error)

WaitEvent waits for an event from the held snapshot.

type SnapshotEvent

type SnapshotEvent struct {
	Code      SnapshotEventCode
	TimeLabel int64
	Corrupted *SnapshotEventCorrupted
	NoSpace   *SnapshotEventLowFreeSpace
}

SnapshotEvent represents an event received from a held snapshot.

type SnapshotEventCode

type SnapshotEventCode int

SnapshotEventCode identifies the type of snapshot event.

const (
	// EventCorrupted — snapshot image corrupted.
	// v1 kernel code 1, v2 kernel code 0.
	EventCorrupted SnapshotEventCode = 0
	// EventLowFreeSpace — difference storage limit reached (v1) or no space (v2).
	// v1 kernel code 0, v2 kernel code 1.
	EventLowFreeSpace SnapshotEventCode = 1
)

type SnapshotEventCorrupted

type SnapshotEventCorrupted struct {
	OrigDevIDMajor uint32
	OrigDevIDMinor uint32
	ErrorCode      int32
}

SnapshotEventCorrupted provides details for EventCorrupted.

type SnapshotEventLowFreeSpace

type SnapshotEventLowFreeSpace struct {
	RequestedSectors uint64
}

SnapshotEventLowFreeSpace provides details when the diff storage is full.

type SnapshotImageInfo

type SnapshotImageInfo struct {
	ErrorCode int32
	Image     string
}

SnapshotImageInfo describes the snapshot image for a device (v2 only).

type Tracker

type Tracker struct {
	// contains filtered or unexported fields
}

Tracker manages CBT and snapshot participation for a single block device.

func OpenTracker

func OpenTracker(devicePath string) (*Tracker, error)

OpenTracker opens the appropriate device for the detected API version. devicePath is the block device path (e.g., /dev/sda1) — used for v2 directly, stat'd for major:minor in v1.

func (*Tracker) Attach

func (t *Tracker) Attach() (bool, error)

func (*Tracker) CBTInfo

func (t *Tracker) CBTInfo() (CBTInfo, error)

func (*Tracker) Close

func (t *Tracker) Close() error

func (*Tracker) Detach

func (t *Tracker) Detach() error

func (*Tracker) MarkDirty

func (t *Tracker) MarkDirty(ranges []SectorRange) error

func (*Tracker) ReadCBTMap

func (t *Tracker) ReadCBTMap(offset, length uint32, dst []byte) error

func (*Tracker) SnapshotAdd

func (t *Tracker) SnapshotAdd(id UUID) error

SnapshotAdd adds the device to a snapshot. v2 only — v1 adds at create time.

func (*Tracker) SnapshotInfo

func (t *Tracker) SnapshotInfo() (SnapshotImageInfo, error)

SnapshotInfo retrieves snapshot image information (v2 only).

func (*Tracker) V1DevID

func (t *Tracker) V1DevID() DevID

V1DevID returns the device major:minor (v1 only, zero value otherwise).

type UUID

type UUID [16]byte

UUID is a 16-byte unique identifier used by blksnap for snapshots.

Example
package main

import (
	"fmt"

	"github.com/pbs-plus/go-blksnap"
)

func main() {
	id, err := blksnap.ParseUUID("550e8400-e29b-41d4-a716-446655440000")
	if err != nil {
		panic(err)
	}
	fmt.Println(id.String())
}
Output:
550e8400-e29b-41d4-a716-446655440000

func MustParseUUID

func MustParseUUID(s string) UUID
Example
package main

import (
	"fmt"

	"github.com/pbs-plus/go-blksnap"
)

func main() {
	id := blksnap.MustParseUUID("550e8400-e29b-41d4-a716-446655440000")
	fmt.Println(id.IsZero())
}
Output:
false

func ParseUUID

func ParseUUID(s string) (UUID, error)

func (UUID) IsZero

func (u UUID) IsZero() bool

func (UUID) String

func (u UUID) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL