7 Commits
34 changed files with 744 additions and 216 deletions
+2 -1
View File
@@ -12,6 +12,7 @@ import (
"gitea.suyono.dev/suyono/wingmate"
"gitea.suyono.dev/suyono/wingmate/cmd/cli"
wmenv "gitea.suyono.dev/suyono/wingmate/task/env"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/sys/unix"
@@ -74,7 +75,7 @@ func main() {
if selfArgs, childArgs, err = cli.SplitArgs(os.Args); err != nil {
selfArgs = os.Args
}
app.childArgs = childArgs
app.childArgs = wmenv.ExpandEnv(os.Environ(), childArgs)
app.err = err
rootCmd.SetArgs(selfArgs[1:])
+1 -1
View File
@@ -46,7 +46,7 @@ func main() {
_ = file.Close()
}()
if err = wingmate.NewLog(file); err == nil {
if err = wingmate.NewLog(file, wingmate.Time|wingmate.Caller); err == nil {
wingmate.Log().Info().Msg(logMessage)
}
}
+3 -2
View File
@@ -32,7 +32,7 @@ func convert(cfg *config.Config) *wConfig {
for _, s := range cfg.Service {
st := task.NewServiceTask(s.Name).SetCommand(s.Command...).SetEnv(s.Environ...)
st.SetFlagSetsid(s.Setsid).SetWorkingDir(s.WorkingDir)
st.SetFallbackEnv(s.FallbackEnv...).SetFlagSetsid(s.Setsid).SetWorkingDir(s.WorkingDir)
st.SetUser(s.User).SetGroup(s.Group).SetStartSecs(s.StartSecs).SetPidFile(s.PidFile)
st.SetConfig(cfg)
retval.tasks.AddService(st)
@@ -52,7 +52,8 @@ func convert(cfg *config.Config) *wConfig {
schedule = configToTaskCronSchedule(c.CronSchedule)
ct := task.NewCronTask(c.Name).SetCommand(c.Command...).SetEnv(c.Environ...)
ct.SetFlagSetsid(c.Setsid).SetWorkingDir(c.WorkingDir).SetUser(c.User).SetGroup(c.Group)
ct.SetFallbackEnv(c.FallbackEnv...).SetFlagSetsid(c.Setsid).SetWorkingDir(c.WorkingDir)
ct.SetUser(c.User).SetGroup(c.Group)
ct.SetSchedule(c.Schedule, schedule)
ct.SetConfig(cfg)
+2 -1
View File
@@ -21,7 +21,8 @@ func main() {
cfg *config.Config
)
_ = wingmate.NewLog(os.Stderr)
_ = wingmate.NewLog(os.Stderr, wingmate.Time|wingmate.Caller)
wingmate.SetGlobalLevel(wingmate.InfoLevel)
config.SetVersion(version)
config.ParseFlags()
+13 -8
View File
@@ -30,6 +30,7 @@ const (
WMPidProxyPathFlag = "pid-proxy"
WMExecPathFlag = "exec"
PathConfigFlag = "config"
GlobalLogConfig = "log_level"
)
type Config struct {
@@ -41,12 +42,13 @@ type Config struct {
}
type Task struct {
Command []string `mapstructure:"command"`
Environ []string `mapstructure:"environ"`
Setsid bool `mapstructure:"setsid"`
User string `mapstructure:"user"`
Group string `mapstructure:"group"`
WorkingDir string `mapstructure:"working_dir"`
Command []string `mapstructure:"command"`
Environ []string `mapstructure:"environ"`
FallbackEnv []string `mapstructure:"fallback_env"`
Setsid bool `mapstructure:"setsid"`
User string `mapstructure:"user"`
Group string `mapstructure:"group"`
WorkingDir string `mapstructure:"working_dir"`
}
type ServiceTask struct {
@@ -84,9 +86,11 @@ func Read() (*Config, error) {
_ = viper.BindEnv(PathConfig)
_ = viper.BindEnv(PidProxyPathConfig)
_ = viper.BindEnv(ExecPathConfig)
_ = viper.BindEnv(GlobalLogConfig)
viper.SetDefault(PathConfig, DefaultConfigPath)
viper.SetDefault(PidProxyPathConfig, PidProxyPathDefault)
viper.SetDefault(ExecPathConfig, ExecPathDefault)
viper.SetDefault(GlobalLogConfig, wingmate.InfoLevelStr)
var (
dirent []os.DirEntry
@@ -101,6 +105,7 @@ func Read() (*Config, error) {
crones []CronTask
)
wingmate.SetGlobalLevelStr(viper.GetString(GlobalLogConfig))
serviceAvailable = false
cronAvailable = false
outConfig := &Config{
@@ -111,7 +116,7 @@ func Read() (*Config, error) {
svcdir = filepath.Join(configPath, ServiceDirName)
dirent, err = os.ReadDir(svcdir)
if err != nil {
wingmate.Log().Error().Msgf("encounter error when reading service directory %s: %+v", svcdir, err)
wingmate.Log().Warn().Msgf("encounter error when reading service directory %s: %+v", svcdir, err)
}
if len(dirent) > 0 {
for _, d := range dirent {
@@ -134,7 +139,7 @@ func Read() (*Config, error) {
cronAvailable = true
}
if err != nil {
wingmate.Log().Error().Msgf("encounter error when reading crontab %s: %+v", crontabfile, err)
wingmate.Log().Warn().Msgf("encounter error when reading crontab %s: %+v", crontabfile, err)
}
wingmateConfigAvailable = false
+1 -1
View File
@@ -53,7 +53,7 @@ func TestRead(t *testing.T) {
_ = f.Close()
}
_ = wingmate.NewLog(os.Stderr)
_ = wingmate.NewLog(os.Stderr, wingmate.Caller|wingmate.Time)
tests := []testEntry{
{
name: "positive",
+1 -1
View File
@@ -20,7 +20,7 @@ func TestCrontab(t *testing.T) {
wantErr bool
}
_ = wingmate.NewLog(os.Stderr)
_ = wingmate.NewLog(os.Stderr, wingmate.Caller|wingmate.Time)
tests := []testEntry{
{
name: "positive",
+1 -1
View File
@@ -18,7 +18,7 @@ func TestYaml(t *testing.T) {
wantErr bool
}
_ = wingmate.NewLog(os.Stderr)
_ = wingmate.NewLog(os.Stderr, wingmate.Caller|wingmate.Time)
tests := []testEntry{
{
name: "positive",
+8 -6
View File
@@ -1,15 +1,17 @@
FROM golang:1.22-alpine3.20 AS builder
FROM golang:1.24-alpine3.22 AS builder
ADD . /root/wingmate
WORKDIR /root/wingmate/
ARG TEST_BUILD
RUN apk update && apk add git make build-base && \
CGO_ENABLED=1 make all && \
make DESTDIR=/usr/local/bin/wingmate install
#RUN apk update && apk add git make build-base && \
# CGO_ENABLED=1 make all && \
# make DESTDIR=/usr/local/bin/wingmate install
RUN apk update && apk add git make && \
make all && make DESTDIR=/usr/local/bin/wingmate install
FROM alpine:3.20
FROM alpine:3.22
RUN apk add tzdata && ln -s /usr/share/zoneinfo/Australia/Sydney /etc/localtime && \
adduser -h /home/user1 -D -s /bin/sh user1 && \
@@ -19,4 +21,4 @@ ADD --chmod=755 docker/alpine/entry.sh /usr/local/bin/entry.sh
ADD --chmod=755 docker/alpine/etc /etc
ENTRYPOINT [ "/usr/local/bin/entry.sh" ]
CMD [ "/usr/local/bin/wingmate" ]
CMD [ "/usr/local/bin/wingmate" ]
-3
View File
@@ -1,3 +0,0 @@
*/5 * * * * /etc/wingmate/crontab.d/cron1.sh
17,42 */2 * * * /etc/wingmate/crontab.d/cron2.sh
7,19,23,47 22 * * * /etc/wingmate/crontab.d/cron3.sh
@@ -1,9 +0,0 @@
#!/bin/sh
export WINGMATE_DUMMY_PATH=/usr/local/bin/wmdummy
export WINGMATE_LOG=/var/log/cron1.log
export WINGMATE_LOG_MESSAGE="cron executed in minute 5,10,15,20,25,30,35,40,45,50,55"
echo "I'm runnig with dummy=$WINGMATE_DUMMY_PATH, log=$WINGMATE_LOG and mesage=$WINGMATE_LOG_MESSAGE" >> /var/log/debug-cron.log
exec /usr/local/bin/wmoneshot
@@ -1,7 +0,0 @@
#!/bin/sh
export WINGMATE_DUMMY_PATH=/usr/local/bin/wmdummy
export WINGMATE_LOG=/var/log/cron2.log
export WINGMATE_LOG_MESSAGE="cron scheduled using 17,42 */2 * * *"
exec /usr/local/bin/wmoneshot
@@ -1,7 +0,0 @@
#!/bin/sh
export WINGMATE_DUMMY_PATH=/usr/local/bin/wmdummy
export WINGMATE_LOG=/var/log/cron3.log
export WINGMATE_LOG_MESSAGE="cron entry: 7,19,23,47 22 * * * /etc/wingmate/crontab.d/cron3.sh"
exec /usr/local/bin/wmoneshot
@@ -1,4 +0,0 @@
#!/bin/sh
export DUMMY_PATH=/usr/local/bin/wmdummy
exec /usr/local/bin/wmexec --setsid --user user1:user1 -- /usr/local/bin/wmstarter
@@ -1,5 +0,0 @@
#!/bin/sh
export WINGMATE_ONESHOT_PATH=/usr/local/bin/wmoneshot
export WINGMATE_DUMMY_PATH=/usr/local/bin/wmdummy
exec /usr/local/bin/wmexec --user 1001 -- /usr/local/bin/wmspawner
+2 -2
View File
@@ -1,4 +1,4 @@
FROM golang:1.22-bookworm AS builder
FROM golang:1.24-bookworm AS builder
ADD . /root/wingmate
WORKDIR /root/wingmate/
@@ -17,4 +17,4 @@ ADD --chmod=755 docker/bookworm/entry.sh /usr/local/bin/entry.sh
ADD --chmod=755 docker/bookworm/etc /etc
ENTRYPOINT [ "/usr/local/bin/entry.sh" ]
CMD [ "/usr/local/bin/wingmate" ]
CMD [ "/usr/local/bin/wingmate" ]
+195
View File
@@ -0,0 +1,195 @@
# Code Review: Wingmate
Branch: `main` (whole-repository review; no comparison branch)
Effort: high
Context used: [Wingmate README](../README.md), [YAML configuration reference](../wingmate.yaml.md)
> This doc is a live tracker. Update the **Status** column/field as findings are triaged, fixed, or dismissed — don't leave the table out of sync with the detail sections below.
The review covers the supervisor runtime, helper binaries, privilege boundaries, configuration compatibility, operations, build, and tests.
## Status legend
| Status | Meaning |
|---|---|
| 🔴 Open | Not yet triaged or fixed |
| 🟡 In progress | Fix underway |
| 🟢 Fixed | Fix landed on this branch |
| 🔵 Verified | Independently confirmed real (see Verification note) but not yet fixed |
| ⚪ Won't fix | Triaged and consciously deferred/rejected, with reason noted |
## Tracker
| # | Finding | File | Status |
|---|---|---|---|
| 1 | P1: Init mode does not enforce its PID 1 operating requirement | `init/signal-pump.go:31` | 🔴 Open |
| 2 | P1: A missing task command crashes the supervisor | `task/task.go:289` | 🔵 Verified |
| 3 | P1: A zero cron step can hang startup and exhaust memory | `config/yaml.go:147` | 🔴 Open |
| 4 | P2: A clean checkout cannot compile all test packages | `cmd/wingmate/wingmate.go:14` | 🔵 Verified |
| 5 | P2: CLI tests call a process entry point they cannot control | `cmd/wingmate/wingmate_test.go:8` | 🔵 Verified |
| 6 | P2: One config load can read another load's YAML | `config/yaml.go:40` | 🔵 Verified |
| 7 | P1: `wmexec` retains supplementary groups when changing identity | `cmd/exec/exec.go:106` | 🔵 Verified |
| 8 | P1: A long log line can stall a service or cron job | `init/service.go:98` | 🔵 Verified |
| 9 | P1: `wmpidproxy` can signal processes other than its daemon | `cmd/pidproxy/pidproxy.go:109` | 🔵 Verified |
| 10 | P2: Legacy cron commands with arguments don't run | `task/task.go:40` | 🔵 Verified |
| 11 | P2: A YAML parse error can leak secrets into logs | `config/yaml.go:52` | 🔵 Verified |
| 12 | P2: A failing service can restart continuously without a useful exit diagnostic | `init/service.go:71` | 🔵 Verified |
| 13 | P2: Named identities crash `wmexec` instead of working or returning a clear error | `cmd/exec/ent.go:5` | 🔵 Verified |
## Findings
### 1. P1: Init mode does not enforce its PID 1 operating requirement
- **Status**: 🔴 Open
- **File**: `init/signal-pump.go:31–67`, `init/sighandler.go:21–35`
- **Kind**: Reliability and test isolation — namespace-wide shutdown is intentional for container init; the concern is accidental use outside that operating mode.
- **Summary**: Wingmate's shutdown path broadcasts TERM and potentially KILL without checking that it is running as PID 1.
- **Failure scenario**: A developer runs Wingmate as an ordinary host process and sends it TERM to exercise shutdown. The signal pump can reach unrelated processes in the same PID namespace that Wingmate has permission to signal.
- **Recommendations**:
1. **(Recommended)** Preserve init-mode broadcasts in a dedicated PID namespace. Reject init-mode startup outside PID 1, and guard the real broadcast at the signal boundary so callers cannot bypass the check. Document the dedicated namespace requirement separately from the PID 1 check.
2. Unit-test shutdown decisions with a fake signal sender and clock. Track real signal delivery in the separate [WM-001 Docker shutdown integration test](tasks/WM-001-docker-shutdown-test.md), which does not cover production enforcement.
3. Implement targeted shutdown for ordinary Linux processes as a separate mode under [WM-002](tasks/WM-002-non-init-supervisor-mode.md).
### 2. P1: A missing task command crashes the supervisor
- **Status**: 🔵 Verified
- **File**: `task/task.go:256–306`, `task/cron.go:210–253`, `config/yaml.go:48–73`
- **Summary**: YAML loading accepts tasks without a command, and the task accessors assume `UtilDepCheck` populated a nonempty command line.
- **Failure scenario**: A YAML service with a `working_dir` but no `command` passes config loading. `UtilDepCheck` leaves `cmdLine` empty, and `ServiceTask.Command()` panics when the worker indexes it. Valid legacy tasks also panic if a caller reads their command before `UtilDepCheck()`.
- **Verification note**: A config probe confirmed that `Read()` accepts the missing command, and a separate run of the built binary reproduced the panic from `init/service.go:45`. `TestServicesV0` and `TestCronV0` reproduced the initialization failure independently.
- **Recommendations**:
1. **(Recommended)** Validate command inputs before launching workers and separate command construction from helper-binary version checks.
2. Cover missing commands, valid legacy tasks, and wrapper argument construction with regression tests.
### 3. P1: A zero cron step can hang startup and exhaust memory
- **Status**: 🔴 Open
- **File**: `config/yaml.go:145–161`, `config/crontab.go:165–181`
- **Summary**: Both cron parsers accept a zero step for fields whose valid range includes zero.
- **Failure scenario**: A `*/0` minute step passes the field range check, then the expansion loop repeatedly appends zero because its counter never advances. Startup can hang and exhaust memory. This path was identified by inspection; the unbounded loop was not run.
- **Recommendations**:
1. **(Recommended)** Reject zero before expansion and share the step parser across YAML and legacy crontab.
2. Add table-driven tests for zero, valid steps, and field boundaries.
### 4. P2: A clean checkout cannot compile all test packages
- **Status**: 🔵 Verified
- **File**: `cmd/wingmate/wingmate.go:14`, `cmd/pidproxy/pidproxy.go:37`, `cmd/exec/exec.go:36` (and each command's `Makefile:1–3`)
- **Kind**: Build and test setup — the standard Go entry point depends on files generated by Make.
- **Summary**: Each command embeds an ignored `version.txt` that its Makefile creates.
- **Failure scenario**: Running `go test ./...` in a clean checkout fails to compile all three command packages with `pattern version.txt: no matching files found`.
- **Verification note**: `go test ./... -run '^$'` isolated the compile failures. After generating version files in a temporary copy, `go build ./...` and `go vet ./...` passed.
- **Recommendations**:
1. **(Recommended)** Give ordinary Go builds a default version and inject release versions at build time, preserving the version match between Wingmate and its helper binaries.
### 5. P2: CLI tests call a process entry point they cannot control
- **Status**: 🔵 Verified
- **File**: `cmd/wingmate/wingmate_test.go:8–23`, `cmd/wingmate/wingmate.go:18–36`, `config/flags.go:11–25`
- **Kind**: Test design — configuration tests enter the production process lifecycle.
- **Summary**: The tests use machine-specific paths, mutate process-wide arguments, and call `main()` directly.
- **Failure scenario**: `TestEntry_configPathEnv` points at a developer-specific `/Volumes/Source/...` path. Without that directory, `main()` logs a fatal error and exits the test process. With a valid fixture, `main()` enters the blocking supervisor.
- **Verification note**: After the version-file prerequisite was satisfied in a temporary copy, `go test ./... -timeout=15s` reached the command tests and reproduced the fatal exit on the missing config path.
- **Recommendations**:
1. **(Recommended)** Extract a startup function that takes explicit arguments, uses a fresh flag set, returns errors, and accepts a supervisor callback.
2. Use `t.TempDir()` and `t.Setenv()` to assert flag, environment, and default precedence without launching services.
### 6. P2: One config load can read another load's YAML
- **Status**: 🔵 Verified
- **File**: `config/yaml.go:27–49`, `config/config.go:84–115`
- **Summary**: The package-global Viper instance retains prior search paths between calls to `Read()`.
- **Failure scenario**: A process loads YAML from a directory defining service `first`, then changes `WINGMATE_CONFIG_PATH` to a directory defining only `second`. The second `Read()` returns `first`.
- **Verification note**: A same-process probe with two valid temporary config directories reproduced the stale service without resetting Viper between calls.
- **Recommendations**:
1. **(Recommended)** Use a fresh Viper instance for each load, read the explicitly selected file, and store resolved settings on the returned config.
2. Keep a regression test that loads two distinct directories in sequence.
### 7. P1: `wmexec` retains supplementary groups when changing identity
- **Status**: 🔵 Verified
- **File**: `cmd/exec/exec.go:106–138`
- **Kind**: Security — incomplete credential change.
- **Summary**: `wmexec` sets the requested UID and optional primary GID without replacing the supplementary group list.
- **Failure scenario**: Wingmate starts a service under a less-privileged account, but the child inherits supplementary groups that may still grant access to files or devices the target account should not be able to use.
- **Verification note**: Invoking the built binary with the review user's numeric UID and primary GID left the supplementary groups unchanged. A privileged root-to-user transition was not exercised.
- **Recommendations**:
1. **(Recommended)** Resolve the target identity and group list before changing credentials, replace the supplementary groups, and fail before executing the child if any part of the switch fails.
2. Verify the child's full group list in an isolated privileged test.
### 8. P1: A long log line can stall a service or cron job
- **Status**: 🔵 Verified
- **File**: `init/service.go:80–110`, `init/cron.go:59–75`
- **Kind**: Reliability — the output reader can block the workload it is observing.
- **Summary**: When `bufio.Scanner` encounters an oversized line, the shared reader stops draining the pipe without closing it.
- **Failure scenario**: A child continues writing a long record after the scanner stops. The pipe fills, the child blocks instead of exiting, and Wingmate can stay stuck waiting for the other output reader.
- **Verification note**: A bounded test with the real pipe reader reproduced the scanner error and a writer that remained blocked until its deadline.
- **Recommendations**:
1. **(Recommended)** Keep draining output while capping or splitting individual log records. Raising the scanner limit alone leaves the same failure at a higher threshold.
2. Cover an oversized line followed by ordinary output and verify the stream still completes.
### 9. P1: `wmpidproxy` can signal processes other than its daemon
- **Status**: 🔵 Verified
- **File**: `cmd/pidproxy/pidproxy.go:109–157`
- **Kind**: Security and reliability — a daemon-writable file determines what the proxy can signal.
- **Summary**: The proxy passes unvalidated PID-file contents to `kill` and rereads the file when handling shutdown.
- **Failure scenario**: A nonpositive value has process-group or broadcast semantics rather than identifying one daemon. Even a positive PID can redirect TERM if the file changes after the proxy has checked the original process.
- **Verification note**: A parser probe confirmed that nonpositive values are accepted. The shutdown target was traced in code; no live signals were sent to PID-file targets.
- **Recommendations**:
1. **(Recommended)** Reject values outside the valid positive PID range and bind monitoring and shutdown to the same verified process identity, rather than rereading the target from the file.
2. Cover invalid PID values and a file replacement between monitoring and shutdown.
### 10. P2: Legacy cron commands with arguments don't run
- **Status**: 🔵 Verified
- **File**: `config/crontab.go:76–110`, `cmd/wingmate/bridge.go:45–49`, `task/task.go:40–42`, `init/cron.go:32–39`
- **Kind**: Compatibility — the README promises simple commands with arguments in legacy crontabs.
- **Summary**: The legacy parser passes the whole command field through as one executable name.
- **Failure scenario**: A cron entry ending in `/bin/echo hello` makes Wingmate try to start an executable named `/bin/echo hello`, so the job never runs.
- **Verification note**: A probe followed the crontab through `config.Read()` and `convert()` and confirmed that the task exposes `/bin/echo hello` as the executable and no arguments.
- **Recommendations**:
1. **(Recommended)** Parse the documented simple-command format into an executable and arguments without introducing shell evaluation.
2. Test both executable-only entries and commands with arguments.
### 11. P2: A YAML parse error can leak secrets into logs
- **Status**: 🔵 Verified
- **File**: `config/yaml.go:48–67`
- **Kind**: Security and observability — configuration diagnostics can expose values to log readers.
- **Summary**: A task decode failure logs the entire YAML entry, including unrelated environment values.
- **Failure scenario**: An operator supplies an invalid `startsecs` alongside a valid secret in `environ`. The startup error includes the secret even though the secret had nothing to do with the decode failure.
- **Verification note**: A probe with an invalid `startsecs` captured a fake environment token in the emitted logs.
- **Recommendations**:
1. **(Recommended)** Log the task name and a sanitized field-level error without dumping task values.
2. Assert that a parse error still identifies the failing task while redacting unrelated environment values.
### 12. P2: A failing service can restart continuously without a useful exit diagnostic
- **Status**: 🔵 Verified
- **File**: `init/service.go:71–94`
- **Kind**: Performance and operations — rapid restarts consume resources and obscure why the service is failing.
- **Summary**: The restart loop sleeps after setup or start failures but discards `cmd.Wait()` results and immediately retries when a started child exits.
- **Failure scenario**: A service starts successfully and immediately exits nonzero. Wingmate repeatedly forks the service without a delay or an exit-status diagnostic.
- **Verification note**: A service-loop probe observed two launches of a failing process in about 11 ms.
- **Recommendations**:
1. **(Recommended)** Apply bounded backoff to repeated short-lived exits, interrupt the delay on shutdown, and report the child's exit reason.
2. Test repeated failures and cancellation during the delay.
### 13. P2: Named identities crash `wmexec` instead of working or returning a clear error
- **Status**: 🔵 Verified
- **File**: `cmd/exec/ent.go:1–10`, `cmd/exec/ent_lin.go:12–32`, `cmd/exec/exec.go:106–127`
- **Kind**: Compatibility — the documented account-name syntax depends on the build and the lookup result.
- **Summary**: The CGO-disabled account lookup panics, and the CGO implementation can dereference a null result when a name is missing.
- **Failure scenario**: A CGO-disabled build panics for a valid username. A CGO-enabled build can segfault for an unknown username because `getpwnam` may return null without setting `errno`.
- **Verification note**: Local CLI runs reproduced the panic for an existing named user with CGO disabled and the segmentation fault for an unknown user with CGO enabled.
- **Recommendations**:
1. **(Recommended)** Use an account lookup that works on supported builds and returns a normal error for unknown users and groups.
2. Exercise named and numeric identities in both CGO build configurations.
## Clean areas (checked, no issues found)
- Existing CLI helper and configuration tests passed `go test -race -shuffle=on -count=10 ./cmd/cli ./config`. This run did not cover the supervisor lifecycle.
- With the generated version files present, `go build ./...` passed with CGO enabled and disabled, and `go vet ./...` passed. `go mod verify` also passed. Docker was unavailable, so container packaging and real PID 1 shutdown were not verified.
+8
View File
@@ -0,0 +1,8 @@
# Project tasks
| ID | Task | Status |
| --- | --- | --- |
| WM-001 | [Automate the Docker shutdown integration test](WM-001-docker-shutdown-test.md) | Todo |
| WM-002 | [Add a non-init supervisor mode](WM-002-non-init-supervisor-mode.md) | Todo |
Give each new task a stable ID and a Markdown file with acceptance criteria. Use **Todo**, **In progress**, or **Done** in this index.
+49
View File
@@ -0,0 +1,49 @@
# WM-001: Automate the Docker shutdown integration test
Shutdown is currently tested manually in Docker. Wingmate is designed to act as Linux init: it broadcasts shutdown signals so that even orphaned descendants receive them. Add an opt-in test runner that verifies real signal delivery in disposable containers. The runner must work on a separate Linux test machine without a coding agent and produce a portable diagnostic bundle for analysis back in the development environment.
## Scope
### In scope
- A shell runner, disposable child fixtures, and test-specific Docker setup to build and test the current checkout on Linux.
- Two shutdown scenarios in isolated containers: a child that exits on TERM and a child that stays alive after TERM until Wingmate escalates.
- A portable diagnostic archive and instructions for running the test, finding its results, and bringing them back to the development environment.
### Out of scope
- Changes to Wingmate's production shutdown behavior or PID 1 enforcement.
- Unit-test refactors, CI wiring, and support for other container engines.
- General supervisor coverage, including service restarts, cron scheduling, and orphan reaping.
## Acceptance criteria
- [ ] Provide a standalone shell script with one documented command that builds Wingmate from the current checkout and runs the test on a Linux Docker engine. Document the prerequisites and how to copy the result back. Running `go test ./...` alone does not invoke this test.
- [ ] Start Wingmate directly as PID 1 in a dedicated container PID namespace. Verify that it is PID 1 before sending any shutdown signal. Do not use Docker's `--init`, host PID mode, or another container's PID namespace.
- [ ] In a fresh container with a cooperative child, wait for an explicit readiness marker, send `SIGTERM` to Wingmate through Docker, and verify that the child received `SIGTERM` and Wingmate exited without escalating.
- [ ] In a fresh container with a TERM-resistant child, verify that the child receives `SIGTERM` and stays alive until Wingmate escalates to `SIGKILL`. Send `SIGTERM` without scheduling a Docker fallback kill, and require the container to exit before the test timeout and before forced cleanup.
- [ ] Bound readiness and shutdown waits. Collect diagnostics before removing containers on success or failure. Preserve partial diagnostics if the build fails, a case times out, or a container never starts.
- [ ] Print a concise result for each case and the path to a timestamped diagnostic archive in a caller-selectable output directory. Return a nonzero exit status if setup fails, a case fails, or a case times out.
## Diagnostic bundle
The archive should be usable without access to the test machine or the original containers. Include:
- A plain-text summary with the result of each case, the first failed assertion with expected and actual results, and whether any cases could not run.
- The Git revision and whether the checkout was dirty, the Docker client and engine versions, and the test platform and architecture.
- Build output and timestamped container logs for each case, including Wingmate and child output.
- A timestamped record of the PID 1 and readiness checks, when TERM was sent, any observed escalation, the container exit status, and whether a timeout or forced cleanup occurred.
Capture only the configuration and container metadata needed to diagnose the run. Keep host environment variables and Docker credentials out of the archive.
## Implementation notes
- Use a readiness marker that the child emits after installing its TERM handler. Wait for the marker with a deadline rather than sleeping for a fixed interval.
- Have the TERM-resistant fixture log that it received TERM while continuing to run. Use Wingmate's `start pumping SIGKILL signal` log and the container's exit as evidence of escalation; a container exit alone is insufficient.
- Record the shutdown outcome before forced cleanup so cleanup cannot turn a timeout into a pass. Keep the logs from failures that occur before either shutdown scenario starts.
- Use UTC timestamps across the event timeline and logs so they can be compared after the archive is copied to another machine.
## Relevant code
- [Signal handler](../../init/sighandler.go) and [shutdown escalation](../../init/signal-pump.go)
- [Bookworm Dockerfile](../../docker/bookworm/Dockerfile) and [entrypoint](../../docker/bookworm/entry.sh)
@@ -0,0 +1,32 @@
# WM-002: Add a non-init supervisor mode
Let Wingmate run as an ordinary Linux process under an existing init system, in the spirit of Python's Supervisor. It should start and restart configured programs and shut down only the workloads it owns. The existing container init mode remains the default.
## Scope
### In scope
- An explicit opt-in mode for running Wingmate in the foreground as a regular user, without being PID 1.
- Start, monitor, and restart foreground services using existing YAML and shell-script configurations. Keep existing cron scheduling for supported foreground jobs and apply the same shutdown rules to running jobs.
- Track and reap Wingmate's own child processes. Send shutdown signals only to managed workloads, including descendants that remain in a process group Wingmate created for the workload.
- Document how to select the mode, what it can supervise, and how to configure programs to stay in the foreground.
### Out of scope
- Changes to PID 1 shutdown behavior or the [PID 1 Docker test](WM-001-docker-shutdown-test.md).
- Full Supervisor compatibility, including its configuration format, control socket, web UI, and `supervisorctl`.
- Managing unrelated processes or adopting detached daemons. Supporting PID-file proxying and commands that create a separate session in this mode is deferred.
## Acceptance criteria
- [ ] A documented option starts Wingmate as a non-PID-1, unprivileged Linux process. Existing container invocations still select init mode by default.
- [ ] A configured foreground service starts and restarts after an unexpected exit. When Wingmate begins shutting down, it stops starting new services and cron jobs, and it does not restart processes that exit during shutdown.
- [ ] On shutdown, Wingmate sends TERM to its managed workloads, waits for a bounded grace period, and sends KILL only to managed workloads that remain. It never broadcasts signals or uses a catch-all child reaper in this mode.
- [ ] Unsupported task options, such as `pidfile` and `setsid`, produce a clear error naming the task before any workload starts.
- [ ] Tests cover restart, graceful shutdown, and escalation. A Linux integration test runs Wingmate as non-PID 1 inside an isolated PID namespace and verifies that an unrelated process in the same namespace survives both shutdown paths.
## Implementation notes
- Give each workload its own process group at launch. Wingmate and unrelated processes must stay outside those groups.
- Assign one owner to wait for each direct child. Keep init-mode orphan reaping separate from the non-init execution path.
- Synchronize process starts with shutdown so a child cannot start after shutdown has taken its list of workloads to stop.
+17 -20
View File
@@ -1,36 +1,33 @@
module gitea.suyono.dev/suyono/wingmate
go 1.22.7
go 1.24
toolchain go1.27.3
require (
github.com/rs/zerolog v1.33.0
github.com/spf13/cobra v1.8.1
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.9.0
golang.org/x/sys v0.25.0
github.com/rs/zerolog v1.34.0
github.com/spf13/cobra v1.9.1
github.com/spf13/pflag v1.0.6
github.com/spf13/viper v1.20.1
github.com/stretchr/testify v1.10.0
golang.org/x/sys v0.33.0
)
require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/sagikazarmark/locafero v0.6.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sagikazarmark/locafero v0.9.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.7.0 // indirect
github.com/spf13/afero v1.14.0 // indirect
github.com/spf13/cast v1.8.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect
golang.org/x/text v0.18.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
golang.org/x/text v0.25.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+32 -73
View File
@@ -1,110 +1,69 @@
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pelletier/go-toml/v2 v2.2.0 h1:QLgLl2yMN7N+ruc31VynXs1vhMZa7CeHHejIeBAsoHo=
github.com/pelletier/go-toml/v2 v2.2.0/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/locafero v0.6.0 h1:ON7AQg37yzcRPU69mt7gwhFEBwxI6P9T4Qu3N51bwOk=
github.com/sagikazarmark/locafero v0.6.0/go.mod h1:77OmuIc6VTraTXKXIs/uvUxKGUXjE1GbemJYHqdNjX0=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k=
github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w=
github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=
github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk=
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk=
github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81 h1:6R2FC06FonbXQ8pK11/PDFY6N6LWlf9KlzibaCapmqc=
golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81/go.mod h1:CQ1k9gNrJ50XIzaKCRR2hssIjF07kZFEiieALBM/ARQ=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+9 -10
View File
@@ -18,11 +18,12 @@ func (i *Init) cron(wg *sync.WaitGroup, cron CronTask, exitFlag <-chan any) {
defer wg.Done()
var (
iwg *sync.WaitGroup
err error
stdout io.ReadCloser
stderr io.ReadCloser
cmd *exec.Cmd
iwg *sync.WaitGroup
err error
stdout io.ReadCloser
stderr io.ReadCloser
cmd *exec.Cmd
patchedEnv []string
)
ticker := time.NewTicker(time.Second * 30)
@@ -34,11 +35,9 @@ cron:
wingmate.Log().Error().Str(cronTag, cron.Name()).Msgf("%+v", err)
goto fail
}
cmd = exec.Command(cron.Command(), cron.Arguments()...)
cmd.Env = os.Environ()
if cron.EnvLen() > 0 {
cmd.Env = append(cmd.Env, cron.Environ()...)
}
patchedEnv = cron.PatchEnv(os.Environ())
cmd = exec.Command(cron.Command(patchedEnv...), cron.Arguments(patchedEnv...)...)
cmd.Env = patchedEnv
if len(cron.WorkingDir()) > 0 {
cmd.Dir = cron.WorkingDir()
+3 -2
View File
@@ -23,10 +23,11 @@ type TaskStatus interface {
type Task interface {
Name() string
Command() string
Arguments() []string
Command(...string) string
Arguments(...string) []string
EnvLen() int
Environ() []string
PatchEnv([]string) []string
Setsid() bool
UserGroup() UserGroup
WorkingDir() string
+6 -6
View File
@@ -25,6 +25,7 @@ func (i *Init) service(wg *sync.WaitGroup, task ServiceTask, exitFlag <-chan any
stdout io.ReadCloser
failStatus bool
cmd *exec.Cmd
patchedEnv []string
)
defer func() {
@@ -39,11 +40,10 @@ service:
failStatus = true
goto fail
}
cmd = exec.Command(task.Command(), task.Arguments()...)
cmd.Env = os.Environ()
if task.EnvLen() > 0 {
cmd.Env = append(cmd.Env, task.Environ()...)
}
patchedEnv = task.PatchEnv(os.Environ())
cmd = exec.Command(task.Command(patchedEnv...), task.Arguments(patchedEnv...)...)
cmd.Env = patchedEnv
if len(task.WorkingDir()) > 0 {
cmd.Dir = task.WorkingDir()
@@ -107,5 +107,5 @@ func (i *Init) pipeReader(wg *sync.WaitGroup, pipe io.ReadCloser, tag, serviceNa
wingmate.Log().Error().Str(tag, serviceName).Msgf("got error when reading pipe: %#v", err)
}
wingmate.Log().Info().Str(tag, serviceName).Msg("closing pipe")
wingmate.Log().Debug().Str(tag, serviceName).Msg("closing pipe")
}
+2 -2
View File
@@ -19,14 +19,14 @@ func (i *Init) sighandler(wg *sync.WaitGroup, trigger chan<- any, selfExit <-cha
isOpen := true
c := make(chan os.Signal, 1)
signal.Notify(c, unix.SIGINT, unix.SIGTERM, unix.SIGCHLD)
signal.Notify(c, unix.SIGINT, unix.SIGTERM, unix.SIGQUIT, unix.SIGCHLD)
signal:
for {
select {
case s := <-c:
switch s {
case unix.SIGTERM, unix.SIGINT:
case unix.SIGTERM, unix.SIGINT, unix.SIGQUIT:
if isOpen {
wingmate.Log().Info().Msg("initiating shutdown...")
close(trigger)
+2 -2
View File
@@ -52,9 +52,9 @@ func (i *Init) sigTermPump(startTime time.Time, selfExit <-chan any) status {
t := time.NewTicker(time.Millisecond * 100)
defer t.Stop()
wingmate.Log().Info().Msg("start pumping SIGTERM signal")
wingmate.Log().Debug().Msg("start pumping SIGTERM signal")
defer func() {
wingmate.Log().Info().Msg("stop pumping SIGTERM signal")
wingmate.Log().Debug().Msg("stop pumping SIGTERM signal")
}()
for time.Since(startTime) < time.Duration(time.Second*4) {
+5 -5
View File
@@ -20,7 +20,7 @@ func (i *Init) waiter(wg *sync.WaitGroup, runningFlag <-chan any, sigHandlerFlag
defer wg.Done()
defer func() {
wingmate.Log().Info().Msg("waiter exiting...")
wingmate.Log().Debug().Msg("waiter exiting...")
}()
running = true
@@ -41,7 +41,7 @@ wait:
} else {
select {
case <-runningFlag:
wingmate.Log().Info().Msg("waiter received shutdown signal...")
wingmate.Log().Debug().Msg("waiter received shutdown signal...")
running = false
default:
}
@@ -55,14 +55,14 @@ wait:
if flagged {
close(sigHandlerFlag)
flagged = false
wingmate.Log().Warn().Msg("waiter: inner flag")
wingmate.Log().Debug().Msg("waiter: inner flag")
}
wingmate.Log().Warn().Msg("waiter: no child left")
wingmate.Log().Debug().Msg("waiter: no child left")
break wait
}
}
wingmate.Log().Warn().Msgf("Wait4 returns error: %+v", err)
wingmate.Log().Debug().Msgf("Wait4 returns error: %+v", err)
waitingForSignal = true
}
}
+102 -7
View File
@@ -12,17 +12,44 @@ const (
timeTag = "time"
)
const (
Time = 1 << iota
Caller
)
const (
PanicLevel = 5 - iota
FatalLevel
ErrorLevel
WarnLevel
InfoLevel
DebugLevel
TraceLevel
)
const (
PanicLevelStr = "panic"
FatalLevelStr = "fatal"
ErrorLevelStr = "error"
WarnLevelStr = "warn"
InfoLevelStr = "info"
DebugLevelStr = "debug"
TraceLevelStr = "trace"
)
var (
w *wrapper
)
type wrapper struct {
log zerolog.Logger
log zerolog.Logger
flag int
}
func NewLog(wc io.WriteCloser) error {
func NewLog(wc io.WriteCloser, flag int) error {
w = &wrapper{
log: zerolog.New(wc),
log: zerolog.New(wc),
flag: flag,
}
return nil
}
@@ -34,20 +61,78 @@ func Log() logger.Log {
return w
}
func SetGlobalLevel(level int) {
switch level {
case PanicLevel:
zerolog.SetGlobalLevel(zerolog.PanicLevel)
case FatalLevel:
zerolog.SetGlobalLevel(zerolog.FatalLevel)
case ErrorLevel:
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
case WarnLevel:
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case InfoLevel:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case DebugLevel:
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case TraceLevel:
zerolog.SetGlobalLevel(zerolog.TraceLevel)
}
}
func SetGlobalLevelStr(level string) {
switch level {
case PanicLevelStr:
zerolog.SetGlobalLevel(zerolog.PanicLevel)
case FatalLevelStr:
zerolog.SetGlobalLevel(zerolog.FatalLevel)
case ErrorLevelStr:
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
case WarnLevelStr:
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case InfoLevelStr:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case DebugLevelStr:
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case TraceLevelStr:
zerolog.SetGlobalLevel(zerolog.TraceLevel)
}
}
func (w *wrapper) flagPass(e *zerolog.Event) *zerolog.Event {
if w.flag&Time != 0 {
e = e.Time(timeTag, time.Now())
}
if w.flag&Caller != 0 {
e = e.Caller(2)
}
return e
}
func (w *wrapper) Info() logger.Content {
return (*eventWrapper)(w.log.Info().Time(timeTag, time.Now()))
return (*eventWrapper)(w.flagPass(w.log.Info()))
}
func (w *wrapper) Debug() logger.Content {
return (*eventWrapper)(w.flagPass(w.log.Debug()))
}
func (w *wrapper) Trace() logger.Content {
return (*eventWrapper)(w.flagPass(w.log.Trace()))
}
func (w *wrapper) Warn() logger.Content {
return (*eventWrapper)(w.log.Warn().Time(timeTag, time.Now()))
return (*eventWrapper)(w.flagPass(w.log.Warn()))
}
func (w *wrapper) Error() logger.Content {
return (*eventWrapper)(w.log.Error().Time(timeTag, time.Now()))
return (*eventWrapper)(w.flagPass(w.log.Error()))
}
func (w *wrapper) Fatal() logger.Content {
return (*eventWrapper)(w.log.Fatal().Time(timeTag, time.Now()))
return (*eventWrapper)(w.flagPass(w.log.Fatal()))
}
type eventWrapper zerolog.Event
@@ -69,3 +154,13 @@ func (w *eventWrapper) Err(err error) logger.Content {
rv := (*zerolog.Event)(w).Err(err)
return (*eventWrapper)(rv)
}
func (w *eventWrapper) Caller() logger.Content {
rv := (*zerolog.Event)(w).Caller()
return (*eventWrapper)(rv)
}
func (w *eventWrapper) Time(tag string, now time.Time) logger.Content {
rv := (*zerolog.Event)(w).Time(tag, now)
return (*eventWrapper)(rv)
}
+4 -2
View File
@@ -7,13 +7,15 @@ type Content interface {
Err(error) Content
}
type Level interface {
type LogLevel interface {
Info() Content
Warn() Content
Error() Content
Fatal() Content
Debug() Content
Trace() Content
}
type Log interface {
Level
LogLevel
}
+25 -6
View File
@@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/json"
"fmt"
wmenv "gitea.suyono.dev/suyono/wingmate/task/env"
"time"
"gitea.suyono.dev/suyono/wingmate"
@@ -80,6 +81,7 @@ type CronTask struct {
command []string
cmdLine []string
environ []string
fallbackEnv []string
setsid bool
workingDir string
lastRun time.Time
@@ -106,6 +108,12 @@ func (c *CronTask) SetEnv(envs ...string) *CronTask {
return c
}
func (c *CronTask) SetFallbackEnv(envs ...string) *CronTask {
c.fallbackEnv = make([]string, len(envs))
copy(c.fallbackEnv, envs)
return c
}
func (c *CronTask) SetFlagSetsid(flag bool) *CronTask {
c.setsid = flag
return c
@@ -224,19 +232,25 @@ func (c *CronTask) UtilDepCheck() error {
return nil
}
func (c *CronTask) Command() string {
func (c *CronTask) Command(env ...string) string {
if len(env) > 0 {
return wmenv.ExpandEnv(env, []string{c.cmdLine[0]})[0]
}
return c.cmdLine[0]
}
func (c *CronTask) Arguments() []string {
func (c *CronTask) Arguments(env ...string) []string {
if len(c.cmdLine) == 1 {
return nil
}
retval := make([]string, len(c.cmdLine)-1)
copy(retval, c.cmdLine[1:])
argCopy := make([]string, len(c.cmdLine)-1)
copy(argCopy, c.cmdLine[1:])
if len(env) > 0 {
argCopy = wmenv.ExpandEnv(env, argCopy)
}
return retval
return argCopy
}
func (c *CronTask) EnvLen() int {
@@ -249,6 +263,11 @@ func (c *CronTask) Environ() []string {
return retval
}
func (c *CronTask) PatchEnv(env []string) []string {
env = wmenv.PatchEnv(env, c.environ)
return wmenv.FallbackEnv(env, c.fallbackEnv)
}
func (c *CronTask) Setsid() bool {
return c.setsid
}
@@ -264,7 +283,7 @@ func (c *CronTask) WorkingDir() string {
func (c *CronTask) Status() wminit.TaskStatus {
//TODO: implement me!
panic("not implemented")
return nil
// return nil
}
func (c *CronTask) TimeToRun(now time.Time) bool {
+127
View File
@@ -0,0 +1,127 @@
package env
import (
"fmt"
"gitea.suyono.dev/suyono/wingmate"
"regexp"
"strings"
)
var (
envCapture = regexp.MustCompile(`\$+[a-zA-Z_][a-zA-Z0-9_]*|\$+{[a-zA-Z_][a-zA-Z0-9_]*}`)
envEsc = regexp.MustCompile(`^\$\$+[^$]+$`) // escaped, starts with two or more $ character
envRef = regexp.MustCompile(`^\$([^$]+)$`) // capture the variable name
envRefExplicit = regexp.MustCompile(`^\${([^$]+)}$`) // capture the variable name - explicit
)
func expandEnv(envMap map[string]string, input string) string {
if envEsc.MatchString(input) {
return input
}
if envName := envRefExplicit.FindStringSubmatch(input); envName != nil && envName[1] != "" {
exVal, ok := envMap[envName[1]]
if !ok {
return ""
}
return exVal
}
if envName := envRef.FindStringSubmatch(input); envName != nil && envName[1] != "" {
exVal, ok := envMap[envName[1]]
if !ok {
return ""
}
return exVal
}
return input
}
func PatchEnv(existing, new []string) []string {
tMap := make(map[string]string)
for _, e := range existing {
key, value, ok := strings.Cut(e, "=")
if !ok {
wingmate.Log().Warn().Msgf("removing invalid environment:", e)
continue
}
tMap[key] = value
}
for _, e := range new {
key, value, ok := strings.Cut(e, "=")
if !ok {
wingmate.Log().Warn().Msgf("removing invalid environment:", e)
continue
}
if strings.ContainsAny(key, "$") {
wingmate.Log().Error().Err(fmt.Errorf("variable name contains $")).Msgf("removing invalid environment:", e)
continue
}
value = envCapture.ReplaceAllStringFunc(value, func(rep string) string {
return expandEnv(tMap, rep)
})
tMap[key] = value
}
outEnv := make([]string, 0, len(existing))
for key, val := range tMap {
outEnv = append(outEnv, fmt.Sprintf("%s=%s", key, val))
}
return outEnv
}
func ExpandEnv(env []string, input []string) []string {
envMap := make(map[string]string)
for _, e := range env {
key, value, ok := strings.Cut(e, "=")
if !ok {
wingmate.Log().Warn().Msgf("removing bad environment:", e)
continue
}
envMap[key] = value
}
for i, s := range input {
s = envCapture.ReplaceAllStringFunc(s, func(rep string) string {
return expandEnv(envMap, rep)
})
input[i] = s
}
return input
}
func FallbackEnv(env []string, fallbacks []string) []string {
envMap := make(map[string]string)
for _, e := range env {
key, value, ok := strings.Cut(e, "=")
if !ok {
wingmate.Log().Warn().Msgf("removing bad environment:", e)
continue
}
envMap[key] = value
}
for _, e := range fallbacks {
key, value, ok := strings.Cut(e, "=")
if !ok {
wingmate.Log().Warn().Msgf("removing bad environment:", e)
continue
}
value = envCapture.ReplaceAllStringFunc(value, func(rep string) string {
return expandEnv(envMap, rep)
})
if _, ok = envMap[key]; !ok {
env = append(env, fmt.Sprintf("%s=%s", key, value))
}
}
return env
}
+39 -21
View File
@@ -4,10 +4,9 @@ import (
"crypto/sha256"
"encoding/json"
"fmt"
"gitea.suyono.dev/suyono/wingmate"
wminit "gitea.suyono.dev/suyono/wingmate/init"
wmenv "gitea.suyono.dev/suyono/wingmate/task/env"
)
type config interface {
@@ -69,20 +68,21 @@ func (ts *Tasks) Crones() []wminit.CronTask {
func (ts *Tasks) Get(name string) (wminit.Task, error) {
//TODO: implement me!
panic("not implemented")
return nil, nil
// return nil, nil
}
type ServiceTask struct {
name string
command []string
cmdLine []string
environ []string
setsid bool
background bool
workingDir string
startSecs uint
pidFile string
config config
name string
command []string
cmdLine []string
environ []string
fallbackEnv []string
setsid bool
background bool
workingDir string
startSecs uint
pidFile string
config config
userGroup
}
@@ -104,6 +104,12 @@ func (t *ServiceTask) SetEnv(envs ...string) *ServiceTask {
return t
}
func (t *ServiceTask) SetFallbackEnv(envs ...string) *ServiceTask {
t.fallbackEnv = make([]string, len(envs))
copy(t.fallbackEnv, envs)
return t
}
func (t *ServiceTask) SetFlagSetsid(flag bool) *ServiceTask {
t.setsid = flag
return t
@@ -218,6 +224,7 @@ func (t *ServiceTask) Name() string {
}
func (t *ServiceTask) prepareCommandLine() []string {
//TODO: is this method used somewhere? if not, can I remove this?
if len(t.cmdLine) > 0 {
return t.cmdLine
}
@@ -279,19 +286,25 @@ func (t *ServiceTask) UtilDepCheck() error {
return nil
}
func (t *ServiceTask) Command() string {
func (t *ServiceTask) Command(env ...string) string {
if len(env) > 0 {
return wmenv.ExpandEnv(env, []string{t.cmdLine[0]})[0]
}
return t.cmdLine[0]
}
func (t *ServiceTask) Arguments() []string {
func (t *ServiceTask) Arguments(env ...string) []string {
if len(t.cmdLine) == 1 {
return nil
}
retval := make([]string, len(t.cmdLine)-1)
copy(retval, t.cmdLine[1:])
argCopy := make([]string, len(t.cmdLine)-1)
copy(argCopy, t.cmdLine[1:])
if len(env) > 0 {
argCopy = wmenv.ExpandEnv(env, argCopy)
}
return retval
return argCopy
}
func (t *ServiceTask) EnvLen() int {
@@ -304,6 +317,11 @@ func (t *ServiceTask) Environ() []string {
return retval
}
func (t *ServiceTask) PatchEnv(env []string) []string {
env = wmenv.PatchEnv(env, t.environ)
return wmenv.FallbackEnv(env, t.fallbackEnv)
}
func (t *ServiceTask) Setsid() bool {
return t.setsid
}
@@ -323,19 +341,19 @@ func (t *ServiceTask) WorkingDir() string {
func (t *ServiceTask) Status() wminit.TaskStatus {
//TODO: implement me!
panic("not implemented")
return nil
// return nil
}
func (t *ServiceTask) AutoStart() bool {
//TODO: implement me!
panic("not implemented")
return false
// return false
}
func (t *ServiceTask) AutoRestart() bool {
//TODO: implement me!
panic("not implemented")
return false
// return false
}
func (t *ServiceTask) StartSecs() uint {
+53 -1
View File
@@ -1,9 +1,12 @@
package task
import (
"os"
"testing"
"gitea.suyono.dev/suyono/wingmate"
wminit "gitea.suyono.dev/suyono/wingmate/init"
"github.com/stretchr/testify/assert"
"testing"
)
func TestServicesV0(t *testing.T) {
@@ -77,3 +80,52 @@ func TestTasks_List(t *testing.T) {
assert.ElementsMatch(t, testNames, tnames)
}
func TestServiceTaskPatchEnv(t *testing.T) {
type testEntry struct {
name string
systemEnv []string
serviceEnv []string
expected []string
}
_ = wingmate.NewLog(os.Stderr, wingmate.Caller|wingmate.Time)
tests := []testEntry{
{
name: "normal",
systemEnv: []string{"PATH=/bin:/usr/bin:/usr/local/bin"},
serviceEnv: []string{
"SPARK_HOME=/opt/spark",
"PATH=$SPARK_HOME/bin:$PATH",
},
expected: []string{
"SPARK_HOME=/opt/spark",
"PATH=/opt/spark/bin:/bin:/usr/bin:/usr/local/bin",
},
},
{
name: "explicit",
systemEnv: []string{"PART=hello "},
serviceEnv: []string{"GREET=${PART}world"},
expected: []string{"PART=hello ", "GREET=hello world"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Run("service", func(t *testing.T) {
st := NewServiceTask(tt.name)
st.SetEnv(tt.serviceEnv...)
result := st.PatchEnv(tt.systemEnv)
assert.ElementsMatch(t, result, tt.expected)
})
t.Run("cron", func(t *testing.T) {
st := NewCronTask(tt.name)
st.SetEnv(tt.serviceEnv...)
result := st.PatchEnv(tt.systemEnv)
assert.ElementsMatch(t, result, tt.expected)
})
})
}
}