6 Commits
wip2 ... main

30 changed files with 458 additions and 216 deletions

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:])

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

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)

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

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

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",

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",

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",

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" ]

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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

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" ]

35
go.mod
View File

@@ -1,36 +1,31 @@
module gitea.suyono.dev/suyono/wingmate
go 1.22.7
go 1.24
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
)

105
go.sum
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=

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

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

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

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)

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

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
}
}

109
logger.go
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)
}

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
}

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
task/env/env.go vendored Normal file
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
}

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 {

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