-
Notifications
You must be signed in to change notification settings - Fork 493
/
client.go
2400 lines (2041 loc) · 52.5 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Kapacitor HTTP API client written in Go
package client
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"path"
"strconv"
"time"
"github.com/influxdata/influxdb/influxql"
khttp "github.com/influxdata/kapacitor/http"
"github.com/pkg/errors"
)
const DefaultUserAgent = "KapacitorClient"
// These are the constant enpoints for the API.
// The server will always return a `link` to resources,
// so path manipulation should not be necessary.
// The only exception is if you only have an ID for a resource
// then use the appropriate *Link methods.
const (
basePath = "/kapacitor/v1"
basePreviewPath = "/kapacitor/v1preview"
pingPath = basePath + "/ping"
logLevelPath = basePath + "/loglevel"
logsPath = basePreviewPath + "/logs"
debugVarsPath = basePath + "/debug/vars"
tasksPath = basePath + "/tasks"
templatesPath = basePath + "/templates"
recordingsPath = basePath + "/recordings"
recordStreamPath = basePath + "/recordings/stream"
recordBatchPath = basePath + "/recordings/batch"
recordQueryPath = basePath + "/recordings/query"
replaysPath = basePath + "/replays"
replayBatchPath = basePath + "/replays/batch"
replayQueryPath = basePath + "/replays/query"
configPath = basePath + "/config"
serviceTestsPath = basePath + "/service-tests"
alertsPath = basePath + "/alerts"
topicsPath = alertsPath + "/topics"
topicEventsPath = "events"
topicHandlersPath = "handlers"
storagePath = basePath + "/storage"
storesPath = storagePath + "/stores"
backupPath = storagePath + "/backup"
)
// HTTP configuration for connecting to Kapacitor
type Config struct {
// The URL of the Kapacitor server.
URL string
// Timeout for API requests, defaults to no timeout.
Timeout time.Duration
// UserAgent is the http User Agent, defaults to "KapacitorClient".
UserAgent string
// InsecureSkipVerify gets passed to the http client, if true, it will
// skip https certificate verification. Defaults to false.
InsecureSkipVerify bool
// TLSConfig allows the user to set their own TLS config for the HTTP
// Client. If set, this option overrides InsecureSkipVerify.
TLSConfig *tls.Config
// Optional credentials for authenticating with the server.
Credentials *Credentials
// Optional Transport https://golang.org/pkg/net/http/#RoundTripper
// If nil the default transport will be used
Transport http.RoundTripper
}
// AuthenticationMethod defines the type of authentication used.
type AuthenticationMethod int
// Supported authentication methods.
const (
_ AuthenticationMethod = iota
UserAuthentication
BearerAuthentication
)
// Set of credentials depending on the authentication method
type Credentials struct {
Method AuthenticationMethod
// UserAuthentication fields
Username string
Password string
// BearerAuthentication fields
Token string
}
func (c Credentials) Validate() error {
switch c.Method {
case UserAuthentication:
if c.Username == "" {
return errors.New("missing username")
}
if c.Password == "" {
return errors.New("missing password")
}
case BearerAuthentication:
if c.Token == "" {
return errors.New("missing token")
}
default:
return errors.New("missing authentication method")
}
return nil
}
type localTransport struct {
h http.Handler
}
func (l *localTransport) RoundTrip(r *http.Request) (*http.Response, error) {
w := httptest.NewRecorder()
l.h.ServeHTTP(w, r)
return w.Result(), nil
}
func NewLocalTransport(h http.Handler) http.RoundTripper {
return &localTransport{
h: h,
}
}
// Basic HTTP client
type Client struct {
url *url.URL
userAgent string
httpClient *http.Client
credentials *Credentials
}
// Create a new client.
func New(conf Config) (*Client, error) {
if conf.UserAgent == "" {
conf.UserAgent = DefaultUserAgent
}
u, err := url.Parse(conf.URL)
if err != nil {
return nil, err
} else if u.Scheme != "http" && u.Scheme != "https" {
return nil, fmt.Errorf(
"Unsupported protocol scheme: %s, your address must start with http:// or https://",
u.Scheme,
)
}
if conf.Credentials != nil {
if err := conf.Credentials.Validate(); err != nil {
return nil, errors.Wrap(err, "invalid credentials")
}
}
rt := conf.Transport
var tr *http.Transport
if rt == nil {
tr = khttp.NewDefaultTransportWithTLS(&tls.Config{
InsecureSkipVerify: conf.InsecureSkipVerify,
})
if conf.TLSConfig != nil {
tr.TLSClientConfig = conf.TLSConfig
}
rt = tr
}
return &Client{
url: u,
userAgent: conf.UserAgent,
httpClient: &http.Client{
Timeout: conf.Timeout,
Transport: rt,
},
credentials: conf.Credentials,
}, nil
}
type Relation string
const (
Self Relation = "self"
)
func (r Relation) String() string {
return string(r)
}
type Link struct {
Relation Relation `json:"rel"`
Href string `json:"href"`
}
type DBRP struct {
Database string `json:"db"`
RetentionPolicy string `json:"rp"`
}
func (d DBRP) String() string {
return fmt.Sprintf("%q.%q", d.Database, d.RetentionPolicy)
}
// Statistics about the execution of a task.
type ExecutionStats struct {
// Summary stats about the entire task
TaskStats map[string]interface{} `json:"task-stats,omitempty"`
// Stats for each node in the task
NodeStats map[string]map[string]interface{} `json:"node-stats,omitempty"`
}
type TaskType int
const (
InvalidTask TaskType = 0
StreamTask TaskType = 1
BatchTask TaskType = 2
)
func (tt TaskType) MarshalText() ([]byte, error) {
switch tt {
case StreamTask:
return []byte("stream"), nil
case BatchTask:
return []byte("batch"), nil
case InvalidTask:
return []byte("invalid"), nil
default:
return nil, fmt.Errorf("unknown TaskType %d", tt)
}
}
func (tt *TaskType) UnmarshalText(text []byte) error {
switch s := string(text); s {
case "stream":
*tt = StreamTask
case "batch":
*tt = BatchTask
case "invalid":
*tt = InvalidTask
default:
return fmt.Errorf("unknown TaskType %s", s)
}
return nil
}
func (tt TaskType) String() string {
s, err := tt.MarshalText()
if err != nil {
return err.Error()
}
return string(s)
}
type TaskStatus int
const (
Disabled TaskStatus = 1
Enabled TaskStatus = 2
)
func (ts TaskStatus) MarshalText() ([]byte, error) {
switch ts {
case Disabled:
return []byte("disabled"), nil
case Enabled:
return []byte("enabled"), nil
default:
return nil, fmt.Errorf("unknown TaskStatus %d", ts)
}
}
func (ts *TaskStatus) UnmarshalText(text []byte) error {
switch s := string(text); s {
case "enabled":
*ts = Enabled
case "disabled":
*ts = Disabled
default:
return fmt.Errorf("unknown TaskStatus %s", s)
}
return nil
}
func (ts TaskStatus) String() string {
s, err := ts.MarshalText()
if err != nil {
return err.Error()
}
return string(s)
}
type Status int
const (
Failed Status = iota
Running
Finished
)
func (s Status) MarshalText() ([]byte, error) {
switch s {
case Failed:
return []byte("failed"), nil
case Running:
return []byte("running"), nil
case Finished:
return []byte("finished"), nil
default:
return nil, fmt.Errorf("unknown Status %d", s)
}
}
func (s *Status) UnmarshalText(text []byte) error {
switch t := string(text); t {
case "failed":
*s = Failed
case "running":
*s = Running
case "finished":
*s = Finished
default:
return fmt.Errorf("unknown Status %s", t)
}
return nil
}
func (s Status) String() string {
t, err := s.MarshalText()
if err != nil {
return err.Error()
}
return string(t)
}
type Clock int
const (
Fast Clock = iota
Real
)
func (c Clock) MarshalText() ([]byte, error) {
switch c {
case Fast:
return []byte("fast"), nil
case Real:
return []byte("real"), nil
default:
return nil, fmt.Errorf("unknown Clock %d", c)
}
}
func (c *Clock) UnmarshalText(text []byte) error {
switch s := string(text); s {
case "fast":
*c = Fast
case "real":
*c = Real
default:
return fmt.Errorf("unknown Clock %s", s)
}
return nil
}
func (c Clock) String() string {
s, err := c.MarshalText()
if err != nil {
return err.Error()
}
return string(s)
}
type VarType int
const (
VarUnknown VarType = iota
VarBool
VarInt
VarFloat
VarString
VarRegex
VarDuration
VarLambda
VarList
VarStar
)
func (vt VarType) MarshalText() ([]byte, error) {
switch vt {
case VarBool:
return []byte("bool"), nil
case VarInt:
return []byte("int"), nil
case VarFloat:
return []byte("float"), nil
case VarString:
return []byte("string"), nil
case VarRegex:
return []byte("regex"), nil
case VarDuration:
return []byte("duration"), nil
case VarLambda:
return []byte("lambda"), nil
case VarList:
return []byte("list"), nil
case VarStar:
return []byte("star"), nil
default:
return nil, fmt.Errorf("unknown VarType %d", vt)
}
}
func (vt *VarType) UnmarshalText(text []byte) error {
switch s := string(text); s {
case "bool":
*vt = VarBool
case "int":
*vt = VarInt
case "float":
*vt = VarFloat
case "string":
*vt = VarString
case "regex":
*vt = VarRegex
case "duration":
*vt = VarDuration
case "lambda":
*vt = VarLambda
case "list":
*vt = VarList
case "star":
*vt = VarStar
default:
return fmt.Errorf("unknown VarType %s", s)
}
return nil
}
func (vt VarType) String() string {
s, err := vt.MarshalText()
if err != nil {
return err.Error()
}
return string(s)
}
type Vars map[string]Var
func (vs *Vars) UnmarshalJSON(b []byte) error {
dec := json.NewDecoder(bytes.NewReader(b))
dec.UseNumber()
data := make(map[string]Var)
err := dec.Decode(&data)
if err != nil {
return err
}
*vs = make(Vars)
for name, v := range data {
if v.Value != nil {
switch v.Type {
case VarDuration:
switch value := v.Value.(type) {
case json.Number:
i, err := value.Int64()
if err != nil {
return errors.Wrapf(err, "invalid var %v", v)
}
v.Value = time.Duration(i)
case string:
d, err := influxql.ParseDuration(value)
if err != nil {
return errors.Wrapf(err, "invalid duration string for var %s", v)
}
v.Value = d
default:
return fmt.Errorf("invalid var %v: expected int or string value", v)
}
case VarInt:
n, ok := v.Value.(json.Number)
if !ok {
return fmt.Errorf("invalid var %v: expected int value", v)
}
v.Value, err = n.Int64()
if err != nil {
return errors.Wrapf(err, "invalid var %v", v)
}
case VarFloat:
n, ok := v.Value.(json.Number)
if !ok {
return fmt.Errorf("invalid var %v: expected float value", v)
}
v.Value, err = n.Float64()
if err != nil {
return errors.Wrapf(err, "invalid var %v", v)
}
case VarList:
values, ok := v.Value.([]interface{})
if !ok {
return fmt.Errorf("invalid var %v: expected list of vars", v)
}
vars := make([]Var, len(values))
for i := range values {
m, ok := values[i].(map[string]interface{})
if !ok {
return fmt.Errorf("invalid var %v: expected list of vars", v)
}
if typeText, ok := m["type"]; ok {
err := vars[i].Type.UnmarshalText([]byte(typeText.(string)))
if err != nil {
return err
}
} else {
return fmt.Errorf("invalid var %v: expected list type key in object", v)
}
if value, ok := m["value"]; ok {
vars[i].Value = value
} else {
return fmt.Errorf("invalid var %v: expected list value key in object", v)
}
}
v.Value = vars
}
}
(*vs)[name] = v
}
return nil
}
type Var struct {
Type VarType `json:"type" yaml:"type"`
Value interface{} `json:"value" yaml:"value"`
Description string `json:"description" yaml:"description"`
}
// A Task plus its read-only attributes.
type Task struct {
Link Link `json:"link"`
ID string `json:"id"`
TemplateID string `json:"template-id"`
Type TaskType `json:"type"`
DBRPs []DBRP `json:"dbrps"`
TICKscript string `json:"script"`
Vars Vars `json:"vars"`
Dot string `json:"dot"`
Status TaskStatus `json:"status"`
Executing bool `json:"executing"`
Error string `json:"error"`
ExecutionStats ExecutionStats `json:"stats"`
Created time.Time `json:"created"`
Modified time.Time `json:"modified"`
LastEnabled time.Time `json:"last-enabled,omitempty"`
}
// A Template plus its read-only attributes.
type Template struct {
Link Link `json:"link"`
ID string `json:"id"`
Type TaskType `json:"type"`
TICKscript string `json:"script"`
Vars Vars `json:"vars"`
Dot string `json:"dot"`
Error string `json:"error"`
Created time.Time `json:"created"`
Modified time.Time `json:"modified"`
}
// Information about a recording.
type Recording struct {
Link Link `json:"link"`
ID string `json:"id"`
Type TaskType `json:"type"`
Size int64 `json:"size"`
Date time.Time `json:"date"`
Error string `json:"error"`
Status Status `json:"status"`
Progress float64 `json:"progress"`
}
// Information about a replay.
type Replay struct {
Link Link `json:"link"`
ID string `json:"id"`
Task string `json:"task"`
Recording string `json:"recording"`
RecordingTime bool `json:"recording-time"`
Clock Clock `json:"clock"`
Date time.Time `json:"date"`
Error string `json:"error"`
Status Status `json:"status"`
Progress float64 `json:"progress"`
ExecutionStats ExecutionStats `json:"stats,omitempty"`
}
type JSONOperation struct {
Path string `json:"path"`
Operation string `json:"op"`
Value interface{} `json:"value"`
From string `json:"from,omitempty"`
}
type JSONPatch []JSONOperation
func (c *Client) URL() string {
return c.url.String()
}
func (c *Client) BaseURL() url.URL {
return *c.url
}
func (c *Client) prepRequest(req *http.Request) error {
req.Header.Set("User-Agent", c.userAgent)
if c.credentials != nil {
switch c.credentials.Method {
case UserAuthentication:
req.SetBasicAuth(c.credentials.Username, c.credentials.Password)
case BearerAuthentication:
req.Header.Set("Authorization", "Bearer "+c.credentials.Token)
default:
return errors.New("unknown authentication method set")
}
}
return nil
}
func (c *Client) decodeError(resp *http.Response) error {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
type errResp struct {
Error string `json:"error"`
}
d := json.NewDecoder(bytes.NewReader(body))
rp := errResp{}
d.Decode(&rp)
if rp.Error != "" {
return errors.New(rp.Error)
}
return fmt.Errorf("invalid response: code %d: body: %s", resp.StatusCode, string(body))
}
// Perform the request.
// If result is not nil the response body is JSON decoded into result.
// Codes is a list of valid response codes.
func (c *Client) Do(req *http.Request, result interface{}, codes ...int) (*http.Response, error) {
err := c.prepRequest(req)
if err != nil {
return nil, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
valid := false
for _, code := range codes {
if resp.StatusCode == code {
valid = true
break
}
}
if !valid {
return nil, c.decodeError(resp)
}
if result != nil {
d := json.NewDecoder(resp.Body)
err := d.Decode(result)
if err != nil {
return nil, fmt.Errorf("failed to decode JSON: %v", err)
}
}
return resp, nil
}
func (c *Client) Logs(ctx context.Context, w io.Writer, q map[string]string) error {
u := c.BaseURL()
u.Path = logsPath
qp := u.Query()
for k, v := range q {
qp.Add(k, v)
}
u.RawQuery = qp.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
err = c.prepRequest(req)
if err != nil {
return err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
return fmt.Errorf("bad status code %v", resp.StatusCode)
}
errCh := make(chan error, 1)
defer close(errCh)
go func() {
_, err := io.Copy(w, resp.Body)
errCh <- err
}()
select {
case <-ctx.Done():
return nil
case err := <-errCh:
return err
}
}
// Ping the server for a response.
// Ping returns how long the request took, the version of the server it connected to, and an error if one occurred.
func (c *Client) Ping() (time.Duration, string, error) {
now := time.Now()
u := *c.url
u.Path = pingPath
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return 0, "", err
}
resp, err := c.Do(req, nil, http.StatusNoContent)
if err != nil {
return 0, "", err
}
version := resp.Header.Get("X-Kapacitor-Version")
return time.Since(now), version, nil
}
func (c *Client) TaskLink(id string) Link {
return Link{Relation: Self, Href: path.Join(tasksPath, id)}
}
func (c *Client) TemplateLink(id string) Link {
return Link{Relation: Self, Href: path.Join(templatesPath, id)}
}
func (c *Client) ConfigSectionLink(section string) Link {
return Link{Relation: Self, Href: path.Join(configPath, section)}
}
func (c *Client) ConfigElementLink(section, element string) Link {
href := path.Join(configPath, section, element)
if element == "" {
href += "/"
}
return Link{Relation: Self, Href: href}
}
func (c *Client) ServiceTestLink(service string) Link {
return Link{Relation: Self, Href: path.Join(serviceTestsPath, service)}
}
func (c *Client) TopicLink(id string) Link {
return Link{Relation: Self, Href: path.Join(topicsPath, id)}
}
func (c *Client) TopicEventsLink(topic string) Link {
return Link{Relation: Self, Href: path.Join(topicsPath, topic, topicEventsPath)}
}
func (c *Client) TopicEventLink(topic, event string) Link {
return Link{Relation: Self, Href: path.Join(topicsPath, topic, topicEventsPath, event)}
}
func (c *Client) TopicHandlersLink(topic string) Link {
return Link{Relation: Self, Href: path.Join(topicsPath, topic, topicHandlersPath)}
}
func (c *Client) TopicHandlerLink(topic, id string) Link {
return Link{Relation: Self, Href: path.Join(topicsPath, topic, topicHandlersPath, id)}
}
func (c *Client) StorageLink(name string) Link {
return Link{Relation: Self, Href: path.Join(storesPath, name)}
}
type CreateTaskOptions struct {
ID string `json:"id,omitempty" yaml:"id"`
TemplateID string `json:"template-id,omitempty" yaml:"template-id"`
Type TaskType `json:"type,omitempty"`
DBRPs []DBRP `json:"dbrps,omitempty" yaml:"dbrps"`
TICKscript string `json:"script,omitempty"`
Status TaskStatus `json:"status,omitempty"`
Vars Vars `json:"vars,omitempty" yaml:"vars"`
}
// Create a new task.
// Errors if the task already exists.
func (c *Client) CreateTask(opt CreateTaskOptions) (Task, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
err := enc.Encode(opt)
if err != nil {
return Task{}, err
}
u := *c.url
u.Path = tasksPath
req, err := http.NewRequest("POST", u.String(), &buf)
if err != nil {
return Task{}, err
}
req.Header.Set("Content-Type", "application/json")
t := Task{}
_, err = c.Do(req, &t, http.StatusOK)
return t, err
}
type UpdateTaskOptions struct {
ID string `json:"id,omitempty" yaml:"id"`
TemplateID string `json:"template-id,omitempty" yaml:"template-id"`
Type TaskType `json:"type,omitempty"`
DBRPs []DBRP `json:"dbrps,omitempty" yaml:"dbrps"`
TICKscript string `json:"script,omitempty"`
Status TaskStatus `json:"status,omitempty"`
Vars Vars `json:"vars,omitempty" yaml:"vars"`
}
// Update an existing task.
// Only fields that are not their default value will be updated.
func (c *Client) UpdateTask(link Link, opt UpdateTaskOptions) (Task, error) {
t := Task{}
if link.Href == "" {
return t, fmt.Errorf("invalid link %v", link)
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
err := enc.Encode(opt)
if err != nil {
return t, err
}
u := *c.url
u.Path = link.Href
req, err := http.NewRequest("PATCH", u.String(), &buf)
if err != nil {
return t, err
}
req.Header.Set("Content-Type", "application/json")
_, err = c.Do(req, &t, http.StatusOK)
if err != nil {
return t, err
}
return t, nil
}
type TaskOptions struct {
DotView string
ScriptFormat string
ReplayID string
}
func (o *TaskOptions) Default() {
if o.DotView == "" {
o.DotView = "attributes"
}
if o.ScriptFormat == "" {
o.ScriptFormat = "formatted"
}
}
func (o *TaskOptions) Values() *url.Values {
v := &url.Values{}
v.Set("dot-view", o.DotView)
v.Set("script-format", o.ScriptFormat)
v.Set("replay-id", o.ReplayID)
return v
}
// Get information about a task.
// Options can be nil and the default options will be used.
// By default the DOT content will use attributes for stats. Use DotView="labels" to generate a purley labels based DOT content, which can accurately be rendered but is less readable.
// By default the TICKscript contents are formatted, use ScriptFormat="raw" to return the TICKscript unmodified.
func (c *Client) Task(link Link, opt *TaskOptions) (Task, error) {
task := Task{}
if link.Href == "" {
return task, fmt.Errorf("invalid link %v", link)
}
if opt == nil {
opt = new(TaskOptions)
}
opt.Default()
u := *c.url
u.Path = link.Href
u.RawQuery = opt.Values().Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return task, err
}
_, err = c.Do(req, &task, http.StatusOK)
if err != nil {
return task, err
}
return task, nil
}
// Delete a task.
func (c *Client) DeleteTask(link Link) error {
if link.Href == "" {
return fmt.Errorf("invalid link %v", link)
}
u := *c.url
u.Path = link.Href
req, err := http.NewRequest("DELETE", u.String(), nil)
if err != nil {
return err
}
_, err = c.Do(req, nil, http.StatusNoContent)
return err
}
type ListTasksOptions struct {
TaskOptions
Pattern string
Fields []string
Offset int
Limit int
}
func (o *ListTasksOptions) Default() {
o.TaskOptions.Default()
if o.Limit == 0 {
o.Limit = 100
}
}
func (o *ListTasksOptions) Values() *url.Values {
v := o.TaskOptions.Values()
v.Set("pattern", o.Pattern)
for _, field := range o.Fields {
v.Add("fields", field)
}
v.Set("offset", strconv.FormatInt(int64(o.Offset), 10))
v.Set("limit", strconv.FormatInt(int64(o.Limit), 10))
return v
}
// Get tasks.
func (c *Client) ListTasks(opt *ListTasksOptions) ([]Task, error) {
if opt == nil {
opt = new(ListTasksOptions)
}
opt.Default()
u := *c.url
u.Path = tasksPath
u.RawQuery = opt.Values().Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
// Response type
type response struct {
Tasks []Task `json:"tasks"`
}