virtigoctl/create.go

95 lines
2.2 KiB
Go
Raw Permalink Normal View History

// Copyright 2024 WIT.COM Inc Licensed GPL 3.0
package main
import (
"errors"
"fmt"
"path/filepath"
"strings"
pb "go.wit.com/lib/protobuf/virtbuf"
"go.wit.com/log"
"google.golang.org/protobuf/proto"
)
func createFilename(dir string, filename string) error {
log.Info("dir ==", dir)
log.Info("filename ==", filename)
filetype := filepath.Ext(filename)
if filetype != ".qcow2" {
log.Info("file type", filetype, "not supported")
return errors.New("only supporting qcow2 images for now")
}
hostname := strings.TrimSuffix(filename, filetype)
log.Info("hostname ==", hostname)
newDroplet := pb.NewDefaultDroplet(hostname)
newDisk := new(pb.Disk)
newDisk.Filename = filename
newDisk.Filepath = dir
newDroplet.Disks = append(newDroplet.Disks, newDisk)
var eth *pb.Network
eth = new(pb.Network)
eth.Name = "worldbr"
newDroplet.Networks = append(newDroplet.Networks, eth)
url := urlbase + "/create"
// body, err := postDropletJSON(url, newDroplet)
// if err != nil {
// log.Info("postDropletJSON() failed:", err)
// return err
// }
body, err := postDropletWIRE(url, newDroplet)
if err != nil {
log.Info("postDropletJSON() failed:", err)
return err
}
test := strings.TrimSpace(string(body))
// log.Info("virtigo returned body:", test)
for _, line := range strings.Split(test, "\n") {
log.Info("GOT:", line)
}
return nil
}
// send protobuf as wire data
func postDropletWIRE(url string, d *pb.Droplet) (string, error) {
var bytes []byte
var err error
// Automatically marshal to protobuf binary format
bytes, err = proto.Marshal(d)
if err != nil {
log.Fatalf("Failed to marshal: %v", err)
return "", err
}
// fmt.Printf("Encoded data: %x\n", bytes)
fmt.Printf("Encoded len(data): %d\n", len(bytes))
return post(url, bytes)
}
// send protobuf in json format
func postDropletJSON(url string, d *pb.Droplet) (string, error) {
// send protobuf as JSON
bytes, err := d.MarshalJSON()
if err != nil {
log.Info("virtbuf.MarshalJson() failed:", err)
return "", err
}
return post(url, bytes)
}
func post(url string, bytes []byte) (string, error) {
body, err := httpPost(url, bytes)
if err != nil {
log.Info("httpPost() failed:", err)
return "", err
}
return string(body), nil
}