-
Notifications
You must be signed in to change notification settings - Fork 129
/
client.go
355 lines (300 loc) · 10.4 KB
/
client.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
Copyright 2014 Rohith All rights reserved.
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 marathon
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/golang/glog"
)
// Marathon is the interface to the marathon API
type Marathon interface {
// -- APPLICATIONS ---
// check it see if a application exists
HasApplication(name string) (bool, error)
// get a listing of the application ids
ListApplications(url.Values) ([]string, error)
// a list of application versions
ApplicationVersions(name string) (*ApplicationVersions, error)
// check a application version exists
HasApplicationVersion(name, version string) (bool, error)
// change an application to a different version
SetApplicationVersion(name string, version *ApplicationVersion) (*DeploymentID, error)
// check if an application is ok
ApplicationOK(name string) (bool, error)
// create an application in marathon
CreateApplication(application *Application) (*Application, error)
// delete an application
DeleteApplication(name string) (*DeploymentID, error)
// update an application in marathon
UpdateApplication(application *Application) (*DeploymentID, error)
// a list of deployments on a application
ApplicationDeployments(name string) ([]*DeploymentID, error)
// scale a application
ScaleApplicationInstances(name string, instances int, force bool) (*DeploymentID, error)
// restart an application
RestartApplication(name string, force bool) (*DeploymentID, error)
// get a list of applications from marathon
Applications(url.Values) (*Applications, error)
// get a specific application
Application(name string) (*Application, error)
// wait of application
WaitOnApplication(name string, timeout time.Duration) error
// -- TASKS ---
// get a list of tasks for a specific application
Tasks(application string) (*Tasks, error)
// get a list of all tasks
AllTasks(v url.Values) (*Tasks, error)
// get the endpoints for a service on a application
TaskEndpoints(name string, port int, healthCheck bool) ([]string, error)
// kill all the tasks for any application
KillApplicationTasks(applicationID, hostname string, scale bool) (*Tasks, error)
// kill a single task
KillTask(taskID string, scale bool) (*Task, error)
// kill the given array of tasks
KillTasks(taskIDs []string, scale bool) error
// --- GROUPS ---
// list all the groups in the system
Groups() (*Groups, error)
// retrieve a specific group from marathon
Group(name string) (*Group, error)
// create a group deployment
CreateGroup(group *Group) error
// delete a group
DeleteGroup(name string) (*DeploymentID, error)
// update a groups
UpdateGroup(id string, group *Group) (*DeploymentID, error)
// check if a group exists
HasGroup(name string) (bool, error)
// wait for an group to be deployed
WaitOnGroup(name string, timeout time.Duration) error
// --- DEPLOYMENTS ---
// get a list of the deployments
Deployments() ([]*Deployment, error)
// delete a deployment
DeleteDeployment(id string, force bool) (*DeploymentID, error)
// check to see if a deployment exists
HasDeployment(id string) (bool, error)
// wait of a deployment to finish
WaitOnDeployment(id string, timeout time.Duration) error
// --- SUBSCRIPTIONS ---
// a list of current subscriptions
Subscriptions() (*Subscriptions, error)
// add a events listener
AddEventsListener(channel EventsChannel, filter int) error
// remove a events listener
RemoveEventsListener(channel EventsChannel)
// remove our self from subscriptions
Unsubscribe(string) error
// --- MISC ---
// get the marathon url
GetMarathonURL() string
// ping the marathon
Ping() (bool, error)
// grab the marathon server info
Info() (*Info, error)
// retrieve the leader info
Leader() (string, error)
// cause the current leader to abdicate
AbdicateLeader() (string, error)
}
var (
// ErrInvalidEndpoint is thrown when the marathon url specified was invalid
ErrInvalidEndpoint = errors.New("invalid Marathon endpoint specified")
// ErrInvalidResponse is thrown when marathon responds with invalid or error response
ErrInvalidResponse = errors.New("invalid response from Marathon")
// ErrDoesNotExist is thrown when the resource does not exists
ErrDoesNotExist = errors.New("the resource does not exist")
// ErrMarathonDown is thrown when all the marathon endpoints are down
ErrMarathonDown = errors.New("all the Marathon hosts are presently down")
// ErrInvalidArgument is thrown when invalid argument
ErrInvalidArgument = errors.New("the argument passed is invalid")
// ErrTimeoutError is thrown when the operation has timed out
ErrTimeoutError = errors.New("the operation has timed out")
// ErrConflict is thrown when the resource is conflicting (ie. app already exists)
ErrConflict = errors.New("conflicting resource")
)
type marathonClient struct {
sync.RWMutex
// the configuration for the client
config Config
// the flag used to prevent multiple SSE subscriptions
subscribedToSSE bool
// the ip address of the client
ipAddress string
// the http server */
eventsHTTP *http.Server
// the http client use for making requests
httpClient *http.Client
// the output for the logger
logger *log.Logger
// the marathon cluster
cluster Cluster
// a map of service you wish to listen to
listeners map[EventsChannel]int
}
// NewClient creates a new marathon client
// config: the configuration to use
func NewClient(config Config) (Marathon, error) {
// step: we parse the url and build a cluster
cluster, err := newCluster(config.URL)
if err != nil {
return nil, err
}
service := new(marathonClient)
service.config = config
service.listeners = make(map[EventsChannel]int, 0)
service.cluster = cluster
service.httpClient = &http.Client{
Timeout: (time.Duration(config.RequestTimeout) * time.Second),
}
return service, nil
}
// GetMarathonURL retrieves the marathon url
func (r *marathonClient) GetMarathonURL() string {
return r.cluster.URL()
}
// Ping pings the current marathon endpoint (note, this is not a ICMP ping, but a rest api call)
func (r *marathonClient) Ping() (bool, error) {
if err := r.apiGet(marathonAPIPing, nil, nil); err != nil {
return false, err
}
return true, nil
}
func (r *marathonClient) encodeRequest(data interface{}) (string, error) {
response, err := json.Marshal(data)
if err != nil {
return "", err
}
return string(response), err
}
func (r *marathonClient) decodeRequest(stream io.Reader, result interface{}) error {
if err := json.NewDecoder(stream).Decode(result); err != nil {
return err
}
return nil
}
func (r *marathonClient) buildPostData(data interface{}) (string, error) {
if data == nil {
return "", nil
}
content, err := r.encodeRequest(data)
if err != nil {
return "", err
}
return content, nil
}
func (r *marathonClient) apiGet(uri string, post, result interface{}) error {
return r.apiOperation("GET", uri, post, result)
}
func (r *marathonClient) apiPut(uri string, post, result interface{}) error {
return r.apiOperation("PUT", uri, post, result)
}
func (r *marathonClient) apiPost(uri string, post, result interface{}) error {
return r.apiOperation("POST", uri, post, result)
}
func (r *marathonClient) apiDelete(uri string, post, result interface{}) error {
return r.apiOperation("DELETE", uri, post, result)
}
func (r *marathonClient) apiOperation(method, uri string, post, result interface{}) error {
content, err := r.buildPostData(post)
if err != nil {
return err
}
_, _, err = r.apiCall(method, uri, content, result)
return err
}
func (r *marathonClient) apiCall(method, uri, body string, result interface{}) (int, string, error) {
glog.V(debugLevel).Infof("[api]: method: %s, uri: %s, body: %s", method, uri, body)
status, content, _, err := r.httpRequest(method, uri, body)
if err != nil {
return 0, "", err
}
glog.V(debugLevel).Infof("[api] result: status: %d, content: %s\n", status, content)
if status >= 200 && status <= 299 {
if result != nil {
if err := r.decodeRequest(strings.NewReader(content), result); err != nil {
glog.V(debugLevel).Infof("failed to unmarshall the response from marathon, error: %s", err)
return status, content, ErrInvalidResponse
}
}
return status, content, nil
}
switch status {
case 500:
return status, "", ErrInvalidResponse
case 404:
return status, "", ErrDoesNotExist
case 409:
return status, "", ErrConflict
}
// step: lets decode into a error message
var message struct {
Message string `json:"message"`
}
if err := r.decodeRequest(strings.NewReader(content), &message); err != nil {
return status, content, ErrInvalidResponse
}
errorMessage := "unknown error"
if message.Message != "" {
errorMessage = message.Message
}
return status, "", fmt.Errorf("%s", errorMessage)
}
func (r *marathonClient) httpRequest(method, uri, body string) (int, string, *http.Response, error) {
var content string
var response *http.Response
// Try to connect to Marathon until succeed or
// the whole custer is down
for {
// Get a member from the cluster
marathon, err := r.cluster.GetMember()
if err != nil {
return 0, "", nil, err
}
url := fmt.Sprintf("%s/%s", marathon, uri)
glog.V(debugLevel).Infof("[http] request: %s, uri: %s, url: %s", method, uri, url)
// Make the http request to Marathon
request, err := http.NewRequest(method, url, strings.NewReader(body))
if err != nil {
return 0, "", nil, err
}
// Add any basic auth and the content headers
if r.config.HTTPBasicAuthUser != "" {
request.SetBasicAuth(r.config.HTTPBasicAuthUser, r.config.HTTPBasicPassword)
}
request.Header.Add("Content-Type", "application/json")
request.Header.Add("Accept", "application/json")
response, err = r.httpClient.Do(request)
if err == nil {
break
}
r.cluster.MarkDown()
}
if response.ContentLength != 0 {
responseContent, err := ioutil.ReadAll(response.Body)
if err != nil {
return response.StatusCode, "", response, err
}
content = string(responseContent)
}
return response.StatusCode, content, response, nil
}