script.go 6.79 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package script

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"strings"
	"time"

	"git.scc.kit.edu/feudal/feudalClient/config"
Lukas Burgey's avatar
Lukas Burgey committed
16
	"git.scc.kit.edu/feudal/feudalClient/deployments"
Lukas Burgey's avatar
Lukas Burgey committed
17
	"git.scc.kit.edu/feudal/feudalScripts/v2"
Lukas Burgey's avatar
Lukas Burgey committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
)

type (
	// Sink implements sink.Sink
	Sink struct {
		Config    *config.Config
		Scheduled chan deps.Dep

		// Replies for the backend
		Replies chan deps.Reply
	}

	// ackResponse response of the backend for our response
	ackResponse struct {
		Error string `json:"error"`
	}
)

36
37
38
39
var (
	httpClient = &http.Client{}
)

Lukas Burgey's avatar
Lukas Burgey committed
40
func (sink *Sink) depServices(dep deps.Dep) (services []config.Service, err error) {
41
42
	// find the matching service
	if dep.Service != (config.Service{}) {
Lukas Burgey's avatar
Lukas Burgey committed
43
44
45
46
47
48
49
50
		for _, s := range sink.Config.Services {
			if s.Name == dep.Service.Name {
				services = []config.Service{s}
				return
			}
		}
	}

51
	err = fmt.Errorf("Dep has no service")
Lukas Burgey's avatar
Lukas Burgey committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
	return
}

func (sink *Sink) scheduleDep(dep deps.Dep) (err error) {
	// determine the services of the deployment
	var services []config.Service
	services, err = sink.depServices(dep)
	if err != nil {
		return
	}

	// execute the deployment for all the services
	for _, svc := range services {
		dep.Service = svc

Lukas Burgey's avatar
Lukas Burgey committed
67
68
69
		if sink.Config.Debug.Scripts {
			dep.Log("Scheduling execution for %s", svc.Name)
		}
Lukas Burgey's avatar
Lukas Burgey committed
70
71
72
73
74
75
76
77
78
79
80

		// schedule the deployment
		sink.Scheduled <- dep
	}
	return
}

func (sink *Sink) handleDep(dep deps.Dep) (output scripts.Output, err error) {

	// encode input as json
	input := scripts.Input{
Lukas Burgey's avatar
Lukas Burgey committed
81
82
83
		StateTarget: dep.StateTarget,
		User:        dep.User,
		Answers:     dep.Answers,
Lukas Burgey's avatar
Lukas Burgey committed
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
	}

	iBytes, err := input.Marshal()
	if err != nil {
		return
	}

	var (
		stdin          io.WriteCloser
		stdout, stderr io.ReadCloser
	)

	// execute the script
	if sink.Config.Debug.Scripts {
		dep.Log("Executing: '%s'", dep.Service.Command)
		dep.Log("Input: %s", input)
	}

	commandParts := strings.Split(dep.Service.Command, " ")
	cmd := exec.Command(commandParts[0], commandParts[1:]...)
	stdin, err = cmd.StdinPipe()
	if err != nil {
		return
	}
	stdout, err = cmd.StdoutPipe()
	if err != nil {
		return
	}
	stderr, err = cmd.StderrPipe()
	if err != nil {
		return
	}

	err = cmd.Start()
	if err != nil {
		return
	}
	stdin.Write(iBytes)
	stdin.Close()

	// decode json output
	var outputBytes, logOutputBytes []byte
	outputBytes, err = ioutil.ReadAll(stdout)
	if err != nil {
		return
	}

	logOutputBytes, err = ioutil.ReadAll(stderr)
	if err != nil {
		return
	}
	if sink.Config.Debug.Scripts {
		if len(logOutputBytes) > 0 {
			dep.Log("Logs:\n%s", logOutputBytes)
			dep.Log("End of Logs")
		}
	}

	err = cmd.Wait()
	if err != nil {
		return
	}
	if sink.Config.Debug.Scripts {
		var indented = new(bytes.Buffer)
		err = json.Indent(indented, outputBytes, "  ", "  ")
		if err != nil {
			dep.Log("Output (unable to indent: %s):\n%s", err, outputBytes)
		} else {
			dep.Log("Output:\n%s", indented.String())
		}
	}

	err = json.Unmarshal(outputBytes, &output)
	if err != nil {
		if len(outputBytes) > 0 {
			dep.Log("Raw output: %s", outputBytes)
		}
		return
	}

	// if the script does not provide any credential specific states we expect all
	// credentials to have the same state as the whole execution (output.State)
	if output.UserCredentialStates == nil {
		var userCredentialStates = make(scripts.UserCredentialStates)
		for credType, credList := range dep.User.Credentials {
			for _, credential := range credList {
				if stateMap, ok := userCredentialStates[credType]; !ok {
					userCredentialStates[credType] = map[string]scripts.State{
						credential.Name: output.State,
					}
				} else {
					stateMap[credential.Name] = output.State
				}
			}
		}
		output.UserCredentialStates = userCredentialStates
	}
	return
}

// reads deployments from sink.Scheduled
func (sink *Sink) depHandler() {
	handleWrapper := func(dep deps.Dep) {
		log.Printf("[Sink] Handling: %v", dep)

		output, err := sink.handleDep(dep)
		if err != nil {
			dep.Log("Error handling dep: %s", err)

			output = scripts.Output{
				State: scripts.Failed,
				// TODO maybe another message for the user
				Msg: fmt.Sprint(err),
			}
		}

		go func() {
201
202
203
204
205
206
207
208
209
210
211
			reply := deps.Reply{
				ID:                   dep.ID,
				State:                output.State,
				Msg:                  output.Msg,
				UserCredentialStates: output.UserCredentialStates,
			}
			if output.Questionnaire != nil && output.State == scripts.Questionnaire {
				reply.Questionnaire = output.Questionnaire
			}
			if output.Credentials != nil && output.State == scripts.Deployed {
				reply.Credentials = output.Credentials
Lukas Burgey's avatar
Lukas Burgey committed
212
			}
213
214

			sink.Replies <- reply
Lukas Burgey's avatar
Lukas Burgey committed
215
216
217
218
219
220
221
222
223
224
225
226
227
		}()
	}

	for newDep := range sink.Scheduled {
		if sink.Config.Debug.Sequential {
			handleWrapper(newDep)
		} else {
			// handle deps asynchronously
			go handleWrapper(newDep)
		}
	}
}

228
229
func (sink *Sink) sendReply(reply deps.Reply) (err error) {
	taskResponse, err := json.MarshalIndent(reply, "", "    ")
Lukas Burgey's avatar
Lukas Burgey committed
230
231
232
233
	if err != nil {
		return
	}

234
	if sink.Config.Debug.Backend {
Lukas Burgey's avatar
Lukas Burgey committed
235
236
237
		log.Printf("Dep Response:\n%s", taskResponse)
	}

238
239
	url := fmt.Sprintf("https://%s/backend/clientapi/dep-state", sink.Config.Hostname)
	req, err := http.NewRequest("PATCH", url, bytes.NewReader(taskResponse))
Lukas Burgey's avatar
Lukas Burgey committed
240
241
242
243
244
245
246
	if err != nil {
		return
	}
	req.SetBasicAuth(sink.Config.Username, sink.Config.Password)
	req.Header.Set("Content-Type", "application/json")

	// execute request
247
	resp, err := httpClient.Do(req)
Lukas Burgey's avatar
Lukas Burgey committed
248
249
250
251
252
	if err != nil {
		return
	}
	defer resp.Body.Close()

253
254
255
256
257
258
259
260
261
262
263
264
	body, readErr := ioutil.ReadAll(resp.Body)
	if readErr != nil {
		return readErr
	}

	if resp.StatusCode != 200 {
		err = fmt.Errorf("sendReply failed: (status: %v, body: %s)", resp.StatusCode, body)
		return
	}

	if sink.Config.Debug.Backend {
		reply.Log("Successful response")
Lukas Burgey's avatar
Lukas Burgey committed
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
	}
	return
}

func (sink *Sink) retryReply(reply deps.Reply) {
	time.Sleep(time.Minute)
	sink.Replies <- reply
}

// reads replies from sink.Replies
func (sink *Sink) depResponder() {
	for doneDep := range sink.Replies {
		// ack tasks asynchronously
		go func(reply deps.Reply) {
			err := sink.sendReply(reply)
			if err != nil {
				reply.Log("ACK-ERROR: %s", err)

				// retry failed replies
				go sink.retryReply(reply)
				return
			}
		}(doneDep)
	}
}

// Init initializes the sink
func (sink *Sink) Init(conf *config.Config) {
	sink.Config = conf
	sink.Scheduled = make(chan deps.Dep)
	sink.Replies = make(chan deps.Reply)
}

// Connect connects the sink and starts handling incoming deployments
func (sink *Sink) Connect(src <-chan deps.Dep) (err error) {
	// the responder finishes when sink.Replies closes
	go sink.depResponder()

	// the handler finishes when sink.Schedule closes
	go sink.depHandler()

	go func() {
		// schedule until the src runs out
Lukas Burgey's avatar
Lukas Burgey committed
308
		var err error
Lukas Burgey's avatar
Lukas Burgey committed
309
		for deps := range src {
Lukas Burgey's avatar
Lukas Burgey committed
310
311
312
313
			err = sink.scheduleDep(deps)
			if err != nil {
				log.Printf("[Sink] Error scheduling: %v", err)
			}
Lukas Burgey's avatar
Lukas Burgey committed
314
315
		}

Lukas Burgey's avatar
Lukas Burgey committed
316
317
318
		// clean up before exiting
		close(sink.Scheduled)
		close(sink.Replies)
Lukas Burgey's avatar
Lukas Burgey committed
319
320
321
	}()
	return
}