-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcp-instance.go
91 lines (75 loc) · 2.13 KB
/
gcp-instance.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
82
83
84
85
86
87
88
89
90
package helper
import (
"context"
"github.com/andypangaribuan/gcp-instance-scheduler/model"
"github.com/pkg/errors"
"google.golang.org/api/compute/v1"
"google.golang.org/api/option"
sqladmin "google.golang.org/api/sqladmin/v1beta4"
)
/* ============================================
Created by andy pangaribuan on 2021/05/20
Copyright andypangaribuan. All rights reserved.
============================================ */
func StartStopGCE(isStart bool, config model.SchedulerConfigModel) error {
ctx := context.Background()
service, err := compute.NewService(ctx, option.WithCredentialsFile(config.ServiceAccountPath))
if err != nil {
return errors.WithStack(err)
}
instance, err := service.Instances.Get(config.ProjectId, config.Zone, config.Instance).Do()
if err != nil {
return errors.WithStack(err)
}
if instance.Status == "RUNNING" && isStart {
return nil
}
if instance.Status == "TERMINATED" && !isStart {
return nil
}
if isStart {
_, err := service.Instances.Start(config.ProjectId, config.Zone, config.Instance).Do()
if err != nil {
return errors.WithStack(err)
}
} else {
_, err := service.Instances.Stop(config.ProjectId, config.Zone, config.Instance).Do()
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func StartStopCloudSQL(isStart bool, config model.SchedulerConfigModel) error {
ctx := context.Background()
service, err := sqladmin.NewService(ctx, option.WithCredentialsFile(config.ServiceAccountPath))
if err != nil {
return errors.WithStack(err)
}
instance, err := service.Instances.Get(config.ProjectId, config.Instance).Do()
if err != nil {
return errors.WithStack(err)
}
if instance.Settings.ActivationPolicy == "ALWAYS" && isStart {
return nil
}
if instance.Settings.ActivationPolicy == "NEVER" && !isStart {
return nil
}
action := ""
if isStart {
action = "ALWAYS"
} else {
action = "NEVER"
}
setting := &sqladmin.DatabaseInstance{
Settings: &sqladmin.Settings{
ActivationPolicy: action,
},
}
_, err = service.Instances.Patch(config.ProjectId, config.Instance, setting).Do()
if err != nil {
return errors.WithStack(err)
}
return nil
}