forked from evergreen-ci/evergreen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_spawn.go
225 lines (194 loc) · 6.56 KB
/
api_spawn.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
package service
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/alerts"
"github.com/evergreen-ci/evergreen/cloud"
"github.com/evergreen-ci/evergreen/model/distro"
"github.com/evergreen-ci/evergreen/model/event"
"github.com/evergreen-ci/evergreen/model/host"
"github.com/evergreen-ci/evergreen/notify"
"github.com/evergreen-ci/evergreen/rest/data"
"github.com/evergreen-ci/evergreen/util"
"github.com/gorilla/mux"
"github.com/mongodb/grip"
"github.com/pkg/errors"
)
type spawnResponse struct {
Hosts []host.Host `json:"hosts,omitempty"`
HostInfo host.Host `json:"host_info,omitempty"`
Distros []string `json:"distros,omitempty"`
// empty if the request succeeded
ErrorMessage string `json:"error_message,omitempty"`
}
func (as *APIServer) listDistros(w http.ResponseWriter, r *http.Request) {
distros, err := distro.Find(distro.BySpawnAllowed())
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
distroList := []string{}
for _, d := range distros {
distroList = append(distroList, d.Id)
}
as.WriteJSON(w, http.StatusOK, spawnResponse{Distros: distroList})
}
func (as *APIServer) requestHost(w http.ResponseWriter, r *http.Request) {
user := MustHaveUser(r)
hostRequest := struct {
Distro string `json:"distro"`
PublicKey string `json:"public_key"`
}{}
err := util.ReadJSONInto(util.NewRequestReader(r), &hostRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if hostRequest.Distro == "" {
http.Error(w, "distro may not be blank", http.StatusBadRequest)
return
}
if hostRequest.PublicKey == "" {
http.Error(w, "public key may not be blank", http.StatusBadRequest)
return
}
hc := &data.DBHostConnector{}
spawnHost, err := hc.NewIntentHost(hostRequest.Distro, hostRequest.PublicKey, "", user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if spawnHost == nil {
http.Error(w, "spawned host is nil", http.StatusBadRequest)
return
}
as.WriteJSON(w, http.StatusOK, "")
}
func (as *APIServer) spawnHostReady(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
instanceId := vars["instance_id"]
status := vars["status"]
// mark the host itself as provisioned
h, err := host.FindOne(host.ById(instanceId))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if h == nil {
http.Error(w, "host not found", http.StatusNotFound)
return
}
if status == evergreen.HostStatusSuccess {
if err = h.SetRunning(evergreen.User); err != nil {
grip.Errorf("Error marking host id %s as %s: %+v",
instanceId, evergreen.HostStatusSuccess, err)
}
} else {
grip.Warning(errors.WithStack(alerts.RunHostProvisionFailTriggers(h)))
if err = h.SetDecommissioned(evergreen.User, ""); err != nil {
grip.Errorf("Error marking host %s for user %s as decommissioned: %+v",
h.Host, h.StartedBy, err)
}
grip.Infof("Decommissioned %s for user %s because provisioning failed",
h.Host, h.StartedBy)
// send notification to the Evergreen team about this provisioning failure
subject := fmt.Sprintf("%v Spawn provisioning failure on %v", notify.ProvisionFailurePreface, h.Distro.Id)
message := fmt.Sprintf("Provisioning failed on %v host %v for user %v", h.Distro.Id, h.Host, h.StartedBy)
if err = notify.NotifyAdmins(subject, message, &as.Settings); err != nil {
grip.Errorln("issue sending email:", err)
}
// get/store setup logs
body := util.NewRequestReader(r)
defer body.Close()
setupLog, err := ioutil.ReadAll(body)
if err != nil {
grip.Errorln("problem reading request:", err)
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
event.LogProvisionFailed(instanceId, string(setupLog))
}
message := fmt.Sprintf(`
Host with id %v spawned.
The host's dns name is %v.
To ssh in: ssh -i <your private key> %v@%v`,
h.Id, h.Host, h.User, h.Host)
if status == evergreen.HostStatusFailed {
message += fmt.Sprintf("\nUnfortunately, the host's setup script did not run fully - check the setup.log " +
"file in the machine's home directory to see more details")
}
err = notify.TrySendNotificationToUser(h.StartedBy, "Your host is ready", message, notify.ConstructMailer(as.Settings.Notify))
grip.ErrorWhenln(err != nil, "Error sending email", err)
as.WriteJSON(w, http.StatusOK, spawnResponse{HostInfo: *h})
}
// returns info on the host specified
func (as *APIServer) hostInfo(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
instanceId := vars["instance_id"]
h, err := host.FindOne(host.ById(instanceId))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if h == nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
as.WriteJSON(w, http.StatusOK, spawnResponse{HostInfo: *h})
}
// returns info on all of the hosts spawned by a user
func (as *APIServer) hostsInfoForUser(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
user := vars["user"]
hosts, err := host.Find(host.ByUserWithUnterminatedStatus(user))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
as.WriteJSON(w, http.StatusOK, spawnResponse{Hosts: hosts})
}
func (as *APIServer) modifyHost(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
instanceId := vars["instance_id"]
hostAction := r.FormValue("action")
h, err := host.FindOne(host.ById(instanceId))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if h == nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
user := GetUser(r)
if user == nil || user.Id != h.StartedBy {
message := fmt.Sprintf("Only %v is authorized to terminate this host", h.StartedBy)
http.Error(w, message, http.StatusUnauthorized)
return
}
switch hostAction {
case "terminate":
if h.Status == evergreen.HostTerminated {
message := fmt.Sprintf("Host %v is already terminated", h.Id)
http.Error(w, message, http.StatusBadRequest)
return
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
cloudHost, err := cloud.GetCloudHost(ctx, h, &as.Settings)
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if err = cloudHost.TerminateInstance(ctx, user.Id); err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, errors.Wrap(err, "Failed to terminate spawn host"))
return
}
as.WriteJSON(w, http.StatusOK, spawnResponse{HostInfo: *h})
default:
http.Error(w, fmt.Sprintf("Unrecognized action %v", hostAction), http.StatusBadRequest)
}
}