script.go 6.73 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"
16
	deps "git.scc.kit.edu/feudal/feudalClient/deployments"
lukasburgey's avatar
lukasburgey committed
17
	"git.scc.kit.edu/feudal/feudalClient/indent"
18
	scripts "git.scc.kit.edu/feudal/feudalScripts/v2"
Lukas Burgey's avatar
Lukas Burgey committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
)

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"`
	}
)

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

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

52
	err = fmt.Errorf("Dep has no service")
Lukas Burgey's avatar
Lukas Burgey committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
	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
68
69
70
		if sink.Config.Debug.Scripts {
			dep.Log("Scheduling execution for %s", svc.Name)
		}
Lukas Burgey's avatar
Lukas Burgey committed
71
72
73
74
75
76
77
78
79
80
81

		// 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
82
83
84
		StateTarget: dep.StateTarget,
		User:        dep.User,
		Answers:     dep.Answers,
Lukas Burgey's avatar
Lukas Burgey committed
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
	}

	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()

lukasburgey's avatar
lukasburgey committed
125
126
	// read stdout / stderr
	var stdoutBytes, stderrBytes []byte
Lukas Burgey's avatar
Lukas Burgey committed
127

lukasburgey's avatar
lukasburgey committed
128
	stdoutBytes, err = ioutil.ReadAll(stdout)
Lukas Burgey's avatar
Lukas Burgey committed
129
130
131
	if err != nil {
		return
	}
lukasburgey's avatar
lukasburgey committed
132
133
134
135
136

	stderrBytes, _ = ioutil.ReadAll(stderr)
	if sink.Config.Debug.Scripts && len(stderrBytes) > 0 {
		dep.Log("Logs:\n%s", stderrBytes)
		dep.Log("End of Logs")
Lukas Burgey's avatar
Lukas Burgey committed
137
138
	}

lukasburgey's avatar
lukasburgey committed
139
	// waits for command execution and pipe reading
Lukas Burgey's avatar
Lukas Burgey committed
140
141
142
143
144
	err = cmd.Wait()
	if err != nil {
		return
	}
	if sink.Config.Debug.Scripts {
lukasburgey's avatar
lukasburgey committed
145
		dep.Log("Output: %s", indent.Indent(stdoutBytes))
Lukas Burgey's avatar
Lukas Burgey committed
146
147
	}

lukasburgey's avatar
lukasburgey committed
148
	err = json.Unmarshal(stdoutBytes, &output)
Lukas Burgey's avatar
Lukas Burgey committed
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
	if err != nil {
		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() {
190
191
192
193
194
195
196
197
198
199
200
			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
201
			}
202
203

			sink.Replies <- reply
Lukas Burgey's avatar
Lukas Burgey committed
204
205
206
207
208
209
210
211
212
213
214
215
216
		}()
	}

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

217
func (sink *Sink) sendReply(reply deps.Reply) (err error) {
Lukas Burgey's avatar
Lukas Burgey committed
218
219
	var taskResponse []byte
	taskResponse, err = json.MarshalIndent(reply, "", "    ")
Lukas Burgey's avatar
Lukas Burgey committed
220
221
222
223
	if err != nil {
		return
	}

224
	if sink.Config.Debug.Backend {
Lukas Burgey's avatar
Lukas Burgey committed
225
226
227
		log.Printf("Dep Response:\n%s", taskResponse)
	}

228
	url := fmt.Sprintf("https://%s/client/dep-state", sink.Config.Hostname)
Lukas Burgey's avatar
Lukas Burgey committed
229
230
	var req *http.Request
	req, err = http.NewRequest("PATCH", url, bytes.NewReader(taskResponse))
Lukas Burgey's avatar
Lukas Burgey committed
231
232
233
234
235
236
237
	if err != nil {
		return
	}
	req.SetBasicAuth(sink.Config.Username, sink.Config.Password)
	req.Header.Set("Content-Type", "application/json")

	// execute request
Lukas Burgey's avatar
Lukas Burgey committed
238
239
	var resp *http.Response
	resp, err = httpClient.Do(req)
Lukas Burgey's avatar
Lukas Burgey committed
240
241
242
243
244
	if err != nil {
		return
	}
	defer resp.Body.Close()

Lukas Burgey's avatar
Lukas Burgey committed
245
	var body []byte
246
247
	body, readErr := ioutil.ReadAll(resp.Body)
	if readErr != nil {
Lukas Burgey's avatar
Lukas Burgey committed
248
249
		log.Printf("sendReply: unable to read response body")
		body = []byte{}
250
251
252
253
254
255
256
257
258
	}

	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
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
	}
	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
302
		var err error
Lukas Burgey's avatar
Lukas Burgey committed
303
		for deps := range src {
Lukas Burgey's avatar
Lukas Burgey committed
304
305
306
307
			err = sink.scheduleDep(deps)
			if err != nil {
				log.Printf("[Sink] Error scheduling: %v", err)
			}
Lukas Burgey's avatar
Lukas Burgey committed
308
309
		}

Lukas Burgey's avatar
Lukas Burgey committed
310
311
312
		// clean up before exiting
		close(sink.Scheduled)
		close(sink.Replies)
Lukas Burgey's avatar
Lukas Burgey committed
313
314
315
	}()
	return
}