-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackit.go
More file actions
366 lines (310 loc) · 9.41 KB
/
stackit.go
File metadata and controls
366 lines (310 loc) · 9.41 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package stackit
import (
"bytes"
"context"
"embed"
"encoding/base64"
"fmt"
"text/template"
"github.com/loft-sh/log"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/iaas/wait"
"github.com/loft-sh/devpod/pkg/client"
"github.com/pkg/errors"
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/devpod-provider-stackit/pkg/options"
)
//go:embed cloud-config.yaml
var cloudConfigFS embed.FS
const (
SSHUserName = "devpod"
SSHPort = "22"
ubuntuImageID = "117e8764-41c2-405f-aece-b53aa08b28cc"
)
type Stackit struct {
client *iaas.APIClient
}
func New(options *options.ClientOptions) *Stackit {
apiClient, err := iaas.NewAPIClient(config.WithRegion(options.Region))
if err != nil {
panic(err)
}
return &Stackit{
client: apiClient,
}
}
func (s *Stackit) Init(ctx context.Context, projectID string) error {
_, err := s.client.ListServers(ctx, projectID).Execute()
if err != nil {
return err
}
return nil
}
func (s *Stackit) GetPublicIPOfServer(ctx context.Context, projectId, machineName string) (string, error) {
server, err := s.getServerByName(ctx, projectId, machineName)
if err != nil {
return "", err
}
if server == nil {
return "", errors.New("server not found")
}
if server.Nics == nil {
return "", errors.New("no networks found")
}
for _, network := range *server.Nics {
if network.PublicIp != nil {
return *network.PublicIp, nil
}
}
return "", errors.New("no public IP found")
}
func (s *Stackit) Status(ctx context.Context, projectId, machineName string) (client.Status, error) {
server, err := s.getServerByName(ctx, projectId, machineName)
if err != nil {
return client.StatusNotFound, nil
}
if server == nil {
return client.StatusNotFound, nil
}
return statusFromPowerStateString(server.GetPowerStatus()), nil
}
func (s *Stackit) Start(ctx context.Context, projectId, machineName string) error {
server, err := s.getServerByName(ctx, projectId, machineName)
if err != nil {
return err
}
err = s.client.StartServer(ctx, projectId, *server.Id).Execute()
if err != nil {
return err
}
return nil
}
func (s *Stackit) Stop(ctx context.Context, projectId, machineName string) error {
server, err := s.getServerByName(ctx, projectId, machineName)
if err != nil {
return err
}
err = s.client.StopServer(ctx, projectId, *server.Id).Execute()
if err != nil {
return err
}
return nil
}
func (s *Stackit) Delete(ctx context.Context, projectId, machineName string) error {
server, err := s.getServerByName(ctx, projectId, machineName)
if err != nil {
return fmt.Errorf("delete: %w", err)
}
gotError := false
err = s.client.DeleteServer(ctx, projectId, *server.Id).Execute()
if err != nil {
log.Default.Errorf("failed to delete server")
}
_, err = wait.DeleteServerWaitHandler(ctx, s.client, projectId, *server.Id).WaitWithContext(ctx)
if err != nil {
log.Default.Errorf("error while waiting for server deletion")
}
nics := *server.Nics
if len(nics) == 0 {
log.Default.Errorf("no networks found for server")
gotError = true
} else {
publicIPAddress := nics[0].PublicIp
if publicIPAddress != nil {
publicIP, err := s.getPublicIPByIPAddress(ctx, projectId, *publicIPAddress)
if err != nil {
log.Default.Errorf("failed to get public IP")
gotError = true
}
err = s.client.DeletePublicIP(ctx, projectId, *publicIP.Id).Execute()
if err != nil {
log.Default.Errorf("failed to delete public IP")
gotError = true
}
}
networkId := nics[0].NetworkId
err = s.client.DeleteNetwork(ctx, projectId, *networkId).Execute()
if err != nil {
log.Default.Errorf("failed to delete network")
gotError = true
}
_, err = wait.DeleteNetworkWaitHandler(ctx, s.client, projectId, *networkId).WaitWithContext(ctx)
if err != nil {
log.Default.Errorf("error while waiting for network deletion")
}
for _, id := range *nics[0].SecurityGroups {
name, err := s.getSecurityGroupNameByID(ctx, projectId, id)
if err != nil {
log.Default.Errorf("failed to get name of security group by ID")
gotError = true
}
if name != "default" {
err = s.client.DeleteSecurityGroup(ctx, projectId, id).Execute()
if err != nil {
log.Default.Errorf("failed to delete security group %q", name)
gotError = true
}
}
}
}
if gotError {
return errors.New("failed to delete all components associated to the devpod")
}
return nil
}
func statusFromPowerStateString(state string) client.Status {
switch state {
case "CRASHED":
return client.StatusStopped
case "STOPPED":
return client.StatusStopped
case "RUNNING":
return client.StatusRunning
case "ERROR":
return client.StatusStopped
}
return client.StatusNotFound
}
func (s *Stackit) Create(ctx context.Context, options *options.Options, publicKey []byte) error {
sshPublicKey := string(publicKey)
network, err := s.createNetwork(ctx, options.ProjectID, options.MachineID)
if err != nil {
return err
}
userdata, err := generateUserData(sshPublicKey)
if err != nil {
return err
}
createServerPayload := iaas.CreateServerPayload{
Name: &options.MachineID,
AvailabilityZone: &options.AvailabilityZone,
MachineType: &options.Flavor,
BootVolume: &iaas.CreateServerPayloadBootVolume{
DeleteOnTermination: utils.Ptr(true),
Size: utils.Ptr(options.DiskSize),
Source: &iaas.BootVolumeSource{
Id: utils.Ptr(ubuntuImageID),
Type: utils.Ptr("image"),
},
},
Networking: &iaas.CreateServerPayloadNetworking{
CreateServerNetworking: &iaas.CreateServerNetworking{
NetworkId: network.NetworkId,
},
},
UserData: userdata,
}
server, err := s.client.CreateServer(ctx, options.ProjectID).CreateServerPayload(createServerPayload).Execute()
if err != nil {
return err
}
server, err = wait.CreateServerWaitHandler(ctx, s.client, options.ProjectID, *server.Id).WaitWithContext(ctx)
if err != nil {
return err
}
publicIP, err := s.client.CreatePublicIP(ctx, options.ProjectID).CreatePublicIPPayload(iaas.CreatePublicIPPayload{}).Execute()
if err != nil {
return err
}
err = s.client.AddPublicIpToServer(ctx, options.ProjectID, *server.Id, *publicIP.Id).Execute()
if err != nil {
return err
}
createSecurityGroupPayload := iaas.CreateSecurityGroupPayload{
Name: &options.MachineID,
}
securityGroup, err := s.client.CreateSecurityGroup(ctx, options.ProjectID).CreateSecurityGroupPayload(createSecurityGroupPayload).Execute()
if err != nil {
return err
}
createSecurityGroupRulePayload := iaas.CreateSecurityGroupRulePayload{
Description: utils.Ptr("SSH"),
Direction: utils.Ptr("ingress"),
PortRange: &iaas.PortRange{
Min: utils.Ptr(int64(22)),
Max: utils.Ptr(int64(22)),
},
Protocol: &iaas.CreateProtocol{
String: utils.Ptr("tcp"),
},
}
securityGroupRule, err := s.client.CreateSecurityGroupRule(ctx, options.ProjectID, *securityGroup.Id).CreateSecurityGroupRulePayload(createSecurityGroupRulePayload).Execute()
if err != nil {
return err
}
fmt.Println(*securityGroupRule)
err = s.client.AddSecurityGroupToServer(ctx, options.ProjectID, *server.Id, *securityGroup.Id).Execute()
if err != nil {
return err
}
return nil
}
func generateUserData(publicKey string) (*[]byte, error) {
t, err := template.New("cloud-config.yaml").ParseFS(cloudConfigFS, "cloud-config.yaml")
if err != nil {
return nil, err
}
output := new(bytes.Buffer)
if err := t.Execute(output, map[string]string{
"PublicKey": publicKey,
"Username": SSHUserName,
}); err != nil {
return nil, err
}
encodedUserData := base64.StdEncoding.EncodeToString(output.Bytes())
byteArray := []byte(encodedUserData)
return &byteArray, nil
}
func (s *Stackit) createVolume(ctx context.Context, projectId, volumeName, volumeAvailabilityZone string, volumeSize int64) (string, error) {
createVolumePayload := iaas.CreateVolumePayload{
Name: &volumeName,
AvailabilityZone: &volumeAvailabilityZone,
Size: &volumeSize,
}
volume, err := s.client.CreateVolume(ctx, projectId).CreateVolumePayload(createVolumePayload).Execute()
if err != nil {
return "", err
}
return *volume.Id, nil
}
func (s *Stackit) getServerByName(ctx context.Context, projectId, serverName string) (*iaas.Server, error) {
servers, err := s.client.ListServers(ctx, projectId).Details(true).Execute()
if err != nil {
return nil, err
}
if servers == nil {
return nil, errors.New("server not found")
}
if servers.Items == nil {
return nil, errors.New("servers not found")
}
for _, server := range *servers.Items {
if *server.Name == serverName {
return &server, nil
}
}
return nil, errors.New("server not found")
}
func (s *Stackit) getPublicIPByIPAddress(ctx context.Context, projectId, ipAddress string) (*iaas.PublicIp, error) {
publicIPs, err := s.client.ListPublicIPs(ctx, projectId).Execute()
if err != nil {
return nil, err
}
if len(*publicIPs.Items) == 0 {
return nil, errors.New("no public IPs found")
}
for _, publicIP := range *publicIPs.Items {
if *publicIP.Ip == ipAddress {
return &publicIP, nil
}
}
return nil, errors.New("public IP not found")
}
func (s *Stackit) getSecurityGroupNameByID(ctx context.Context, projectId, securityGroupId string) (string, error) {
securityGroup, err := s.client.GetSecurityGroup(ctx, projectId, securityGroupId).Execute()
if err != nil {
return "", errors.New("security group not found")
}
return *securityGroup.Name, nil
}