-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcommands.go
More file actions
176 lines (152 loc) · 4.75 KB
/
Copy pathcommands.go
File metadata and controls
176 lines (152 loc) · 4.75 KB
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
/*
Copyright 2020–2021 MET Norway
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 main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/http"
"os/exec"
"time"
"github.com/metno/go-mms/pkg/mms"
"github.com/urfave/cli/v2"
)
func listAllEventsCmd(ctx *cli.Context) error {
events := []*mms.ProductEvent{}
if ctx.String("production-hub") == "" {
return fmt.Errorf("No production-hub specified")
}
url := ctx.String("production-hub") + "/api/v1/events"
newEvents, err := mms.ListProductEvents(url)
if err != nil {
return fmt.Errorf("failed to access events: %v", err)
}
events = append(events, newEvents...)
for _, event := range events {
fmt.Printf("Event: %+v\n", event)
}
return nil
}
func subscribeEventsCmd(ctx *cli.Context) error {
mmsClient, err := mms.NewNatsConsumerClient(ctx.String("production-hub"))
if err != nil {
return fmt.Errorf("one hub event subscription failed, ending: %v", err)
}
if ctx.String("command") != "None" {
callback := createExecutableCallback(ctx.String("command"), ctx.Bool("args"), ctx.String("product"))
mmsClient.WatchProductEvents(callback)
} else {
// Same as Aviso-echo
mmsClient.WatchProductEvents(productReceiver(ctx.String("product")))
}
return nil
}
func postEventCmd(ctx *cli.Context) error {
var err error
refTime := time.Now()
if ctx.String("reftime") != "now" {
refTime, err = time.Parse(time.RFC3339, ctx.String("reftime"))
if err != nil {
log.Println("Could not parse reftime")
log.Println("Please use RFC 3339 format:")
log.Println("- '2006-01-02T15:04:05Z' for UTC")
log.Println("- '2006-01-02T15:04:05+01:00' for other time zones")
log.Fatalf("Parser error: %v", err)
}
}
productEvent := mms.ProductEvent{
JobName: ctx.String("jobname"),
Product: ctx.String("product"),
ProductLocation: ctx.String("product-location"),
ProductionHub: ctx.String("production-hub"),
Counter: ctx.Int("counter"),
TotalCount: ctx.Int("ntotal"),
RefTime: refTime,
CreatedAt: time.Now(),
NextEventAt: time.Now().Add(time.Second * time.Duration(ctx.Int("event-interval"))),
}
if ctx.String("production-hub") == "" {
return fmt.Errorf("No production-hub specified")
}
url := ctx.String("production-hub") + "/api/v1/events"
// Create a json-payload from productEvent
jsonStr, err := json.Marshal(&productEvent)
// Create a http-request to post the payload
httpReq, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
httpReq.Header.Set("Api-Key", ctx.String("api-key"))
httpReq.Header.Set("Content-Type", "application/json")
// Create a http connection to the api.
var tr *http.Transport
if ctx.Bool("insecure") {
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
} else {
tr = &http.Transport{}
}
httpClient := &http.Client{Transport: tr}
httpResp, err := httpClient.Do(httpReq)
if err != nil {
log.Fatalf("Failed to create http client: %v", err)
}
defer httpResp.Body.Close()
// If 201 is not returned, panic with http response
if httpResp.StatusCode != http.StatusCreated {
log.Fatalln(httpResp.Status)
}
return nil
}
func productReceiver(product string) func(event *mms.ProductEvent) error {
return func(event *mms.ProductEvent) error {
if product != "" && event.Product != product {
return nil
}
encoded, err := json.Marshal(event)
if err != nil {
return fmt.Errorf("failed to encode event as json: %s", err)
}
fmt.Println(string(encoded))
return nil
}
}
func createExecutableCallback(filepath string, args bool, product string) func(event *mms.ProductEvent) error {
_, err := exec.LookPath(filepath)
if err != nil {
log.Fatalf("command executable not found, %s", err)
}
return func(event *mms.ProductEvent) error {
var productLocation string
if product != "" && event.Product != product {
return nil
}
if args {
productLocation = event.ProductLocation
} else {
productLocation = ""
}
command := exec.Command(filepath, productLocation)
var stdout bytes.Buffer
var stderr bytes.Buffer
command.Stdout = &stdout
command.Stderr = &stderr
err = command.Run()
if err != nil {
fmt.Println("Failed", err, stderr.String())
return fmt.Errorf("Failed to run executable, %s", err.Error())
}
fmt.Println(stdout.String())
return nil
}
}