File: executor.go

package info (click to toggle)
mender-client 3.4.0%2Bds1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,084 kB
  • sloc: sh: 1,134; makefile: 277; python: 172; ansic: 125; xml: 27
file content (408 lines) | stat: -rw-r--r-- 11,074 bytes parent folder | download
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
// Copyright 2022 Northern.tech AS
//
//    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 statescript

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"syscall"
	"time"

	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"

	"github.com/mendersoftware/mender/client"
	"github.com/mendersoftware/mender/system"
)

const (
	// exitRetryLater - exit code returned if a script requests a retry
	exitRetryLater = 21

	defaultStateScriptRetryInterval time.Duration = 60 * time.Second

	defaultStateScriptRetryTimeout time.Duration = 30 * time.Minute

	defaultStateScriptTimeout time.Duration = 1 * time.Hour
)

type Executor interface {
	ExecuteAll(state, action string, ignoreError bool, report *client.StatusReportWrapper) error
	CheckRootfsScriptsVersion() error
}

type Launcher struct {
	ArtScriptsPath          string
	RootfsScriptsPath       string
	SupportedScriptVersions []int
	Timeout                 int
	RetryInterval           int
	RetryTimeout            int
}

func (l *Launcher) getRetryInterval() time.Duration {

	if l.RetryInterval != 0 {
		return time.Duration(l.RetryInterval) * time.Second
	}
	log.Warningf(
		"No timeout interval set for the retry-scripts. Falling back to default: %s",
		defaultStateScriptRetryInterval.String(),
	)
	return defaultStateScriptRetryInterval
}

func (l *Launcher) getRetryTimeout() time.Duration {

	if l.RetryTimeout != 0 {
		return time.Duration(l.RetryTimeout) * time.Second
	}
	log.Warningf(
		"No total time set for the retry-scripts' timeslot. Falling back to default: %s",
		defaultStateScriptRetryTimeout.String(),
	)
	return defaultStateScriptRetryTimeout
}

func (l Launcher) getTimeout() time.Duration {

	if l.Timeout != 0 {
		return time.Duration(l.Timeout) * time.Second
	}
	log.Debugf(
		"statescript: The timeout for executing scripts is not defined; using default"+
			" of %s seconds",
		defaultStateScriptTimeout,
	)
	return defaultStateScriptTimeout
}

//TODO: we can optimize for reading directories once and then creating
// a map with all the scripts that needs to be executed.
func (l Launcher) CheckRootfsScriptsVersion() error {
	// first check if we are having some scripts
	scripts, err := ioutil.ReadDir(l.RootfsScriptsPath)
	if err != nil && os.IsNotExist(err) {
		// no scripts; no error
		return nil
	} else if err != nil {
		return errors.Wrap(err, "statescript: can not read rootfs scripts directory")
	}

	if len(scripts) == 0 {
		return nil
	}

	versionFilePath := filepath.Join(l.RootfsScriptsPath, "version")
	f, err := os.Open(versionFilePath)
	if err != nil && os.IsNotExist(err) {
		errmsg := "statescript: The statescript version file is missing. This file needs to be " +
			"present and contain a single number representing which version of the statescript " +
			"support the client is using in order to successfully run statescripts on the client"
		return errors.New(errmsg)
	} else if err != nil {
		return errors.Wrap(err, "statescript")
	}
	defer f.Close()
	ver, err := readVersion(f)
	if _, ok := err.(readVersionParseError); ok {
		errmsg := "statescript: Failed to parse the version file in the statescript" +
			" directory (%s). The file needs to contain a single integer signifying which" +
			" version of the statescript support which this client is using"
		return fmt.Errorf(errmsg, err)
	}
	if err != nil {
		return errors.Wrap(err, "statescript")
	}

	for _, v := range l.SupportedScriptVersions {
		if v == ver {
			return nil
		}
	}
	return errors.Errorf("statescript: unsupported scripts version: %v", ver)
}

func matchVersion(actual int, supported []int, hasScripts bool) error {
	// if there are no scripts to execute we shold not care about the version
	if !hasScripts {
		return nil
	}

	for _, v := range supported {
		if v == actual {
			return nil
		}
	}

	errmsg := "statescript: The version read from the version file in the statescript directory " +
		"does not match the versions supported by the client, please make sure the file is" +
		" present and formatted correctly (supported: %v; actual: %v)."
	return errors.Errorf(errmsg, supported, actual)
}

func (l Launcher) get(state, action string) ([]os.FileInfo, string, error) {

	sDir := l.ArtScriptsPath
	if state == "Idle" || state == "Sync" || state == "Download" {
		sDir = l.RootfsScriptsPath
	}

	// ReadDir reads the directory named by dirname and returns
	// a list of directory entries sorted by filename.
	// The list returned should be sorted which guarantees correct
	// order of scripts execution.
	files, err := ioutil.ReadDir(sDir)
	if err != nil && os.IsNotExist(err) {
		// no state scripts directory; just move on
		return nil, "", nil
	} else if err != nil {
		return nil, "", errors.Wrap(err, "statescript: can not read scripts directory")
	}

	scripts := make([]os.FileInfo, 0)
	var version int

	for _, file := range files {
		if file.Name() == "version" {
			f, err := os.Open(filepath.Join(sDir, file.Name()))
			if err != nil {
				return nil, "", errors.Wrapf(err, "statescript")
			}
			version, err = readVersion(f)
			if err != nil {
				return nil, "", errors.Wrapf(err, "statescript")
			}
		}

		if strings.Contains(file.Name(), state+"_") &&
			strings.Contains(file.Name(), action) {

			// all scripts must be formated like `ArtifactInstall_Enter_05(_wifi-driver)`(optional)
			re := regexp.MustCompile(`([A-Za-z]+)_(Enter|Leave|Error)_[0-9][0-9](_\S+)?`)
			if len(file.Name()) == len(re.FindString(file.Name())) {
				scripts = append(scripts, file)
			} else {
				log.Warningf("Script format mismatch: '%s' will not be run ", file.Name())
			}
		}
	}

	if err := matchVersion(version, l.SupportedScriptVersions,
		len(scripts) != 0); err != nil {
		return nil, "", err
	}

	return scripts, sDir, nil
}

func execute(name string, timeout time.Duration) error {

	cmd := system.Command(name)

	var stderr io.ReadCloser
	var err error

	if !strings.HasPrefix(name, "Idle") && !strings.HasPrefix(name, "Sync") {
		stderr, err = cmd.StderrPipe()
		if err != nil {
			log.Errorf("statescript: %v", err)
			return errors.Wrap(err, "statescript: unable to open stderr pipe")
		}
	}

	// As child process gets the same PGID as the parent by default, in order
	// to avoid killing Mender when killing process group we are setting
	// new PGID for the executed script and its children.
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}

	if err := cmd.Start(); err != nil {
		return err
	}

	timer := time.AfterFunc(timeout, func() {
		// In addition to kill a single process we are sending SIGKILL to
		// process group making sure we are killing the hanging script and
		// all its children.
		_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
	})
	defer timer.Stop()

	var bts []byte
	if stderr != nil {
		bts, err = ioutil.ReadAll(stderr)
		if err != nil {
			log.Error(err)
		}
	}

	if len(bts) > 0 {
		if len(bts) > 10*1024 {
			log.Infof(
				"Collected output (stderr) while running script %s (Truncated to 10KB)\n"+
					"%s\n---------- end of script output",
				name,
				bts[:10*1024],
			)
		} else {
			log.Infof(
				"Collected output (stderr) while running script %s\n%s\n"+
					"---------- end of script output",
				name,
				string(bts),
			)
		}
	}

	if err := cmd.Wait(); err != nil {
		return err
	}
	return nil
}

func retCode(err error) int {
	defaultFailedCode := -1

	if err != nil {
		// try to get the exit code
		if exitError, ok := err.(*exec.ExitError); ok {
			ws := exitError.Sys().(syscall.WaitStatus)
			return ws.ExitStatus()
		} else {
			return defaultFailedCode
		}
	}
	return 0
}

// Catches a script that requests a retry in a loop. Is limited by the total window given to a
// script demanding a retry.
func executeScript(
	s os.FileInfo,
	dir string,
	l Launcher,
	timeout time.Duration,
	ignoreError bool,
) error {

	iet := time.Now()
	for {
		err := execute(filepath.Join(dir, s.Name()), timeout)
		switch ret := retCode(err); ret {
		case 0:
			// success
			return nil
		case exitRetryLater:
			if time.Since(iet) <= l.getRetryTimeout() {
				log.Infof("statescript: %s requested a retry", s.Name())
				time.Sleep(l.getRetryInterval())
				continue
			}
			if ignoreError {
				log.Errorf(
					"statescript: Ignoring error executing '%s': %d: %s",
					s.Name(),
					ret,
					err.Error(),
				)
				return nil
			}
			return errors.Errorf("statescript: retry time-limit exceeded %s", err.Error())
		default:
			// In case of error scripts all should be executed.
			if ignoreError {
				log.Errorf(
					"statescript: Ignoring error executing '%s': %d: %s",
					s.Name(),
					ret,
					err.Error(),
				)
				return nil
			}
			return errors.Errorf("statescript: error executing '%s': %d : %s",
				s.Name(), ret, err.Error())
		}
	}
}

func reportScriptStatus(rep *client.StatusReportWrapper, statusReport string) error {
	c := client.NewStatus()

	return c.Report(rep.API, rep.URL, client.StatusReport{
		DeploymentID: rep.Report.DeploymentID,
		Status:       rep.Report.Status,
		SubState:     statusReport,
	})
}

func (l Launcher) ExecuteAll(state, action string, ignoreError bool,
	report *client.StatusReportWrapper) error {
	scr, dir, err := l.get(state, action)
	if err != nil {
		if ignoreError {
			log.Errorf("statescript: Got an error when trying to execute [%s:%s] script, "+
				"but ignoreError is set to true, so continuing. Full error message: %v",
				state, action, err)
			return nil
		}
		return err
	}

	execBits := os.FileMode(syscall.S_IXUSR | syscall.S_IXGRP | syscall.S_IXOTH)
	timeout := l.getTimeout()

	for _, s := range scr {
		// check if script is executable
		if s.Mode()&execBits == 0 {
			if ignoreError {
				log.Errorf("statescript: Ignoring script '%s' being not executable",
					filepath.Join(dir, s.Name()))
				continue
			} else {
				return errors.Errorf("statescript: script '%s' is not executable",
					filepath.Join(dir, s.Name()))
			}
		}

		subStatus := fmt.Sprintf("Executing script: %s", s.Name())
		log.Info(subStatus)
		if report != nil {
			if err = reportScriptStatus(report, subStatus); err != nil {
				log.Errorf("statescript: Can not send start status to server: %s", err.Error())
			}

			defer func() {
				if err = reportScriptStatus(report,
					fmt.Sprintf("finished executing script: %s", s.Name())); err != nil {
					log.Errorf(
						"statescript: Can not send finished status to server: %s",
						err.Error(),
					)
				}
			}()
		}

		if err = executeScript(s, dir, l, timeout, ignoreError); err != nil {
			return err
		}
	}
	return nil
}