86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
|
package libcapsul
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"io/ioutil"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
// CapsulCreateResponse is a Capsul creation response payload.
|
||
|
type CapsulCreateResponse struct {
|
||
|
ID string
|
||
|
}
|
||
|
|
||
|
// CapsulClient is a Capsul client interface.
|
||
|
type CapsulClient struct {
|
||
|
InstanceURL string
|
||
|
APIToken string
|
||
|
}
|
||
|
|
||
|
// New creates a new Capsul client.
|
||
|
func New(instanceURL, APIToken string) CapsulClient {
|
||
|
return CapsulClient{
|
||
|
InstanceURL: instanceURL,
|
||
|
APIToken: APIToken,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Create creates a new capsul.
|
||
|
func (c CapsulClient) Create(capsulName, capsulType, capsulImage, capsulSSHKey string) (CapsulCreateResponse, error) {
|
||
|
// 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", c.InstanceURL)
|
||
|
logrus.Debugf("using '%s' as capsul create url", capsulCreateURL)
|
||
|
|
||
|
values := map[string]string{
|
||
|
"name": capsulName,
|
||
|
"size": capsulType,
|
||
|
"os": capsulImage,
|
||
|
"ssh_key_0": capsulSSHKey,
|
||
|
}
|
||
|
|
||
|
payload, err := json.Marshal(values)
|
||
|
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{c.APIToken},
|
||
|
}
|
||
|
|
||
|
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))
|
||
|
}
|
||
|
|
||
|
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)
|
||
|
|
||
|
return resp, nil
|
||
|
}
|