This repository has been archived by the owner on Jun 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
packet.go
251 lines (213 loc) · 7.78 KB
/
packet.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
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
// Copyright 2020 The Lokomotive Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package packet
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"text/template"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"github.com/kinvolk/lokomotive/pkg/dns"
"github.com/kinvolk/lokomotive/pkg/platform"
"github.com/kinvolk/lokomotive/pkg/platform/util"
"github.com/kinvolk/lokomotive/pkg/terraform"
)
type workerPool struct {
Name string `hcl:"pool_name,label"`
Count int `hcl:"count"`
DisableBGP bool `hcl:"disable_bgp,optional"`
IPXEScriptURL string `hcl:"ipxe_script_url,optional"`
OSArch string `hcl:"os_arch,optional"`
OSChannel string `hcl:"os_channel,optional"`
OSVersion string `hcl:"os_version,optional"`
NodeType string `hcl:"node_type,optional"`
Labels string `hcl:"labels,optional"`
Taints string `hcl:"taints,optional"`
SetupRaid bool `hcl:"setup_raid,optional"`
SetupRaidHDD bool `hcl:"setup_raid_hdd,optional"`
SetupRaidSSD bool `hcl:"setup_raid_ssd,optional"`
SetupRaidSSDFS bool `hcl:"setup_raid_ssd_fs,optional"`
}
type config struct {
AssetDir string `hcl:"asset_dir"`
AuthToken string `hcl:"auth_token,optional"`
ClusterName string `hcl:"cluster_name"`
Tags map[string]string `hcl:"tags,optional"`
ControllerCount int `hcl:"controller_count"`
ControllerType string `hcl:"controller_type,optional"`
DNS dns.Config `hcl:"dns,block"`
Facility string `hcl:"facility"`
ProjectID string `hcl:"project_id"`
SSHPubKeys []string `hcl:"ssh_pubkeys"`
OSArch string `hcl:"os_arch,optional"`
OSChannel string `hcl:"os_channel,optional"`
OSVersion string `hcl:"os_version,optional"`
IPXEScriptURL string `hcl:"ipxe_script_url,optional"`
ManagementCIDRs []string `hcl:"management_cidrs"`
NodePrivateCIDR string `hcl:"node_private_cidr"`
EnableAggregation bool `hcl:"enable_aggregation,optional"`
Networking string `hcl:"networking,optional"`
NetworkMTU int `hcl:"network_mtu,optional"`
PodCIDR string `hcl:"pod_cidr,optional"`
ServiceCIDR string `hcl:"service_cidr,optional"`
ClusterDomainSuffix string `hcl:"cluster_domain_suffix,optional"`
EnableReporting bool `hcl:"enable_reporting,optional"`
ReservationIDs map[string]string `hcl:"reservation_ids,optional"`
ReservationIDsDefault string `hcl:"reservation_ids_default,optional"`
CertsValidityPeriodHours int `hcl:"certs_validity_period_hours,optional"`
WorkerPools []workerPool `hcl:"worker_pool,block"`
}
// init registers packet as a platform
func init() {
platform.Register("packet", NewConfig())
}
func (c *config) LoadConfig(configBody *hcl.Body, evalContext *hcl.EvalContext) hcl.Diagnostics {
if configBody == nil {
return hcl.Diagnostics{}
}
if diags := gohcl.DecodeBody(*configBody, evalContext, c); len(diags) != 0 {
return diags
}
if len(c.WorkerPools) == 0 {
err := &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "At least one worker pool must be defined",
Detail: "Make sure to define at least one worker pool block in your cluster block",
}
return hcl.Diagnostics{err}
}
return nil
}
func NewConfig() *config {
return &config{
EnableAggregation: true,
}
}
// GetAssetDir returns asset directory path
func (c *config) GetAssetDir() string {
return c.AssetDir
}
func (c *config) Initialize(ex *terraform.Executor) error {
if c.AuthToken == "" && os.Getenv("PACKET_AUTH_TOKEN") == "" {
return fmt.Errorf("cannot find the Packet authentication token:\n" +
"either specify AuthToken or use the PACKET_AUTH_TOKEN environment variable")
}
assetDir, err := homedir.Expand(c.AssetDir)
if err != nil {
return err
}
terraformRootDir := terraform.GetTerraformRootDir(assetDir)
return createTerraformConfigFile(c, terraformRootDir)
}
func (c *config) Install(ex *terraform.Executor) error {
assetDir, err := homedir.Expand(c.AssetDir)
if err != nil {
return err
}
c.AssetDir = assetDir
dnsProvider, err := dns.ParseDNS(&c.DNS)
if err != nil {
return errors.Wrap(err, "parsing DNS configuration failed")
}
if err := c.Initialize(ex); err != nil {
return err
}
// If the provider isn't manual, apply everything in a single step.
if dnsProvider != dns.DNSManual {
return ex.Apply()
}
arguments := []string{"apply", "-auto-approve"}
// Get DNS entries (it forces the creation of the controller nodes).
arguments = append(arguments, fmt.Sprintf("-target=module.packet-%s.null_resource.dns_entries", c.ClusterName))
// Add worker nodes to speed things up.
for index := range c.WorkerPools {
arguments = append(arguments, fmt.Sprintf("-target=module.worker-pool-%d.packet_device.nodes", index))
}
// Create controller and workers nodes.
if err := ex.Execute(arguments...); err != nil {
return errors.Wrap(err, "failed executing Terraform")
}
if err := dns.AskToConfigure(ex, &c.DNS); err != nil {
return errors.Wrap(err, "failed to configure DNS entries")
}
// Finish deployment.
return ex.Apply()
}
func (c *config) Destroy(ex *terraform.Executor) error {
if err := c.Initialize(ex); err != nil {
return err
}
return ex.Destroy()
}
func createTerraformConfigFile(cfg *config, terraformPath string) error {
tmplName := "cluster.tf"
t := template.New(tmplName)
t, err := t.Parse(terraformConfigTmpl)
if err != nil {
return errors.Wrap(err, "failed to parse template")
}
path := filepath.Join(terraformPath, tmplName)
f, err := os.Create(path)
if err != nil {
return errors.Wrapf(err, "failed to create file %q", path)
}
defer f.Close()
keyListBytes, err := json.Marshal(cfg.SSHPubKeys)
if err != nil {
return errors.Wrap(err, "failed to marshal SSH public keys")
}
managementCIDRs, err := json.Marshal(cfg.ManagementCIDRs)
if err != nil {
return errors.Wrapf(err, "failed to marshal management CIDRs")
}
// Packet does not accept tags as a key-value map but as an array of
// strings.
util.AppendTags(&cfg.Tags)
tagsList := []string{}
for k, v := range cfg.Tags {
tagsList = append(tagsList, fmt.Sprintf("%s:%s", k, v))
}
sort.Strings(tagsList)
tags, err := json.Marshal(tagsList)
if err != nil {
return errors.Wrapf(err, "failed to marshal tags")
}
terraformCfg := struct {
Config config
Tags string
SSHPublicKeys string
ManagementCIDRs string
}{
Config: *cfg,
Tags: string(tags),
SSHPublicKeys: string(keyListBytes),
ManagementCIDRs: string(managementCIDRs),
}
if err := t.Execute(f, terraformCfg); err != nil {
return errors.Wrapf(err, "failed to write template to file: %q", path)
}
return nil
}
func (c *config) GetExpectedNodes() int {
workers := 0
for _, wp := range c.WorkerPools {
workers += wp.Count
}
return c.ControllerCount + workers
}