forked from sardinasystems/fleeting-plugin-openstack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
222 lines (179 loc) · 5.52 KB
/
utils.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
package fpoc
import (
"context"
"encoding/json"
"fmt"
"maps"
"regexp"
"strings"
igncfg "github.com/coreos/ignition/v2/config/v3_4"
igntyp "github.com/coreos/ignition/v2/config/v3_4/types"
"github.com/coreos/vcontext/report"
"github.com/gophercloud/gophercloud/v2"
"github.com/gophercloud/gophercloud/v2/openstack/compute/v2/servers"
"github.com/gophercloud/gophercloud/v2/openstack/image/v2/images"
"github.com/mitchellh/mapstructure"
)
// ExtCreateOpts extended version of servers.CreateOpts
// nolint:revive
type ExtCreateOpts struct {
servers.CreateOpts
// fields absent in gophercloud
Description string `json:"description,omitempty"`
KeyName string `json:"key_name,omitempty"`
// annotation overrides
Networks []servers.Network `json:"networks,omitempty"`
SecurityGroups []string `json:"security_groups,omitempty"`
UserData string `json:"user_data,omitempty"`
SchedulerHints *servers.SchedulerHintOpts `json:"scheduler_hints,omitempty"`
}
// ToServerCreateMap for extended opts
func (opts ExtCreateOpts) ToServerCreateMap() (map[string]interface{}, error) {
if opts.Networks != nil {
opts.CreateOpts.Networks = opts.Networks
}
if opts.SecurityGroups != nil {
opts.CreateOpts.SecurityGroups = opts.SecurityGroups
}
if opts.UserData != "" {
opts.CreateOpts.UserData = []byte(opts.UserData)
}
ob, err := opts.CreateOpts.ToServerCreateMap()
if err != nil {
return nil, err
}
b := map[string]any{}
if opts.Description != "" {
b["description"] = opts.Description
}
if opts.KeyName != "" {
b["key_name"] = opts.KeyName
}
sob := ob["server"].(map[string]any)
maps.Copy(sob, b)
return ob, nil
}
type Address struct {
Version int `json:"version"`
Address string `json:"addr"`
MACAddr string `json:"OS-EXT-IPS-MAC:mac_addr,omitempty"`
Type string `json:"OS-EXT-IPS:type,omitempty"`
}
func extractAddresses(srv *servers.Server) (map[string][]Address, error) {
ret := make(map[string][]Address, len(srv.Addresses))
for net, isv := range srv.Addresses {
ism := isv.([]interface{})
items := make([]Address, 0, len(ism))
for _, iv := range ism {
var out Address
cfg := &mapstructure.DecoderConfig{
Metadata: nil,
Result: &out,
TagName: "json",
}
decoder, _ := mapstructure.NewDecoder(cfg)
err := decoder.Decode(iv)
if err != nil {
return nil, err
}
items = append(items, out)
}
ret[net] = items
}
return ret, nil
}
var (
initFinishedRe = regexp.MustCompile(`^.*Cloud-init\ v\.\ \S+\ finished\ at.*$`)
initSSHHostKeyRe = regexp.MustCompile(`^SSH\ host\ key:\ \S+:\S+\ (\S+)$`)
initLoginRe = regexp.MustCompile(`^\S+\ login:\ .*$`)
)
func IsCloudInitFinished(log string) bool {
lines := strings.Split(log, "\n")
for _, line := range lines {
if initFinishedRe.MatchString(line) {
return true
}
}
return false
}
func IsIgnitionFinished(log string) bool {
lines := strings.Split(log, "\n")
// Flatcar do not have any meaningful line,
// so instead we first check that there ssh host key message
// followed with login prompt
searchKeys := true
for _, line := range lines {
if searchKeys {
if initSSHHostKeyRe.MatchString(line) {
searchKeys = false
}
} else {
if initLoginRe.MatchString(line) {
return true
}
}
}
return false
}
// Some good known properties useful for setting up ConnectInfo
//
// See also: https://docs.openstack.org/glance/latest/admin/useful-image-properties.html
type ImageProperties struct {
Architecture string `json:"architecture,omitempty" mapstructure:"architecture,omitempty"`
OSType string `json:"os_type,omitempty" mapstructure:"os_type,omitempty"`
OSDistro string `json:"os_distro,omitempty" mapstructure:"os_distro,omitempty"`
OSVersion string `json:"os_version,omitempty" mapstructure:"os_version,omitempty"`
OSAdminUser string `json:"os_admin_user,omitempty" mapstructure:"os_admin_user,omitempty"`
// Extra map[string]any `mapstructure:",remain"`
}
func GetImageProperties(ctx context.Context, cli *gophercloud.ServiceClient, imageID string) (*ImageProperties, error) {
image, err := images.Get(ctx, cli, imageID).Extract()
if err != nil {
return nil, fmt.Errorf("failed to get image %s: %w", imageID, err)
}
out := new(ImageProperties)
err = mapstructure.Decode(image.Properties, out)
if err != nil {
return nil, fmt.Errorf("failed to parse properties: %w", err)
}
return out, nil
}
func InsertSSHKeyIgn(spec *ExtCreateOpts, username, pubKey string) error {
var cfg igntyp.Config
var err error
if spec.UserData != "" {
var rpt report.Report
cfg, rpt, err = igncfg.ParseCompatibleVersion([]byte(spec.UserData))
if err != nil {
return fmt.Errorf("failed to parse ignition: %w", err)
}
_ = rpt
}
if cfg.Ignition.Version == "" {
cfg.Ignition.Version = igntyp.MaxVersion.String()
}
var user *igntyp.PasswdUser
if cfg.Passwd.Users == nil {
cfg.Passwd.Users = make([]igntyp.PasswdUser, 0)
}
for idx, lu := range cfg.Passwd.Users {
if lu.Name == username {
user = &cfg.Passwd.Users[idx]
break
}
}
if user == nil {
cfg.Passwd.Users = append(cfg.Passwd.Users, igntyp.PasswdUser{Name: username})
user = &cfg.Passwd.Users[len(cfg.Passwd.Users)-1]
}
if user.SSHAuthorizedKeys == nil {
user.SSHAuthorizedKeys = make([]igntyp.SSHAuthorizedKey, 0)
}
user.SSHAuthorizedKeys = append(user.SSHAuthorizedKeys, igntyp.SSHAuthorizedKey(pubKey))
buf, err := json.Marshal(cfg)
if err != nil {
return fmt.Errorf("failed to marshal ignition: %w", err)
}
spec.UserData = string(buf)
return nil
}