forked from linuxkit/linuxkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider_scaleway.go
263 lines (223 loc) · 7.02 KB
/
provider_scaleway.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
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
const (
scalewayMetadataURL = "http://169.254.42.42/"
scalewayUserdataURL = "169.254.42.42:80"
instanceIDFile = "instance_id"
instanceLocationFile = "instance_location"
publicIPFile = "public_ip"
privateIPFile = "private_ip"
)
// ProviderScaleway is the type implementing the Provider interface for Scaleway
type ProviderScaleway struct {
}
// NewScaleway returns a new ProviderScaleway
func NewScaleway() *ProviderScaleway {
return &ProviderScaleway{}
}
func (p *ProviderScaleway) String() string {
return "Scaleway"
}
func (p *ProviderScaleway) sendBootSignal() error {
var client = &http.Client{
Timeout: time.Second * 2,
}
state := []byte(`{"state_detail": "booted"}`)
req, err := http.NewRequest("PATCH", scalewayMetadataURL+"state", bytes.NewBuffer(state))
if err != nil {
return fmt.Errorf("Scaleway: http.NewRequest failed: %s", err)
}
req.Header.Set("Content-Type", "application/json")
_, err = client.Do(req)
if err != nil {
return fmt.Errorf("Scaleway: Could not contact state service: %s", err)
}
return nil
}
// Probe checks if we are running on Scaleway
func (p *ProviderScaleway) Probe() bool {
// Getting the conf should always work...
_, err := scalewayGet(scalewayMetadataURL + "conf")
if err != nil {
log.Printf(err.Error())
return false
}
// we are on Scaleway so we need to send a request to tell that the instance has correctly booted
err = p.sendBootSignal()
if err != nil {
log.Printf("Scaleway: Could not signal that the instance booted")
}
return true
}
// Extract gets both the Scaleway specific and generic userdata
func (p *ProviderScaleway) Extract() ([]byte, error) {
metadata, err := scalewayGet(scalewayMetadataURL + "conf")
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to get conf: %s", err)
}
hostname, err := p.extractInformation(metadata, "hostname")
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to get hostname: %s", err)
}
err = ioutil.WriteFile(path.Join(ConfigPath, Hostname), hostname, 0644)
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to write hostname: %s", err)
}
instanceID, err := p.extractInformation(metadata, "id")
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to get instanceID: %s", err)
}
err = ioutil.WriteFile(path.Join(ConfigPath, instanceIDFile), instanceID, 0644)
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to write instance_id: %s", err)
}
instanceLocation, err := p.extractInformation(metadata, "location_zone_id")
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to get instanceLocation: %s", err)
}
err = ioutil.WriteFile(path.Join(ConfigPath, instanceLocationFile), instanceLocation, 0644)
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to write instance_location: %s", err)
}
publicIP, err := p.extractInformation(metadata, "public_ip_address")
if err != nil {
// not an error
log.Printf("Scaleway: Failed to get publicIP: %s", err)
} else {
err = ioutil.WriteFile(path.Join(ConfigPath, publicIPFile), publicIP, 0644)
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to write public_ip: %s", err)
}
}
privateIP, err := p.extractInformation(metadata, "private_ip")
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to get privateIP: %s", err)
}
err = ioutil.WriteFile(path.Join(ConfigPath, privateIPFile), privateIP, 0644)
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to write private_ip: %s", err)
}
if err := p.handleSSH(metadata); err != nil {
log.Printf("Scaleway: Failed to get ssh data: %s", err)
}
// Generic userdata
userData, err := scalewayGetUserdata()
if err != nil {
log.Printf("Scaleway: Failed to get user-data: %s", err)
// This is not an error
return nil, nil
}
return userData, nil
}
// exctractInformation returns the extracted information given as parameter from the metadata
func (p *ProviderScaleway) extractInformation(metadata []byte, information string) ([]byte, error) {
query := strings.ToUpper(information) + "="
for _, line := range bytes.Split(metadata, []byte("\n")) {
if bytes.HasPrefix(line, []byte(query)) {
return bytes.TrimPrefix(line, []byte(query)), nil
}
}
return []byte(""), fmt.Errorf("No %s found", information)
}
// scalewayGet requests and extracts the requested URL
func scalewayGet(url string) ([]byte, error) {
var client = &http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest("", url, nil)
if err != nil {
return nil, fmt.Errorf("Scaleway: http.NewRequest failed: %s", err)
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Scaleway: Could not contact metadata service: %s", err)
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Scaleway: Status not ok: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Scaleway: Failed to read http response: %s", err)
}
return body, nil
}
// scalewayGetUserdata returns the userdata of the server, differs from scalewayGet since the source port has to be below 1024 in order to work
func scalewayGetUserdata() ([]byte, error) {
server, err := net.ResolveTCPAddr("tcp", scalewayUserdataURL)
if err != nil {
return nil, err
}
var conn *net.TCPConn
foundPort := false
for i := 1; i <= 1024; i++ {
client, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(i))
if err != nil {
return nil, err
}
conn, err = net.DialTCP("tcp", client, server)
if err == nil {
foundPort = true
break
}
}
if foundPort == false {
return nil, errors.New("not able to found a free port below 1024")
}
defer conn.Close()
fmt.Fprintf(conn, "GET /user_data HTTP/1.0\r\n\r\n")
reader := bufio.NewReader(conn)
resp, err := http.ReadResponse(reader, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (p *ProviderScaleway) handleSSH(metadata []byte) error {
sshKeysNumberString, err := p.extractInformation(metadata, "ssh_public_keys")
if err != nil {
return fmt.Errorf("Failed to get sshKeys: %s", err)
}
sshKeysNumber, err := strconv.Atoi(string(sshKeysNumberString))
if err != nil {
return fmt.Errorf("Failed to convert sshKeysNumber to int: %s", err)
}
rootKeys := ""
for i := 0; i < sshKeysNumber; i++ {
sshKey, err := p.extractInformation(metadata, "ssh_public_keys_"+strconv.Itoa(i)+"_key")
if err != nil {
return fmt.Errorf("Failed to get ssh_key %d: %s", i, err)
}
line := string(bytes.Trim(sshKey, "'"))
parts := strings.SplitN(line, " ", 2)
if len(parts) == 2 {
rootKeys = rootKeys + parts[1] + "\n"
}
}
if err := os.Mkdir(path.Join(ConfigPath, SSH), 0755); err != nil {
return fmt.Errorf("Failed to create %s: %s", SSH, err)
}
err = ioutil.WriteFile(path.Join(ConfigPath, SSH, "authorized_keys"), []byte(rootKeys), 0600)
if err != nil {
return fmt.Errorf("Failed to write ssh keys: %s", err)
}
return nil
}