script.go 7.32 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
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
package script

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

	"git.scc.kit.edu/feudal/feudalClient/config"
	"git.scc.kit.edu/feudal/feudalClient/deps"
	"git.scc.kit.edu/feudal/feudalScripts"
)

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

func (sink *Sink) depServices(dep deps.Dep) (services []config.Service, err error) {
	// Option 1: VODeployment
	if dep.ResourceType == "VODeployment" && dep.VO != (deps.VO{}) {
		var ok bool

		// find sids
		var sids []config.ServiceID
		if dep.VO.ResourceType == "Group" {
			sids, ok = sink.Config.GroupToServiceIDs[dep.VO.Name]
			if !ok {
				err = fmt.Errorf("%s: Group %s does not exist", dep, dep.VO.Name)
				return
			}
		} else if dep.VO.ResourceType == "Entitlement" {
			sids, ok = sink.Config.EntitlementToServiceIDs[dep.VO.Name]
			if !ok {
				err = fmt.Errorf("%s: Entitlemnet %s does not exist", dep, dep.VO.Name)
				return
			}
		}
		services, err = sink.Config.GetServices(sids)
		if err != nil {
			return
		}
	} else if dep.ResourceType == "ServiceDeployment" && dep.Service != (config.Service{}) {
		for _, s := range sink.Config.Services {
			if s.Name == dep.Service.Name {
				services = []config.Service{s}
				return
			}
		}
	} else {
		err = fmt.Errorf("Dep is neither a VODeployment or a ServiceDeployment")

		return
	}

	if len(services) == 0 {
		err = fmt.Errorf("Dep has no services")
	}
	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

		//dep.Log("Scheduling execution for %s", svc.Name)

		// 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{
		StateTarget:   dep.StateTarget,
		User:          dep.User,
		Questionnaire: dep.Questionnaire,
		Credentials:   dep.User.Credentials,
	}

	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() {
			sink.Replies <- deps.Reply{
				ID:      dep.ID,
				Service: dep.Service,
				Output:  output,
			}
		}()
	}

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

func (sink *Sink) sendReply(te deps.Reply) (err error) {
	taskResponse, err := json.MarshalIndent(te, "", "    ")
	if err != nil {
		return
	}

	if sink.Config.Debug.Scripts {
		log.Printf("Dep Response:\n%s", taskResponse)
	}

	url := fmt.Sprintf("https://%s/backend/clientapi/response", sink.Config.Hostname)
	req, err := http.NewRequest("POST", url, bytes.NewReader(taskResponse))
	if err != nil {
		return
	}
	req.SetBasicAuth(sink.Config.Username, sink.Config.Password)
	req.Header.Set("Content-Type", "application/json")

	// execute request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		if sink.Config.Debug.Scripts {
			te.Log("Successful response")
		}
	} else {
		te.Log("Response Status: %v", resp.StatusCode)

		var (
			ackResponseBytes []byte
			ackResponse      ackResponse
		)
		ackResponseBytes, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			return
		}
		err = json.Unmarshal(ackResponseBytes, &ackResponse)
		if err != nil {
			return
		}
		te.Log("Response to our response: '%s'", ackResponse.Error)
	}
	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)
	}
}

func (sink *Sink) close() {
	close(sink.Scheduled)
	close(sink.Replies)
}

// 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
		for deps := range src {
			sink.scheduleDep(deps)
		}

		// closes sink.Replies and sink.Schedule
		sink.close()
	}()
	return
}