forked from paypal/gorealis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
realis.go
335 lines (256 loc) · 10.3 KB
/
realis.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
327
328
329
330
331
332
333
334
335
/**
* 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 realis provides the ability to use Thrift API to communicate with Apache Aurora.
package realis
import (
"encoding/base64"
"fmt"
"git.apache.org/thrift.git/lib/go/thrift"
"github.com/pkg/errors"
"github.com/rdelval/gorealis/gen-go/apache/aurora"
"github.com/rdelval/gorealis/response"
"net/http"
"net/http/cookiejar"
"os"
"time"
)
type Realis interface {
AbortJobUpdate(updateKey aurora.JobUpdateKey, message string) (*aurora.Response, error)
AddInstances(instKey aurora.InstanceKey, count int32) (*aurora.Response, error)
CreateJob(auroraJob Job) (*aurora.Response, error)
DescheduleCronJob(key *aurora.JobKey) (*aurora.Response, error)
FetchTaskConfig(instKey aurora.InstanceKey) (*aurora.TaskConfig, error)
GetInstanceIds(key *aurora.JobKey, states map[aurora.ScheduleStatus]bool) (map[int32]bool, error)
JobUpdateDetails(updateQuery aurora.JobUpdateQuery) (*aurora.Response, error)
KillJob(key *aurora.JobKey) (*aurora.Response, error)
KillInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error)
RestartInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error)
RestartJob(key *aurora.JobKey) (*aurora.Response, error)
RollbackJobUpdate(key aurora.JobUpdateKey, message string) (*aurora.Response, error)
ScheduleCronJob(auroraJob Job) (*aurora.Response, error)
StartJobUpdate(updateJob *UpdateJob, message string) (*aurora.Response, error)
StartCronJob(key *aurora.JobKey) (*aurora.Response, error)
Close()
}
type realisClient struct {
client *aurora.AuroraSchedulerManagerClient
}
// Wrap object to provide future flexibility
type RealisConfig struct {
transport thrift.TTransport
}
// Create a new Client with a default transport layer
func NewClient(config RealisConfig) Realis {
httpTrans := (config.transport).(*thrift.THttpClient)
httpTrans.SetHeader("User-Agent", "GoRealis v0.1")
protocolFactory := thrift.NewTJSONProtocolFactory()
return realisClient{
client: aurora.NewAuroraSchedulerManagerClientFactory(config.transport, protocolFactory)}
}
// Create a default configuration of the transport layer, requires a URL to test connection with.
func NewDefaultConfig(url string) (RealisConfig, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return RealisConfig{}, errors.Wrap(err, "Error creating Cookie Jar")
}
//Custom client to timeout after 10 seconds to avoid hanging
trans, err := thrift.NewTHttpPostClientWithOptions(url+"/api",
thrift.THttpClientOptions{Client: &http.Client{Timeout: time.Second * 10, Jar: jar}})
if err != nil {
return RealisConfig{}, errors.Wrap(err, "Error creating transport")
}
if err := trans.Open(); err != nil {
fmt.Fprintln(os.Stderr)
return RealisConfig{}, errors.Wrapf(err, "Error opening connection to %s", url)
}
return RealisConfig{transport: trans}, nil
}
// Helper function to add basic authorization needed to communicate with Apache Aurora.
func AddBasicAuth(config *RealisConfig, username string, password string) {
httpTrans := (config.transport).(*thrift.THttpClient)
httpTrans.SetHeader("Authorization", "Basic "+basicAuth(username, password))
}
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
// Releases resources associated with the realis client.
func (r realisClient) Close() {
r.client.Transport.Close()
}
// Uses predefined set of states to retrieve a set of active jobs in Apache Aurora.
func (r realisClient) GetInstanceIds(key *aurora.JobKey, states map[aurora.ScheduleStatus]bool) (map[int32]bool, error) {
taskQ := &aurora.TaskQuery{Role: key.Role,
Environment: key.Environment,
JobName: key.Name,
Statuses: states}
resp, err := r.client.GetTasksWithoutConfigs(taskQ)
if err != nil {
return nil, errors.Wrap(err, "Error querying Aurora Scheduler for active IDs")
}
tasks := response.ScheduleStatusResult(resp).GetTasks()
jobInstanceIds := make(map[int32]bool)
for _, task := range tasks {
jobInstanceIds[task.GetAssignedTask().GetInstanceId()] = true
}
return jobInstanceIds, nil
}
// Kill specific instances of a job.
func (r realisClient) KillInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error) {
instanceIds := make(map[int32]bool)
for _, instId := range instances {
instanceIds[instId] = true
}
response, err := r.client.KillTasks(key, instanceIds)
if err != nil {
return nil, errors.Wrap(err, "Error sending Kill command to Aurora Scheduler")
}
return response, nil
}
// Sends a kill message to the scheduler for all active tasks under a job.
func (r realisClient) KillJob(key *aurora.JobKey) (*aurora.Response, error) {
instanceIds, err := r.GetInstanceIds(key, aurora.ACTIVE_STATES)
if err != nil {
return nil, errors.Wrap(err, "Could not retrieve relevant task instance IDs")
}
if len(instanceIds) > 0 {
response, err := r.client.KillTasks(key, instanceIds)
if err != nil {
return nil, errors.Wrap(err, "Error sending Kill command to Aurora Scheduler")
}
return response, nil
} else {
return nil, errors.New("No tasks in the Active state")
}
}
// Sends a create job message to the scheduler with a specific job configuration.
func (r realisClient) CreateJob(auroraJob Job) (*aurora.Response, error) {
response, err := r.client.CreateJob(auroraJob.JobConfig())
if err != nil {
return nil, errors.Wrap(err, "Error sending Create command to Aurora Scheduler")
}
return response, nil
}
func (r realisClient) ScheduleCronJob(auroraJob Job) (*aurora.Response, error) {
response, err := r.client.ScheduleCronJob(auroraJob.JobConfig())
if err != nil {
return nil, errors.Wrap(err, "Error sending Cron Job Schedule message to Aurora Scheduler")
}
return response, nil
}
func (r realisClient) DescheduleCronJob(key *aurora.JobKey) (*aurora.Response, error) {
response, err := r.client.DescheduleCronJob(key)
if err != nil {
return nil, errors.Wrap(err, "Error sending Cron Job De-schedule message to Aurora Scheduler")
}
return response, nil
}
func (r realisClient) StartCronJob(key *aurora.JobKey) (*aurora.Response, error) {
response, err := r.client.StartCronJob(key)
if err != nil {
return nil, errors.Wrap(err, "Error sending Start Cron Job message to Aurora Scheduler")
}
return response, nil
}
// Restarts specific instances specified
func (r realisClient) RestartInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error) {
instanceIds := make(map[int32]bool)
for _, instId := range instances {
instanceIds[instId] = true
}
response, err := r.client.RestartShards(key, instanceIds)
if err != nil {
return nil, errors.Wrap(err, "Error sending Restart command to Aurora Scheduler")
}
return response, nil
}
// Restarts all active tasks under a job configuration.
func (r realisClient) RestartJob(key *aurora.JobKey) (*aurora.Response, error) {
instanceIds, err := r.GetInstanceIds(key, aurora.ACTIVE_STATES)
if err != nil {
return nil, errors.Wrap(err, "Could not retrieve relevant task instance IDs")
}
if len(instanceIds) > 0 {
response, err := r.client.RestartShards(key, instanceIds)
if err != nil {
return nil, errors.Wrap(err, "Error sending Restart command to Aurora Scheduler")
}
return response, nil
} else {
return nil, errors.New("No tasks in the Active state")
}
}
// Update all tasks under a job configuration. Currently gorealis doesn't support for canary deployments.
func (r realisClient) StartJobUpdate(updateJob *UpdateJob, message string) (*aurora.Response, error) {
response, err := r.client.StartJobUpdate(updateJob.req, message)
if err != nil {
return nil, errors.Wrap(err, "Error sending StartJobUpdate command to Aurora Scheduler")
}
return response, nil
}
// Abort Job Update on Aurora. Requires the updateId which can be obtained on the Aurora web UI.
func (r realisClient) AbortJobUpdate(
updateKey aurora.JobUpdateKey,
message string) (*aurora.Response, error) {
response, err := r.client.AbortJobUpdate(&updateKey, message)
if err != nil {
return nil, errors.Wrap(err, "Error sending AbortJobUpdate command to Aurora Scheduler")
}
return response, nil
}
// Scale up the number of instances under a job configuration using the configuration for specific
// instance to scale up.
func (r realisClient) AddInstances(instKey aurora.InstanceKey, count int32) (*aurora.Response, error) {
response, err := r.client.AddInstances(&instKey, count)
if err != nil {
return nil, errors.Wrap(err, "Error sending AddInstances command to Aurora Scheduler")
}
return response, nil
}
func (r realisClient) FetchTaskConfig(instKey aurora.InstanceKey) (*aurora.TaskConfig, error) {
ids := make(map[int32]bool)
ids[instKey.InstanceId] = true
taskQ := &aurora.TaskQuery{Role: instKey.JobKey.Role,
Environment: instKey.JobKey.Environment,
JobName: instKey.JobKey.Name,
InstanceIds: ids,
Statuses: aurora.ACTIVE_STATES}
resp, err := r.client.GetTasksStatus(taskQ)
if err != nil {
return nil, errors.Wrap(err, "Error querying Aurora Scheduler for task configuration")
}
tasks := response.ScheduleStatusResult(resp).GetTasks()
if len(tasks) == 0 {
return nil, errors.Errorf("Instance %d for jobkey %s/%s/%s doesn't exist",
instKey.InstanceId,
instKey.JobKey.Environment,
instKey.JobKey.Role,
instKey.JobKey.Name)
}
return tasks[0].AssignedTask.Task, nil
}
func (r realisClient) JobUpdateDetails(updateQuery aurora.JobUpdateQuery) (*aurora.Response, error) {
resp, err := r.client.GetJobUpdateDetails(&updateQuery)
if err != nil {
return nil, errors.Wrap(err, "Unable to get job update details")
}
return resp, nil
}
func (r realisClient) RollbackJobUpdate(key aurora.JobUpdateKey, message string) (*aurora.Response, error) {
resp, err := r.client.RollbackJobUpdate(&key, message)
if err != nil {
return nil, errors.Wrap(err, "Unable to roll back job update")
}
return resp, nil
}