add codes

This commit is contained in:
2025-11-24 15:20:05 +07:00
parent 4fcd71ca05
commit 2c96165a20
3 changed files with 83 additions and 8 deletions

View File

@@ -1,9 +1,12 @@
package storage
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// PoolConfig describes a configured storage pool.
@@ -27,7 +30,6 @@ func ResolveVolume(pools []PoolConfig, poolName, vol string) (string, error) {
if p.Name != poolName {
continue
}
// dir pool: join path/vol
if p.Type == "dir" {
if p.Path == "" {
return "", fmt.Errorf("dir pool %s missing path", poolName)
@@ -35,8 +37,13 @@ func ResolveVolume(pools []PoolConfig, poolName, vol string) (string, error) {
target := filepath.Join(p.Path, vol)
return target, nil
}
// TODO: lvm/zfs support
return "", fmt.Errorf("pool type %s not yet supported", p.Type)
if p.Type == "lvm" {
return fmt.Sprintf("/dev/%s/%s", p.VG, vol), nil
}
if p.Type == "zfs" {
return fmt.Sprintf("%s/%s", p.Path, vol), nil
}
return "", fmt.Errorf("pool type %s not supported", p.Type)
}
return "", fmt.Errorf("pool %s not found", poolName)
}
@@ -56,3 +63,40 @@ func PoolExists(pools []PoolConfig, name string) bool {
}
return false
}
// CreateVolume creates a volume in the given pool (dir or LVM). ZFS is stubbed.
func CreateVolume(pool PoolConfig, name string, sizeGB int) (string, error) {
if name == "" {
return "", errors.New("volume name required")
}
switch pool.Type {
case "dir":
if pool.Path == "" {
return "", fmt.Errorf("dir pool %s missing path", pool.Name)
}
target := filepath.Join(pool.Path, name)
if _, err := os.Stat(target); err == nil {
return target, nil
}
cmd := exec.Command("qemu-img", "create", "-f", "qcow2", target, fmt.Sprintf("%dG", sizeGB))
if err := cmd.Run(); err != nil {
return "", err
}
return target, nil
case "lvm":
if pool.VG == "" {
return "", fmt.Errorf("lvm pool %s missing vg", pool.Name)
}
target := fmt.Sprintf("/dev/%s/%s", pool.VG, name)
args := []string{"lvcreate", "-L", fmt.Sprintf("%dG", sizeGB), "-n", name, pool.VG}
if err := exec.Command("bash", "-lc", strings.Join(args, " ")).Run(); err != nil {
return "", err
}
return target, nil
case "zfs":
// Stub: in practice use `zfs create -V <size> pool/vol`
return "", fmt.Errorf("zfs volume creation not implemented")
default:
return "", fmt.Errorf("unsupported pool type %s", pool.Type)
}
}