Skip to content

Commit

Permalink
rework
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasng committed Dec 8, 2019
1 parent 942b0f0 commit 401b1f8
Show file tree
Hide file tree
Showing 19 changed files with 409 additions and 647 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.idea/
.vscode/

dist/
log/
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
[![codecov](https://codecov.io/gh/matthiasng/service-shark/branch/master/graph/badge.svg)](https://codecov.io/gh/matthiasng/service-shark)
[![Go Report Card](https://goreportcard.com/badge/github.com/matthiasng/service-wrapper)](https://goreportcard.com/report/github.com/matthiasng/service-wrapper)

Service Shark can be used to to host any executable as an Windows service.
Service Shark can be used to to host any executable as a Windows service.

Service Shark is:
- easy to use
Expand All @@ -23,7 +23,7 @@ Service Shark is not:

#### Download from github
```
https://github.com/matthiasng/service-shark/releases/latest)
https://github.com/matthiasng/service-shark/releases/latest
```

#### Scoop
Expand Down
9 changes: 9 additions & 0 deletions cli/arguments.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package cli

type Arguments struct {
Name string
WorkingDirectory string
LogDirectory string
Command string
CommandArguments []string
}
21 changes: 0 additions & 21 deletions cli/cli.go

This file was deleted.

1 change: 0 additions & 1 deletion cli/cli_test.go

This file was deleted.

21 changes: 21 additions & 0 deletions cli/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package cli

import (
"os"
"strings"
)

// ExpandArguments replace all "env:" arguments
func ExpandArguments(args []string) []string {
result := []string{}

for _, arg := range args {
if strings.HasPrefix(arg, "env:") {
result = append(result, os.Getenv(strings.TrimLeft(arg, "env:")))
} else {
result = append(result, arg)
}
}

return result
}
23 changes: 23 additions & 0 deletions cli/env_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package cli

import (
"os"
"testing"

"github.com/stretchr/testify/require"
)

func Test_ExpandArguments(t *testing.T) {
require := require.New(t)

os.Setenv("_ENV_VAL_", "123")
result := ExpandArguments([]string{
"normal",
"-test", "env:_ENV_VAL_",
})

require.Equal(result, []string{
"normal",
"-test", "123",
})
}
22 changes: 22 additions & 0 deletions cli/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package cli

import (
"errors"
)

// Validate command line arguments
func Validate(arguments Arguments) error {
if len(arguments.Name) == 0 {
return errors.New("Name not set (-name)")
}

if len(arguments.WorkingDirectory) == 0 {
return errors.New("Working directory not set (-workdir)")
}

if len(arguments.Command) == 0 {
return errors.New("Command not set (-cmd)")
}

return nil
}
23 changes: 23 additions & 0 deletions cli/validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package cli

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_Validate(t *testing.T) {
require := require.New(t)

args := Arguments{}
require.Error(Validate(args))

args.Name = "123"
require.Error(Validate(args))

args.WorkingDirectory = "C:/"
require.Error(Validate(args))

args.Command = "_unknown_"
require.NoError(Validate(args))
}
23 changes: 11 additions & 12 deletions command/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,29 @@ import (
"path"
"time"

"github.com/matthiasng/service-shark/cli"
"github.com/matthiasng/service-shark/service"
)

type Config struct {
Name string
Arguments []string
}

type Host struct {
CmdConfig Config
LogDirecotry string
Arguments cli.Arguments
cmd *exec.Cmd
logFile *os.File
quitSignal chan struct{}
quitCompleted chan struct{}
}

func (h *Host) init(env service.Environment) error {
h.cmd = exec.Command(h.CmdConfig.Name, h.CmdConfig.Arguments...)
h.cmd = exec.Command(h.Arguments.Command, h.Arguments.CommandArguments...)

if env.IsWindowsService() {
err := os.MkdirAll(h.LogDirecotry, os.ModePerm)
err := os.MkdirAll(h.Arguments.LogDirectory, os.ModePerm)
if err != nil {
return err
}

logFileName := fmt.Sprintf("%s_%s.log", env.Name(), time.Now().Format("02-01-2006_15-04-05"))
logFilePath := path.Join(h.LogDirecotry, logFileName)
logFileName := fmt.Sprintf("%s_%s.log", h.Name(), time.Now().Format("02-01-2006_15-04-05"))
logFilePath := path.Join(h.Arguments.LogDirectory, logFileName)

logFile, err := os.Create(logFilePath)
if err != nil {
Expand Down Expand Up @@ -62,7 +57,7 @@ func (h *Host) Start(env service.Environment) error {

go func() {
<-h.quitSignal
_ = h.cmd.Process.Kill() // #todo kill child process. Test Command -> "C:/Program Files/PowerShell/7-preview/preview/pwsh-preview.cmd"
_ = h.cmd.Process.Kill()
close(h.quitCompleted)
}()

Expand All @@ -82,3 +77,7 @@ func (h *Host) Stop() error {

return nil
}

func (h *Host) Name() string {
return h.Arguments.Name
}
20 changes: 10 additions & 10 deletions example/test-example-service.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,24 @@ $psTestScript = "$PSScriptRoot/test-service.ps1"

$serviceName = "ExampleService-" + (New-Guid)

$serviceLogDirecotry = "$PSScriptRoot/log"
$serviceWorkingDir = $PSScriptRoot
$serviceCommand = $currentPwshExe

$serviceSharkPath = "$PSScriptRoot/../service-shark.exe"

if(!(Test-Path $serviceSharkPath)) {
Write-Host "Run: go build -o service-shark.exe .\main.go"
Write-Host "service-shark.exe not found. Run 'go build -o service-shark.exe .\main.go'"
exit
}

$serviceBinPath = $serviceSharkPath
$serviceBinPath += ' -n "' + $serviceName + '"'
$serviceBinPath += ' -l "' + $serviceLogDirecotry + '"'
$serviceBinPath += ' -c "' + $serviceCommand + '"'
$serviceBinPath += ' -a "' + $psTestScript + '"'
$serviceBinPath += ' -a "-Message" -a "TestMessage with space!"'
$serviceBinPath += ' -a "-PathVar" -a "bind:PATH"'
$serviceBinPath += ' -name "' + $serviceName + '"'
$serviceBinPath += ' -workdir "' + $serviceWorkingDir + '"'
$serviceBinPath += ' -cmd "' + $serviceCommand + '"'
$serviceBinPath += ' --'
$serviceBinPath += ' "' + $psTestScript + '"'
$serviceBinPath += ' -Message "TestMessage with space!"'
$serviceBinPath += ' -PathVar "env:PATH"'


Write-Host "New-Service:"
Expand All @@ -33,8 +34,7 @@ try {
Start-Service -Name $serviceName

Start-Sleep(5)
}
finally {
} finally {
Stop-Service -Name $serviceName
Remove-Service -Name $serviceName
}
3 changes: 1 addition & 2 deletions example/test-service.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ while($true) {
Write-Host "Loop $i : $Message"

if($i % 2 -eq 0) {
#todo stderr
Write-Host "Error $i : $Message"
Write-Error "Error $i : $Message"
}

$i++
Expand Down
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ module github.com/matthiasng/service-shark

go 1.13

require golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e
require (
github.com/stretchr/testify v1.4.0
golang.org/x/sys v0.0.0-20191206214222-bc7efcf3b808
)
15 changes: 13 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e h1:9vRrk9YW2BTzLP0VCB9ZDjU4cPqkg+IDWL7XgxA1yxQ=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
golang.org/x/sys v0.0.0-20191206214222-bc7efcf3b808 h1:FxzWWtFesyhA6D5ohpa+/OJY+9XOBoQtdnjgepvfOIs=
golang.org/x/sys v0.0.0-20191206214222-bc7efcf3b808/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
74 changes: 36 additions & 38 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,54 +1,52 @@
package main

import (
"flag"
"fmt"
"log"
"os"

"github.com/matthiasng/service-shark/cli"
"github.com/matthiasng/service-shark/command"
"github.com/matthiasng/service-shark/service"
)

// #todo working directory

// parser := argparse.NewParser("service-wrapper", `Run a "-command" with "-arguments" as service`)

// serviceName := parser.String("n", "name", &argparse.Options{
// Required: true,
// Help: "Servicename",
// })
// logDirectory := parser.String("l", "logdirectory", &argparse.Options{
// Required: true,
// Help: "Log directory",
// })
// command := parser.String("c", "command", &argparse.Options{
// Required: true,
// Help: "Command",
// })
// arguments := parser.List("a", "arg", &argparse.Options{
// Required: true,
// Help: `Command arguments. Example: '... -a "-key" -a "value" -a "--key2" -a "value"'`,
// })

// err := parser.Parse(os.Args)
// if err != nil {
// fmt.Print(parser.Usage(err))
// os.Exit(2)
// }

// cli.BindArguments(*arguments),
var arguments = cli.Arguments{}

func init() {
flag.CommandLine.Usage = func() {
fmt.Println("Usage of Service Shark:")
flag.PrintDefaults()
}

flag.StringVar(&arguments.Name, "name", "", "Service name [required]")
flag.StringVar(&arguments.WorkingDirectory, "workdir", "", "Working directory [required]")
flag.StringVar(&arguments.LogDirectory, "logdir", "./log", "Log directory. Absolute path or relative to working directory.")
flag.StringVar(&arguments.Command, "cmd", "", "Command [required]")

flag.Parse()
}

func main() {
if err := service.FixWorkingDirectory(); err != nil {
log.Fatal(err)
}

arguments.CommandArguments = cli.ExpandArguments(flag.Args())

if err := cli.Validate(arguments); err != nil {
log.Fatal(err)
}

if err := os.Chdir(arguments.WorkingDirectory); err != nil {
log.Fatal(err)
}

host := command.Host{
CmdConfig: command.Config{
//Name: "powershell",
Name: "C:/Program Files/PowerShell/7-preview/preview/pwsh-preview.cmd",
Arguments: []string{
`P:\_dev\projects\service-shark\example\test-service.ps1`,
},
},
LogDirecotry: "c:/tmp",
Arguments: arguments,
}

if err := service.Run(&host, "todo"); err != nil {
log.Fatalf("[error] - %v", err)
if err := service.Run(&host); err != nil {
log.Fatal(err)
}
}
Loading

0 comments on commit 401b1f8

Please sign in to comment.