-
Notifications
You must be signed in to change notification settings - Fork 489
/
Copy pathmain.go
2207 lines (1926 loc) · 55.1 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"sort"
"strconv"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/ghodss/yaml"
"github.com/influxdata/influxdb/influxql"
"github.com/influxdata/kapacitor/client/v1"
"github.com/pkg/errors"
)
// These variables are populated via the Go linker.
var (
version string
commit string
branch string
)
var defaultURL = "http://localhost:9092"
var defaultSkipVerify = false
var mainFlags = flag.NewFlagSet("main", flag.ExitOnError)
var kapacitordURL = mainFlags.String("url", "", "The URL http(s)://host:port of the kapacitord server. Defaults to the KAPACITOR_URL environment variable or "+defaultURL+" if not set.")
var skipVerify = mainFlags.Bool("skipVerify", false, "Disable SSL verification (note, this is insecure). Defaults to the KAPACITOR_UNSAFE_SSL environment variable or "+strconv.FormatBool(defaultSkipVerify)+" if not set.")
var l = log.New(os.Stderr, "[run] ", log.LstdFlags)
var cli *client.Client
var usageStr = `
Usage: kapacitor [options] [command] [args]
Commands:
record Record the result of a query or a snapshot of the current stream data.
define Create/update a task.
define-template Create/update a template.
define-topic-handler Create/update an alert handler for a topic.
replay Replay a recording to a task.
replay-live Replay data against a task without recording it.
enable Enable and start running a task with live data.
disable Stop running a task.
reload Reload a running task with an updated task definition.
push Publish a task definition to another Kapacitor instance. Not implemented yet.
delete Delete tasks, templates, recordings, replays, topics or topic-handlers.
list List information about tasks, templates, recordings, replays, topics, topic-handlers or service-tests.
show Display detailed information about a task.
show-template Display detailed information about a template.
show-topic-handler Display detailed information about an alert handler for a topic.
show-topic Display detailed information about an alert topic.
level Sets the logging level on the kapacitord server.
stats Display various stats about Kapacitor.
version Displays the Kapacitor version info.
vars Print debug vars in JSON format.
service-tests Test a service.
help Prints help for a command.
Options:
`
func usage() {
fmt.Fprintln(os.Stderr, usageStr)
mainFlags.PrintDefaults()
os.Exit(1)
}
func main() {
mainFlags.Parse(os.Args[1:])
skipSSL := defaultSkipVerify
if skipVerifyEnv := os.Getenv("KAPACITOR_UNSAFE_SSL"); skipVerifyEnv != "" {
var err error
skipSSL, err = strconv.ParseBool(skipVerifyEnv)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
if *skipVerify != false {
skipSSL = *skipVerify
}
url := defaultURL
if urlEnv := os.Getenv("KAPACITOR_URL"); urlEnv != "" {
url = urlEnv
}
if *kapacitordURL != "" {
url = *kapacitordURL
}
var err error
cli, err = connect(url, skipSSL)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(4)
}
args := mainFlags.Args()
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "Error: Must pass a command.")
usage()
}
command := args[0]
args = args[1:]
var commandF func(args []string) error
var commandArgs []string
switch command {
case "help":
commandArgs = args
commandF = doHelp
case "record":
if len(args) == 0 {
recordUsage()
os.Exit(2)
}
commandArgs = args
commandF = doRecord
case "define":
commandArgs = args
commandF = doDefine
case "define-template":
commandArgs = args
commandF = doDefineTemplate
case "define-topic-handler":
commandArgs = args
commandF = doDefineTopicHandler
case "replay":
replayFlags.Parse(args)
commandArgs = replayFlags.Args()
commandF = doReplay
case "replay-live":
if len(args) == 0 {
replayLiveUsage()
os.Exit(2)
}
commandArgs = args
commandF = doReplayLive
case "enable":
commandArgs = args
commandF = doEnable
case "disable":
commandArgs = args
commandF = doDisable
case "reload":
commandArgs = args
commandF = doReload
case "delete":
commandArgs = args
commandF = doDelete
case "list":
commandArgs = args
commandF = doList
case "show":
showFlags.Parse(args)
commandArgs = showFlags.Args()
commandF = doShow
case "show-template":
commandArgs = args
commandF = doShowTemplate
case "show-topic-handler":
commandArgs = args
commandF = doShowTopicHandler
case "show-topic":
commandArgs = args
commandF = doShowTopic
case "level":
commandArgs = args
commandF = doLevel
case "stats":
commandArgs = args
commandF = doStats
case "version":
commandArgs = args
commandF = doVersion
case "vars":
commandArgs = args
commandF = doVars
case "service-tests":
commandArgs = args
commandF = doServiceTest
default:
fmt.Fprintln(os.Stderr, "Unknown command", command)
usage()
}
err = commandF(commandArgs)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(3)
}
}
// Init flag sets
func init() {
replayFlags.Usage = replayUsage
defineFlags.Usage = defineUsage
defineTemplateFlags.Usage = defineTemplateUsage
showFlags.Usage = showUsage
recordStreamFlags.Usage = recordStreamUsage
recordBatchFlags.Usage = recordBatchUsage
recordQueryFlags.Usage = recordQueryUsage
replayLiveBatchFlags.Usage = replayLiveBatchUsage
replayLiveQueryFlags.Usage = replayLiveQueryUsage
}
// helper methods
type responseError struct {
Err string `json:"Error"`
}
func (e responseError) Error() string {
return e.Err
}
func connect(url string, skipSSL bool) (*client.Client, error) {
return client.New(client.Config{
URL: url,
InsecureSkipVerify: skipSSL,
})
}
// Help
func helpUsage() {
var u = "Usage: kapacitor help [command]\n"
fmt.Fprintln(os.Stderr, u)
}
func doHelp(args []string) error {
if len(args) == 1 {
command := args[0]
switch command {
case "record":
recordUsage()
case "define":
defineFlags.Usage()
case "define-template":
defineTemplateFlags.Usage()
case "define-topic-handler":
defineTopicHandlerUsage()
case "replay":
replayFlags.Usage()
case "enable":
enableUsage()
case "disable":
disableUsage()
case "reload":
reloadUsage()
case "delete":
deleteUsage()
case "list":
listUsage()
case "show":
showUsage()
case "show-template":
showTemplateUsage()
case "show-topic-handler":
showTopicHandlerUsage()
case "show-topic":
showTopicUsage()
case "level":
levelUsage()
case "help":
helpUsage()
case "stats":
statsUsage()
case "version":
versionUsage()
case "vars":
varsUsage()
case "service-tests":
varsUsage()
default:
fmt.Fprintln(os.Stderr, "Unknown command", command)
usage()
}
} else {
helpUsage()
usage()
}
return nil
}
// Record
var (
recordStreamFlags = flag.NewFlagSet("record-stream", flag.ExitOnError)
rsTask = recordStreamFlags.String("task", "", "The ID of a task. Uses the dbrp value for the task.")
rsDur = recordStreamFlags.String("duration", "", "How long to record the data stream.")
rsNowait = recordStreamFlags.Bool("no-wait", false, "Do not wait for the recording to finish.")
rsId = recordStreamFlags.String("recording-id", "", "The ID to give to this recording. If not set an random ID is chosen.")
recordBatchFlags = flag.NewFlagSet("record-batch", flag.ExitOnError)
rbTask = recordBatchFlags.String("task", "", "The ID of a task. Uses the queries contained in the task.")
rbStart = recordBatchFlags.String("start", "", "The start time for the set of queries.")
rbStop = recordBatchFlags.String("stop", "", "The stop time for the set of queries (default now).")
rbPast = recordBatchFlags.String("past", "", "Set start time via 'now - past'.")
rbNowait = recordBatchFlags.Bool("no-wait", false, "Do not wait for the recording to finish.")
rbId = recordBatchFlags.String("recording-id", "", "The ID to give to this recording. If not set an random ID is chosen.")
recordQueryFlags = flag.NewFlagSet("record-query", flag.ExitOnError)
rqQuery = recordQueryFlags.String("query", "", "The query to record.")
rqType = recordQueryFlags.String("type", "", "The type of the recording to save (stream|batch).")
rqCluster = recordQueryFlags.String("cluster", "", "Optional named InfluxDB cluster from configuration.")
rqNowait = recordQueryFlags.Bool("no-wait", false, "Do not wait for the recording to finish.")
rqId = recordQueryFlags.String("recording-id", "", "The ID to give to this recording. If not set an random ID is chosen.")
)
func recordUsage() {
var u = `Usage: kapacitor record [batch|stream|query] [options]
Record the result of a InfluxDB query or a snapshot of the live data stream.
Prints the recording ID on exit.
See 'kapacitor help replay' for how to replay a recording.
`
fmt.Fprintln(os.Stderr, u)
}
func recordStreamUsage() {
var u = `Usage: kapacitor record stream [options]
Record a snapshot of the live data stream.
Prints the recording ID on exit.
See 'kapacitor help replay' for how to replay a recording.
Examples:
$ kapacitor record stream -task mem_free -duration 1m
This records the live data stream for 1 minute using the databases and retention policies
from the named task.
Options:
`
fmt.Fprintln(os.Stderr, u)
recordStreamFlags.PrintDefaults()
}
func recordBatchUsage() {
var u = `Usage: kapacitor record batch [options]
Record the result of a InfluxDB query from a task.
Prints the recording ID on exit.
See 'kapacitor help replay' for how to replay a recording.
Examples:
$ kapacitor record batch -task cpu_idle -start 2015-09-01T00:00:00Z -stop 2015-09-02T00:00:00Z
This records the result of the query defined in task 'cpu_idle' and runs the query
until the queries reaches the stop time, starting at time 'start' and incrementing
by the schedule defined in the task.
$ kapacitor record batch -task cpu_idle -past 10h
This records the result of the query defined in task 'cpu_idle' and runs the query
until the queries reaches the present time.
The starting time for the queries is 'now - 10h' and increments by the schedule defined in the task.
Options:
`
fmt.Fprintln(os.Stderr, u)
recordBatchFlags.PrintDefaults()
}
func recordQueryUsage() {
var u = `Usage: kapacitor record query [options]
Record the result of a InfluxDB query.
Prints the recording ID on exit.
Recordings have types like tasks. you must specify the desired type.
See 'kapacitor help replay' for how to replay a recording.
Examples:
$ kapacitor record query -query 'select value from "telegraf"."default"."cpu_idle" where time > now() - 1h and time < now()' -type stream
This records the result of the query and stores it as a stream recording. Use '-type batch' to store as batch recording.
Options:
`
fmt.Fprintln(os.Stderr, u)
recordQueryFlags.PrintDefaults()
}
func doRecord(args []string) error {
var recording client.Recording
var err error
noWait := false
switch args[0] {
case "stream":
recordStreamFlags.Parse(args[1:])
if *rsTask == "" || *rsDur == "" {
recordStreamFlags.Usage()
return errors.New("both task and duration are required")
}
var duration time.Duration
duration, err = influxql.ParseDuration(*rsDur)
if err != nil {
return err
}
noWait = *rsNowait
recording, err = cli.RecordStream(client.RecordStreamOptions{
ID: *rsId,
Task: *rsTask,
Stop: time.Now().Add(duration),
})
if err != nil {
return err
}
case "batch":
recordBatchFlags.Parse(args[1:])
if *rbTask == "" {
recordBatchFlags.Usage()
return errors.New("task is required")
}
if *rbStart == "" && *rbPast == "" {
recordBatchFlags.Usage()
return errors.New("must set one of start or past flags.")
}
if *rbStart != "" && *rbPast != "" {
recordBatchFlags.Usage()
return errors.New("cannot set both start and past flags.")
}
start, stop := time.Time{}, time.Now()
if *rbStart != "" {
start, err = time.Parse(time.RFC3339Nano, *rbStart)
if err != nil {
return err
}
}
if *rbStop != "" {
stop, err = time.Parse(time.RFC3339Nano, *rbStop)
if err != nil {
return err
}
}
if *rbPast != "" {
past, err := influxql.ParseDuration(*rbPast)
if err != nil {
return err
}
start = stop.Add(-1 * past)
}
noWait = *rbNowait
recording, err = cli.RecordBatch(client.RecordBatchOptions{
ID: *rbId,
Task: *rbTask,
Start: start,
Stop: stop,
})
if err != nil {
return err
}
case "query":
recordQueryFlags.Parse(args[1:])
if *rqQuery == "" || *rqType == "" {
recordQueryFlags.Usage()
return errors.New("both query and type are required")
}
var typ client.TaskType
switch *rqType {
case "stream":
typ = client.StreamTask
case "batch":
typ = client.BatchTask
}
noWait = *rqNowait
recording, err = cli.RecordQuery(client.RecordQueryOptions{
ID: *rqId,
Query: *rqQuery,
Type: typ,
Cluster: *rqCluster,
})
if err != nil {
return err
}
default:
return fmt.Errorf("Unknown record type %q, expected 'stream', 'batch' or 'query'", args[0])
}
if noWait {
fmt.Println(recording.ID)
return nil
}
for recording.Status == client.Running {
time.Sleep(500 * time.Millisecond)
recording, err = cli.Recording(recording.Link)
if err != nil {
return err
}
}
fmt.Println(recording.ID)
if recording.Status == client.Failed {
if recording.Error == "" {
recording.Error = "recording failed: unknown reason"
}
return errors.New(recording.Error)
}
return nil
}
// Define
var (
defineFlags = flag.NewFlagSet("define", flag.ExitOnError)
dtick = defineFlags.String("tick", "", "Path to the TICKscript")
dtype = defineFlags.String("type", "", "The task type (stream|batch)")
dtemplate = defineFlags.String("template", "", "Optional template ID")
dvars = defineFlags.String("vars", "", "Optional path to a JSON vars file")
dnoReload = defineFlags.Bool("no-reload", false, "Do not reload the task even if it is enabled")
ddbrp = make(dbrps, 0)
)
func init() {
defineFlags.Var(&ddbrp, "dbrp", `A database and retention policy pair of the form "db"."rp" the quotes are optional. The flag can be specified multiple times.`)
}
type dbrps []client.DBRP
func (d *dbrps) String() string {
return fmt.Sprint(*d)
}
// Parse string of the form "db"."rp" where the quotes are optional but can include escaped quotes
// within the strings.
func (d *dbrps) Set(value string) error {
dbrp := client.DBRP{}
if len(value) == 0 {
return errors.New("dbrp cannot be empty")
}
var n int
if value[0] == '"' {
dbrp.Database, n = parseQuotedStr(value)
} else {
n = strings.IndexRune(value, '.')
if n == -1 {
return errors.New("does not contain a '.', it must be in the form \"dbname\".\"rpname\" where the quotes are optional.")
}
dbrp.Database = value[:n]
}
if value[n] != '.' {
return errors.New("dbrp must specify retention policy, do you have a missing or extra '.'?")
}
value = value[n+1:]
if value[0] == '"' {
dbrp.RetentionPolicy, _ = parseQuotedStr(value)
} else {
dbrp.RetentionPolicy = value
}
*d = append(*d, dbrp)
return nil
}
// parseQuotedStr reads from txt starting with beginning quote until next unescaped quote returning the unescaped string and the number of bytes read.
func parseQuotedStr(txt string) (string, int) {
quote := txt[0]
// Unescape quotes
var buf bytes.Buffer
buf.Grow(len(txt))
last := 1
i := 1
for ; i < len(txt)-1; i++ {
if txt[i] == '\\' && txt[i+1] == quote {
buf.Write([]byte(txt[last:i]))
buf.Write([]byte{quote})
i += 2
last = i
} else if txt[i] == quote {
break
}
}
buf.Write([]byte(txt[last:i]))
return buf.String(), i + 1
}
func defineUsage() {
var u = `Usage: kapacitor define <task ID> [options]
Create or update a task.
A task is defined via a TICKscript that defines the data processing pipeline of the task.
If an option is absent it will be left unmodified.
If the task is enabled then it will be reloaded unless -no-reload is specified.
For example:
You must define a task for the first time with all the flags.
$ kapacitor define my_task -tick path/to/TICKscript -type stream -dbrp mydb.myrp
Later you can change a single property of the task by referencing its name
and only providing the single option you wish to modify.
$ kapacitor define my_task -tick path/to/TICKscript
or
$ kapacitor define my_task -dbrp mydb.myrp -dbrp otherdb.default
NOTE: you must specify all 'dbrp' flags you desire if you wish to modify them.
Options:
`
fmt.Fprintln(os.Stderr, u)
defineFlags.PrintDefaults()
}
func doDefine(args []string) error {
if len(args) < 1 {
fmt.Fprintln(os.Stderr, "Must provide a task ID.")
defineFlags.Usage()
os.Exit(2)
}
defineFlags.Parse(args[1:])
id := args[0]
var script string
if *dtick != "" {
file, err := os.Open(*dtick)
if err != nil {
return err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
script = string(data)
}
var ttype client.TaskType
switch *dtype {
case "stream":
ttype = client.StreamTask
case "batch":
ttype = client.BatchTask
}
vars := make(client.Vars)
if *dvars != "" {
f, err := os.Open(*dvars)
if err != nil {
return errors.Wrapf(err, "faild to open file %s", *dvars)
}
defer f.Close()
dec := json.NewDecoder(f)
if err := dec.Decode(&vars); err != nil {
return errors.Wrapf(err, "invalid JSON in file %s", *dvars)
}
}
l := cli.TaskLink(id)
task, _ := cli.Task(l, nil)
var err error
if task.ID == "" {
_, err = cli.CreateTask(client.CreateTaskOptions{
ID: id,
TemplateID: *dtemplate,
Type: ttype,
DBRPs: ddbrp,
TICKscript: script,
Vars: vars,
Status: client.Disabled,
})
} else {
_, err = cli.UpdateTask(
l,
client.UpdateTaskOptions{
TemplateID: *dtemplate,
Type: ttype,
DBRPs: ddbrp,
TICKscript: script,
Vars: vars,
},
)
}
if err != nil {
return err
}
if !*dnoReload && task.Status == client.Enabled {
_, err := cli.UpdateTask(l, client.UpdateTaskOptions{Status: client.Disabled})
if err != nil {
return err
}
_, err = cli.UpdateTask(l, client.UpdateTaskOptions{Status: client.Enabled})
if err != nil {
return err
}
}
return nil
}
// DefineTemplate
var (
defineTemplateFlags = flag.NewFlagSet("define-template", flag.ExitOnError)
dtTick = defineTemplateFlags.String("tick", "", "Path to the TICKscript")
dtType = defineTemplateFlags.String("type", "", "The template type (stream|batch)")
)
func defineTemplateUsage() {
var u = `Usage: kapacitor define-template <template ID> [options]
Create or update a template.
A template is defined via a TICKscript that defines the data processing pipeline of the template.
If an option is absent it will be left unmodified.
NOTE: Updating a template will reload all associated tasks.
For example:
You must define a template for the first time with all the flags.
$ kapacitor define-template my_template -tick path/to/TICKscript -type stream
Later you can change a single property of the template by referencing its name
and only providing the single option you wish to modify.
$ kapacitor define-template my_template -tick path/to/TICKscript
or
$ kapacitor define-template my_template -type batch
Options:
`
fmt.Fprintln(os.Stderr, u)
defineTemplateFlags.PrintDefaults()
}
func doDefineTemplate(args []string) error {
if len(args) < 1 {
fmt.Fprintln(os.Stderr, "Must provide a template ID.")
defineTemplateFlags.Usage()
os.Exit(2)
}
defineTemplateFlags.Parse(args[1:])
id := args[0]
var script string
if *dtTick != "" {
file, err := os.Open(*dtTick)
if err != nil {
return err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
script = string(data)
}
var ttype client.TaskType
switch *dtType {
case "stream":
ttype = client.StreamTask
case "batch":
ttype = client.BatchTask
}
l := cli.TemplateLink(id)
template, _ := cli.Template(l, nil)
var err error
if template.ID == "" {
_, err = cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: script,
})
} else {
_, err = cli.UpdateTemplate(
l,
client.UpdateTemplateOptions{
Type: ttype,
TICKscript: script,
},
)
}
return err
}
func defineTopicHandlerUsage() {
var u = `Usage: kapacitor define-topic-handler <topic id> <handler id> <path to handler spec file>
Create or update a handler.
A handler is defined via a JSON or YAML file.
For example:
Define a handler using the slack.yaml file:
$ kapacitor define-handler system my_handler slack.yaml
Options:
`
fmt.Fprintln(os.Stderr, u)
}
func doDefineTopicHandler(args []string) error {
if len(args) != 3 {
fmt.Fprintln(os.Stderr, "Must provide a topic ID, a handler ID and a path to a handler file.")
defineTopicHandlerUsage()
os.Exit(2)
}
topic := args[0]
handlerID := args[1]
p := args[2]
f, err := os.Open(p)
if err != nil {
return errors.Wrapf(err, "failed to open handler spec file %q", p)
}
// Decode file into HandlerOptions
var ho client.TopicHandlerOptions
ext := path.Ext(p)
switch ext {
case ".yaml":
data, err := ioutil.ReadAll(f)
if err != nil {
return errors.Wrapf(err, "failed to read handler file %q", p)
}
if err := yaml.Unmarshal(data, &ho); err != nil {
return errors.Wrapf(err, "failed to unmarshal yaml handler file %q", p)
}
case ".json":
if err := json.NewDecoder(f).Decode(&ho); err != nil {
return errors.Wrapf(err, "failed to unmarshal json handler file %q", p)
}
}
ho.ID = handlerID
l := cli.TopicHandlerLink(topic, ho.ID)
handler, _ := cli.TopicHandler(l)
if handler.ID == "" {
_, err = cli.CreateTopicHandler(cli.TopicHandlersLink(topic), ho)
} else {
_, err = cli.ReplaceTopicHandler(l, ho)
}
return err
}
// Replay
var (
replayFlags = flag.NewFlagSet("replay", flag.ExitOnError)
rtask = replayFlags.String("task", "", "The task ID.")
rrecording = replayFlags.String("recording", "", "The recording ID.")
rreal = replayFlags.Bool("real-clock", false, "If set, replay the data in real time. If not set replay data as fast as possible.")
rrec = replayFlags.Bool("rec-time", false, "If set, use the times saved in the recording instead of present times.")
rnowait = replayFlags.Bool("no-wait", false, "Do not wait for the replay to finish.")
rid = replayFlags.String("replay-id", "", "The ID to give to this replay. If not set a random ID is chosen.")
)
func replayUsage() {
var u = `Usage: kapacitor replay [options]
Replay a recording to a task. Prints the replay ID.
The times of the data points will either be relative to now or the exact times
in the recording if the '-rec-time' flag is set. In either case the relative times
between the data points remains the same.
See 'kapacitor help record' for how to create a replay.
See 'kapacitor help define' for how to create a task.
Options:
`
fmt.Fprintln(os.Stderr, u)
replayFlags.PrintDefaults()
}
func doReplay(args []string) error {
if *rrecording == "" {
replayUsage()
return errors.New("must pass recording ID")
}
if *rtask == "" {
replayUsage()
return errors.New("must pass task ID")
}
clk := client.Fast
if *rreal {
clk = client.Real
}
replay, err := cli.CreateReplay(client.CreateReplayOptions{
ID: *rid,
Task: *rtask,
Recording: *rrecording,
RecordingTime: *rrec,
Clock: clk,
})
if err != nil {
return err
}
if *rnowait {
fmt.Println(replay.ID)
return nil
}
for replay.Status == client.Running {
time.Sleep(500 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
return err
}
}
fmt.Println(replay.ID)
if replay.Status == client.Failed {
if replay.Error == "" {
replay.Error = "replay failed: unknown reason"
}
return errors.New(replay.Error)
}
return nil
}
// Replay Live
var (
replayLiveBatchFlags = flag.NewFlagSet("replay-live-batch", flag.ExitOnError)
rlbTask = replayLiveBatchFlags.String("task", "", "The task ID.")
rlbReal = replayLiveBatchFlags.Bool("real-clock", false, "If set, replay the data in real time. If not set replay data as fast as possible.")
rlbRec = replayLiveBatchFlags.Bool("rec-time", false, "If set, use the times saved in the recording instead of present times.")
rlbNowait = replayLiveBatchFlags.Bool("no-wait", false, "Do not wait for the replay to finish.")
rlbId = replayLiveBatchFlags.String("replay-id", "", "The ID to give to this replay. If not set a random ID is chosen.")
rlbStart = replayLiveBatchFlags.String("start", "", "The start time for the set of queries.")
rlbStop = replayLiveBatchFlags.String("stop", "", "The stop time for the set of queries (default now).")
rlbPast = replayLiveBatchFlags.String("past", "", "Set start time via 'now - past'.")
replayLiveQueryFlags = flag.NewFlagSet("replay-live-query", flag.ExitOnError)
rlqTask = replayLiveQueryFlags.String("task", "", "The task ID.")
rlqReal = replayLiveQueryFlags.Bool("real-clock", false, "If set, replay the data in real time. If not set replay data as fast as possible.")
rlqRec = replayLiveQueryFlags.Bool("rec-time", false, "If set, use the times saved in the recording instead of present times.")
rlqNowait = replayLiveQueryFlags.Bool("no-wait", false, "Do not wait for the replay to finish.")
rlqId = replayLiveQueryFlags.String("replay-id", "", "The ID to give to this replay. If not set a random ID is chosen.")
rlqQuery = replayLiveQueryFlags.String("query", "", "The query to replay.")
rlqCluster = replayLiveQueryFlags.String("cluster", "", "Optional named InfluxDB cluster from configuration.")
)
func replayLiveUsage() {
var u = `Usage: kapacitor replay-live <batch|query> [options]
Replay data to a task directly without saving a recording.
The command is a hybrid of the 'kapacitor record batch|query' and 'kapacitor replay' commands.
See either 'kapacitor replay-live batch' or 'kapacitor replay-live query' for more details
`
fmt.Fprintln(os.Stderr, u)
}
func replayLiveBatchUsage() {
var u = `Usage: kapacitor replay-live batch [options]
Replay data from the queries in a batch task against the task.
This is similar to 'kapacitor record batch ...' but without saving a recording.
Examples:
$ kapacitor replay-live batch -task cpu_idle -start 2015-09-01T00:00:00Z -stop 2015-09-02T00:00:00Z
This replays the result of the query defined in task 'cpu_idle' and runs the query
until the queries reaches the stop time, starting at time 'start' and incrementing
by the schedule defined in the task.