-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
179 lines (156 loc) · 4.91 KB
/
main.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
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
package main
import (
"context"
"flag"
"fmt"
"log"
"strings"
"time"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/core"
"github.com/oracle/oci-go-sdk/v65/example/helpers"
"github.com/oracle/oci-go-sdk/v65/identity"
)
func main() {
var t int
flag.IntVar(&t, "t", 0, "Number of minutes between retries")
flag.Parse()
if t == 0 {
run()
return
}
log.Printf("Starting script with %v minutes delay.", t)
for true {
run()
time.Sleep(time.Duration(t) * time.Minute)
}
}
func run() {
cfg, err := loadConfig()
if err != nil {
log.Fatal(err)
}
cfg.validate()
if err != nil {
log.Fatal(err)
}
cp, err := cfg.buildConfigProvider()
if err != nil {
log.Fatal(err)
}
coreClient, err := core.NewComputeClientWithConfigurationProvider(cp)
if err != nil {
log.Fatal(err)
}
identityClient, err := identity.NewIdentityClientWithConfigurationProvider(cp)
if err != nil {
log.Fatal(err)
}
if len(cfg.AvailabilityDomains) == 0 {
cfg.AvailabilityDomains, err = ListAvailabilityDomains(identityClient, cfg.TenancyID)
if err != nil {
log.Fatal(err)
}
}
instances := ListInstances(coreClient, cfg.TenancyID)
existingInstances := checkExistingInstances(cfg, instances)
if existingInstances != "" {
log.Println(existingInstances)
return
}
for _, domain := range cfg.AvailabilityDomains {
log.Println("Trying domain: ", domain)
resp, err := createInstance(coreClient, cfg, domain)
if err == nil {
handleSuccess()
return
}
if !strings.Contains(err.Error(), "Out of host capacity") {
log.Println("Something went wrong: ", resp.HTTPResponse().Status)
return
}
log.Println("Domain out of capacity: ", domain)
}
}
func ListAvailabilityDomains(client identity.IdentityClient, compartmentId string) ([]string, error) {
req := identity.ListAvailabilityDomainsRequest{CompartmentId: common.String(compartmentId)}
resp, err := client.ListAvailabilityDomains(context.Background(), req)
helpers.FatalIfError(err)
var domainNames []string
for _, item := range resp.Items {
domainNames = append(domainNames, *item.Name)
}
return domainNames, nil
}
func ListInstances(client core.ComputeClient, compartmentId string) []core.Instance {
req := core.ListInstancesRequest{Page: common.String(""),
Limit: common.Int(78),
SortBy: core.ListInstancesSortByTimecreated,
SortOrder: core.ListInstancesSortOrderAsc,
CompartmentId: common.String(compartmentId)}
// Send the request using the service client
resp, err := client.ListInstances(context.Background(), req)
helpers.FatalIfError(err)
// Retrieve value from the response.
return resp.Items
}
func checkExistingInstances(cfg config, instances []core.Instance) string {
shape := cfg.Shape
maxInstances := cfg.MaxInstances
var displayNames []string
var states []core.InstanceLifecycleStateEnum
for _, instance := range instances {
if *instance.Shape == shape && instance.LifecycleState != core.InstanceLifecycleStateTerminated {
displayNames = append(displayNames, *instance.DisplayName)
states = append(states, instance.LifecycleState)
}
}
if len(displayNames) < maxInstances {
return ""
}
msg := fmt.Sprintf("Already have an instance(s) %v in state(s) (respectively) %v. User: %v\n", displayNames, states, cfg.UserID)
return msg
}
func createInstance(client core.ComputeClient, cfg config, domain string) (core.LaunchInstanceResponse, error) {
req := core.LaunchInstanceRequest{
LaunchInstanceDetails: core.LaunchInstanceDetails{
Metadata: map[string]string{"ssh_authorized_keys": cfg.SSHPublicKey},
Shape: &cfg.Shape,
CompartmentId: &cfg.TenancyID,
DisplayName: common.String("instance-" + time.Now().Format("20060102-1504")),
AvailabilityDomain: &domain,
SourceDetails: buildSourceDetails(cfg),
CreateVnicDetails: &core.CreateVnicDetails{
AssignPublicIp: common.Bool(false),
SubnetId: &cfg.SubnetID,
AssignPrivateDnsRecord: common.Bool(true),
},
AgentConfig: &core.LaunchInstanceAgentConfigDetails{
PluginsConfig: []core.InstanceAgentPluginConfigDetails{
{
Name: common.String("Compute Instance Monitoring"),
DesiredState: "ENABLED",
},
},
IsMonitoringDisabled: common.Bool(false),
IsManagementDisabled: common.Bool(false),
},
DefinedTags: make(map[string]map[string]interface{}),
FreeformTags: make(map[string]string),
InstanceOptions: &core.InstanceOptions{
AreLegacyImdsEndpointsDisabled: common.Bool(false),
},
AvailabilityConfig: &core.LaunchInstanceAvailabilityConfigDetails{
RecoveryAction: core.LaunchInstanceAvailabilityConfigDetailsRecoveryActionRestoreInstance,
},
ShapeConfig: &core.LaunchInstanceShapeConfigDetails{
Ocpus: &cfg.OCPUS,
MemoryInGBs: &cfg.MemoryInGbs,
},
},
}
return client.LaunchInstance(context.Background(), req)
}
func handleSuccess() {
log.Println("Instance created")
}