forked from go-squads/saga-scheduler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
326 lines (265 loc) · 7.88 KB
/
scheduler.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/pborman/uuid"
log "github.com/sirupsen/logrus"
)
type scheduler struct {
Router *mux.Router
DB *sqlx.DB
client client
metricsDB metricsDB
}
type createContainerRequestData struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Protocol string `json:"protocol,omitempty"`
Server string `json:"server,omitempty"`
Alias string `json:"alias,omitempty"`
}
type client interface {
executeOperationRequest(req *http.Request) (*operation, error)
}
type agentClient struct{}
func (a agentClient) executeOperationRequest(req *http.Request) (*operation, error) {
client := &http.Client{
Timeout: 10 * time.Second,
}
response, err := client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
var op *operation
err = json.Unmarshal(body, &op)
if err != nil {
return nil, err
}
return op, nil
}
func (s *scheduler) initialize(user, password, dbname, host, port, sslmode string) error {
connectionString := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=%s", user, password, dbname, host, port, sslmode)
var err error
s.DB, err = sqlx.Connect("postgres", connectionString)
if err != nil {
return err
}
s.Router = mux.NewRouter()
s.Router.HandleFunc("/api/v1/container", s.createNewLxcHandler).Methods("POST")
s.Router.HandleFunc("/api/v1/container", s.getContainerHandler).Methods("GET")
s.Router.HandleFunc("/api/v1/container/updatestate", s.updateStateLxcHandler).Methods("POST")
s.Router.HandleFunc("/api/v1/container", s.deleteLxcHandler).Methods("DELETE")
s.Router.HandleFunc("/api/v1/lxd/{lxdName}/lxc", s.getLxcListByLxdNameHandler).Methods("GET")
s.client = agentClient{}
s.metricsDB = prometheusMetricsDB{}
return nil
}
func (s *scheduler) run(port string) {
log.Fatal(http.ListenAndServe(port, s.Router))
}
func (s *scheduler) getContainerHandler(w http.ResponseWriter, r *http.Request) {
type resp struct {
ID string `json:"id" db:"id"`
LXDName string `json:"lxd_name" db:"lxd_name"`
LXCName string `json:"lxc_name" db:"lxc_name"`
Image string `json:"image" db:"image"`
Status string `json:"status" db:"status"`
}
var result []resp
rows, err := s.DB.Queryx(`SELECT c.id as "id", c.name as "lxc_name", d.name as "lxd_name", c.alias as "image", c.status as "status" FROM lxc c JOIN lxd d ON c.lxd_id = d.id`)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
}
for rows.Next() {
var temp resp
err = rows.StructScan(&temp)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
}
result = append(result, temp)
}
respondWithJSON(w, http.StatusOK, result)
}
func (s *scheduler) createNewLxcHandler(w http.ResponseWriter, r *http.Request) {
log.Info("-- Got new create lxc request --")
var data createContainerRequestData
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&data); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
lxdInstance, err := s.metricsDB.getLowestLoadLxdInstance()
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
err = lxdInstance.getLxdByIP(s.DB)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
newLxc := lxc{
ID: uuid.New(),
LxdID: lxdInstance.ID,
Name: data.Name,
Type: data.Type,
Alias: data.Alias,
IsDeployed: 1,
}
err = newLxc.insertLxc(s.DB)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
op, err := s.createNewLxc(data, lxdInstance.Address)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
op.LxcID = newLxc.ID
err = op.insertOperation(s.DB)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
respondWithJSON(w, http.StatusOK, op)
return
}
func (s *scheduler) createNewLxc(data createContainerRequestData, lxdIPAddress string) (op *operation, err error) {
url := fmt.Sprintf("http://%s:9200/api/v1/container", lxdIPAddress)
payload, err := json.Marshal(data)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
if err != nil {
return nil, err
}
return s.client.executeOperationRequest(req)
}
func (s *scheduler) deleteLxcHandler(w http.ResponseWriter, r *http.Request) {
log.Info("-- Got delete lxc request --")
type deleteLxcRequest struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
}
var data deleteLxcRequest
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&data); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
lxc := lxc{
ID: data.ID,
}
if err := lxc.getLxc(s.DB); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
lxd := lxd{
ID: lxc.LxdID,
}
if err := lxd.getLxd(s.DB); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
data.Name = lxc.Name
url := fmt.Sprintf("http://%s:9200/api/v1/container", lxd.Address)
payload, err := json.Marshal(data)
req, err := http.NewRequest("DELETE", url, bytes.NewBuffer(payload))
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
op, err := s.client.executeOperationRequest(req)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
err = lxc.deleteLxc(s.DB)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
respondWithJSON(w, http.StatusOK, op)
}
func (s *scheduler) updateStateLxcHandler(w http.ResponseWriter, r *http.Request) {
log.Info("-- Got update state lxc request --")
type updateStateRequest struct {
ID string `json:"id"`
Name string `json:"name"`
State struct {
Action string `json:"action"`
Timeout int `json:"timeout"`
} `json:"state"`
}
var data updateStateRequest
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&data); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
lxc := lxc{
ID: data.ID,
}
if err := lxc.getLxc(s.DB); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
lxd := lxd{
ID: lxc.LxdID,
}
if err := lxd.getLxd(s.DB); err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
url := fmt.Sprintf("http://%s:9200/api/v1/container/updatestate", lxd.Address)
payload, err := json.Marshal(data)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
op, err := s.client.executeOperationRequest(req)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
respondWithJSON(w, http.StatusOK, op)
}
func (s *scheduler) getLxcListByLxdNameHandler(w http.ResponseWriter, r *http.Request) {
log.Info("-- Got get lxc by lxd name request --")
vars := mux.Vars(r)
lxdName := vars["lxdName"]
lxdSearch := lxd{Name: lxdName}
if err := lxdSearch.getLxdIDByName(s.DB); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
}
lxcSearch := lxc{}
lxcList, err := lxcSearch.getLxcListByLxdID(s.DB, lxdSearch.ID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, lxcList)
}
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(code)
w.Write(response)
}