This repository has been archived by the owner on Jul 1, 2023. It is now read-only.
/
wizard.go
273 lines (238 loc) · 6.71 KB
/
wizard.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
264
265
266
267
268
269
270
271
272
273
/*
Copyright 2020 Gravitational, Inc.
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 infra
import (
"bufio"
"context"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"regexp"
"strings"
"golang.org/x/crypto/ssh"
"github.com/gravitational/robotest/lib/loc"
"github.com/gravitational/robotest/lib/wait"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)
func startWizard(provisioner Provisioner, installer Node) (cluster *wizardCluster, err error) {
var session *ssh.Session
err = wait.Retry(context.TODO(), func() error {
session, err = installer.Connect()
if err != nil {
log.Debug(trace.DebugReport(err))
}
return trace.Wrap(err)
})
if err != nil {
return nil, trace.Wrap(err)
}
defer func() {
if err == nil {
return
}
errClose := session.Close()
if errClose != nil {
log.Errorf("failed to close wizard SSH session: %v", errClose)
}
}()
var stdin io.WriteCloser
stdin, err = session.StdinPipe()
if err != nil {
return nil, trace.Wrap(err)
}
defer stdin.Close()
var stdout io.Reader
stdout, err = session.StdoutPipe()
if err != nil {
return nil, trace.Wrap(err)
}
reader, writer := io.Pipe()
go func() {
_, err := io.Copy(io.MultiWriter(os.Stdout, writer), stdout)
if err != nil {
log.Errorf("failed to read from remote stdout: %v", err)
}
reader.Close()
writer.Close()
}()
defer func() {
if err != nil {
reader.Close()
writer.Close()
}
}()
var stderr io.Reader
stderr, err = session.StderrPipe()
if err != nil {
return nil, trace.Wrap(err)
}
go func() {
_, err := io.Copy(os.Stderr, stderr)
if err != nil {
log.Errorf("failed to read from remote stderr: %v", err)
}
}()
// launch the installer
log.Debugf("starting installer...")
err = provisioner.StartInstall(session)
if err != nil {
return nil, trace.Wrap(err)
}
var installerURL *url.URL
log.Debugf("configuring wizard...")
installerURL, err = configureWizard(reader, stdin, provisioner, installer)
if err != nil {
return nil, trace.Wrap(err)
}
if installerURL == nil {
err = trace.NotFound("failed to fetch installer URL. Check installer output for details.")
return nil, err
}
var application *loc.Locator
application, err = extractPackage(*installerURL)
if err != nil {
return nil, trace.Wrap(err)
}
// Discard all stdout content after the necessary wizard details have been obtained
go func() {
_, _ = io.Copy(ioutil.Discard, reader)
}()
// TODO: make sure that all io.Copy goroutines shutdown in Close
return &wizardCluster{
provisioner: provisioner,
application: *application,
installerURL: *installerURL,
session: session,
}, nil
}
func configureWizard(stdout io.Reader, stdin io.Writer, provisioner Provisioner, installerNode Node) (installerURL *url.URL, err error) {
s := bufio.NewScanner(stdout)
var state scannerState = emptyState
var addrs []string
L:
for s.Scan() {
line := s.Text()
switch state {
case readingInterfacesState:
if strings.HasPrefix(line, "---") {
continue
}
match := reInstallerIP.FindStringSubmatch(line)
if len(match) == 3 {
addrs = append(addrs, match[2])
} else {
state = emptyState
}
default:
switch {
case strings.HasPrefix(line, "[interfaces]"):
state = readingInterfacesState
case strings.HasPrefix(line, "select interface number"):
if len(addrs) == 0 {
return nil, trace.NotFound("no network interfaces reported by the installer")
}
index, err := provisioner.SelectInterface(installerNode, addrs)
if err != nil {
return nil, trace.Wrap(err)
}
_, err = io.Copy(stdin, strings.NewReader(fmt.Sprintf("%v\n", index+1)))
if err != nil {
return nil, trace.Wrap(err, "failed to select network interface")
}
case strings.HasPrefix(line, "confirm (yes/no)"):
_, err = io.Copy(stdin, strings.NewReader("yes\n"))
if err != nil {
return nil, trace.Wrap(err, "failed to confirm network interface")
}
case strings.HasPrefix(line, "OPEN THIS IN BROWSER"):
installerURL, err = extractInstallerURL(line, installerNode.Addr())
if err != nil {
return nil, trace.Wrap(err)
}
break L
default:
state = emptyState
}
}
}
return installerURL, nil
}
func extractPackage(installerURL url.URL) (application *loc.Locator, err error) {
packageSuffix := strings.TrimPrefix(installerURL.Path, "/web/installer/new/")
fields := strings.Split(packageSuffix, "/")
if len(fields) != 3 {
return nil, trace.Wrap(err, "invalid application package suffix %q, expected repository/name/version",
packageSuffix)
}
repository, name, version := fields[0], fields[1], fields[2]
return loc.NewLocator(repository, name, version), nil
}
func extractInstallerURL(input, installerIP string) (installerURL *url.URL, err error) {
match := reInstallerURL.FindStringSubmatch(input)
if len(match) != 2 {
return nil, trace.NotFound("failed to extract installer URL")
}
addr := match[1]
addrURL, err := url.Parse(addr)
if err != nil {
return nil, trace.Wrap(err, "failed to parse URL %q", addr)
}
log.Infof("found installer URL: %v", addrURL.Path)
// generated installer URL has private IP in it - replace it with the public IP of the
// installer machine to be able to connect
_, port, err := net.SplitHostPort(addrURL.Host)
if err != nil {
return nil, trace.Wrap(err, "failed to split host:port in %q", addrURL.Host)
}
addrURL.Host = strings.Join([]string{installerIP, port}, ":")
return addrURL, nil
}
type scannerState byte
const (
emptyState = 0
readingInterfacesState = iota
)
func (r *wizardCluster) Close() error {
return r.session.Close()
}
func (r *wizardCluster) Destroy() error {
return r.provisioner.Destroy(context.TODO())
}
func (r *wizardCluster) OpsCenterURL() string {
url := r.installerURL
url.RawQuery = ""
url.Path = ""
return url.String()
}
func (r *wizardCluster) Provisioner() Provisioner {
return r.provisioner
}
func (r *wizardCluster) Config() Config {
return r.config
}
// wizardCluster implements Infra
type wizardCluster struct {
config Config
provisioner Provisioner
session *ssh.Session
installerURL url.URL
application loc.Locator
}
var (
reInstallerURL = regexp.MustCompile("(?m:^OPEN THIS IN BROWSER: (.+)$)")
reInstallerIP = regexp.MustCompile(`(\d+).\s+(\d+.\d+.\d+.\d+)`)
)