-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
81 lines (70 loc) · 2.18 KB
/
stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package victor
import (
"bytes"
"context"
"io"
"net/http"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/auto"
"github.com/pulumi/pulumi/sdk/v3/go/common/apitype"
)
// GetStack fetches the Pulumi stack state file from the provided url,
// and if it does not exist, create a brand new one.
func GetStack(ctx context.Context, client *Client, ws auto.Workspace, url string, verbose bool) (auto.Stack, error) {
// TODO extract the stack from the url ? or the workspace ?
stackName := "victor"
logger := Log()
// Get stack
stack, err := auto.UpsertStack(ctx, stackName, ws)
if err != nil {
return auto.Stack{}, errors.Wrapf(err, "while upserting stack %s", stackName)
}
// Get state from webserver if exist
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
res, err := client.Do(req)
if err != nil {
return auto.Stack{}, errors.Wrapf(err, "while fetching %s", url)
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
if verbose {
logger.Info("stack file not found, starting from a brand new one")
}
return stack, nil
}
if verbose {
logger.Info("loading existing stack")
}
// Load state
state, err := io.ReadAll(res.Body)
if err != nil {
return auto.Stack{}, errors.Wrapf(err, "while reading file at %s", url)
}
udep := apitype.UntypedDeployment{
Version: 3, // Pulumi v3
}
if err := udep.Deployment.UnmarshalJSON(state); err != nil {
return auto.Stack{}, errors.Wrap(err, "while unmarshalling state")
}
if err := stack.Import(ctx, udep); err != nil {
return auto.Stack{}, errors.Wrap(err, "while importing state")
}
return stack, nil
}
// PushStack sends the Pulumi stack state file to the provided url.
func PushStack(ctx context.Context, client *Client, stack auto.Stack, url string) error {
// Export state
udep, err := stack.Export(ctx)
if err != nil {
return errors.Wrap(err, "while exporting state")
}
state, _ := udep.Deployment.MarshalJSON()
// Send it to the webserver
req, _ := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewBuffer(state))
res, err := client.Do(req)
if err != nil {
return errors.Wrapf(err, "while sending state to %s", url)
}
defer res.Body.Close()
return nil
}