fix: devendor capsul code

Closes coop-cloud/organising#155.
This commit is contained in:
2021-10-20 17:25:46 +02:00
parent 7f1d9eeaec
commit 07613f5163
3 changed files with 10 additions and 51 deletions

View File

@ -1,17 +1,13 @@
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
"coopcloud.tech/abra/cli/formatter"
"coopcloud.tech/abra/cli/internal"
"coopcloud.tech/libcapsul"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
@ -182,8 +178,8 @@ environment variable or otherwise passing the "--env/-e" flag.
},
},
Action: func(c *cli.Context) error {
name := c.Args().First()
if name == "" {
capsulName := c.Args().First()
if capsulName == "" {
internal.ShowSubcommandHelpAndError(c, errors.New("no name provided"))
}
@ -191,57 +187,17 @@ environment variable or otherwise passing the "--env/-e" flag.
logrus.Fatal("Capsul API token is missing")
}
// yep, the response time is quite slow, something to fix on the Capsul side
client := &http.Client{Timeout: 20 * time.Second}
capsulCreateURL := fmt.Sprintf("https://%s/api/capsul/create", capsulInstance)
logrus.Debugf("using '%s' as capsul create url", capsulCreateURL)
values := map[string]string{
"name": name,
"size": capsulType,
"os": capsulImage,
"ssh_key_0": capsulSSHKey,
}
payload, err := json.Marshal(values)
capsulClient := libcapsul.New(capsulCreateURL, capsulAPIToken)
resp, err := capsulClient.Create(capsulName, capsulType, capsulImage, capsulSSHKey)
if err != nil {
logrus.Fatal(err)
}
req, err := http.NewRequest("POST", capsulCreateURL, bytes.NewBuffer(payload))
if err != nil {
logrus.Fatal(err)
}
req.Header = http.Header{
"Content-Type": []string{"application/json"},
"Authorization": []string{capsulAPIToken},
}
res, err := client.Do(req)
if err != nil {
logrus.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
logrus.Fatal(string(body))
}
type capsulCreateResponse struct{ ID string }
var resp capsulCreateResponse
if err := json.NewDecoder(res.Body).Decode(&resp); err != nil {
logrus.Fatal(err)
}
logrus.Debugf("capsul created with ID: '%s'", resp.ID)
tableColumns := []string{"Name", "ID"}
table := formatter.CreateTable(tableColumns)
table.Append([]string{name, resp.ID})
table.Append([]string{capsulName, resp.ID})
table.Render()
return nil