1
mirror of https://github.com/rclone/rclone synced 2024-11-10 08:08:35 +01:00

added dependency github.com/sevlyar/go-daemon

This commit is contained in:
ishuah 2018-02-27 22:46:50 +03:00 committed by Ishuah Kariuki
parent fe8eeec5b5
commit 90af7af9a3
39 changed files with 2377 additions and 137 deletions

165
Gopkg.lock generated
View File

@ -4,11 +4,7 @@
[[projects]]
branch = "master"
name = "bazil.org/fuse"
packages = [
".",
"fs",
"fuseutil"
]
packages = [".","fs","fuseutil"]
revision = "371fbbdaa8987b715bdd21d6adc4c9b20155f748"
[[projects]]
@ -25,12 +21,7 @@
[[projects]]
name = "github.com/Azure/go-autorest"
packages = [
"autorest",
"autorest/adal",
"autorest/azure",
"autorest/date"
]
packages = ["autorest","autorest/adal","autorest/azure","autorest/date"]
revision = "6311d7a76f54cf2b6dea03d737d9bd9a6022ac5f"
version = "v9.7.1"
@ -61,35 +52,7 @@
[[projects]]
branch = "master"
name = "github.com/aws/aws-sdk-go"
packages = [
"aws",
"aws/awserr",
"aws/awsutil",
"aws/client",
"aws/client/metadata",
"aws/corehandlers",
"aws/credentials",
"aws/credentials/ec2rolecreds",
"aws/credentials/endpointcreds",
"aws/credentials/stscreds",
"aws/defaults",
"aws/ec2metadata",
"aws/endpoints",
"aws/request",
"aws/session",
"aws/signer/v4",
"internal/shareddefaults",
"private/protocol",
"private/protocol/query",
"private/protocol/query/queryutil",
"private/protocol/rest",
"private/protocol/restxml",
"private/protocol/xml/xmlutil",
"service/s3",
"service/s3/s3iface",
"service/s3/s3manager",
"service/sts"
]
packages = ["aws","aws/awserr","aws/awsutil","aws/client","aws/client/metadata","aws/corehandlers","aws/credentials","aws/credentials/ec2rolecreds","aws/credentials/endpointcreds","aws/credentials/stscreds","aws/defaults","aws/ec2metadata","aws/endpoints","aws/request","aws/session","aws/signer/v4","internal/shareddefaults","private/protocol","private/protocol/query","private/protocol/query/queryutil","private/protocol/rest","private/protocol/restxml","private/protocol/xml/xmlutil","service/s3","service/s3/s3iface","service/s3/s3manager","service/sts"]
revision = "2fe57096de348e6cff4031af99254613f8ef73ea"
[[projects]]
@ -131,12 +94,7 @@
[[projects]]
branch = "master"
name = "github.com/dropbox/dropbox-sdk-go-unofficial"
packages = [
"dropbox",
"dropbox/async",
"dropbox/file_properties",
"dropbox/files"
]
packages = ["dropbox","dropbox/async","dropbox/file_properties","dropbox/files"]
revision = "9c27e83ceccc8f8bbc9afdc17c50798529d608b1"
[[projects]]
@ -174,6 +132,12 @@
packages = ["."]
revision = "0b12d6b5"
[[projects]]
branch = "master"
name = "github.com/kardianos/osext"
packages = ["."]
revision = "ae77be60afb1dcacde03767a8c37337fad28ac14"
[[projects]]
branch = "master"
name = "github.com/kr/fs"
@ -223,13 +187,7 @@
[[projects]]
name = "github.com/pengsrc/go-shared"
packages = [
"buffer",
"check",
"convert",
"log",
"reopen"
]
packages = ["buffer","check","convert","log","reopen"]
revision = "b98065a377794d577e2a0e32869378b9ce4b8952"
version = "v0.1.1"
@ -269,6 +227,12 @@
revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3"
version = "v1.2.0"
[[projects]]
name = "github.com/sevlyar/go-daemon"
packages = ["."]
revision = "e49ef56654f54139c4dc0285f973f74e9649e729"
version = "v0.1.2"
[[projects]]
branch = "master"
name = "github.com/skratchdot/open-golang"
@ -278,10 +242,7 @@
[[projects]]
branch = "master"
name = "github.com/spf13/cobra"
packages = [
".",
"doc"
]
packages = [".","doc"]
revision = "0c34d16c3123764e413b9ed982ada58b1c3d53ea"
[[projects]]
@ -293,10 +254,7 @@
[[projects]]
branch = "master"
name = "github.com/stretchr/testify"
packages = [
"assert",
"require"
]
packages = ["assert","require"]
revision = "87b1dfb5b2fa649f52695dd9eae19abe404a4308"
[[projects]]
@ -307,87 +265,38 @@
[[projects]]
name = "github.com/yunify/qingstor-sdk-go"
packages = [
".",
"config",
"logger",
"request",
"request/builder",
"request/data",
"request/errors",
"request/signer",
"request/unpacker",
"service",
"utils"
]
packages = [".","config","logger","request","request/builder","request/data","request/errors","request/signer","request/unpacker","service","utils"]
revision = "51fa3b6bb3c24f4d646eefff251cd2e6ba716600"
version = "v2.2.9"
[[projects]]
branch = "master"
name = "golang.org/x/crypto"
packages = [
"bcrypt",
"blowfish",
"curve25519",
"ed25519",
"ed25519/internal/edwards25519",
"nacl/secretbox",
"pbkdf2",
"poly1305",
"salsa20/salsa",
"scrypt",
"ssh",
"ssh/agent",
"ssh/terminal"
]
packages = ["bcrypt","blowfish","curve25519","ed25519","ed25519/internal/edwards25519","nacl/secretbox","pbkdf2","poly1305","salsa20/salsa","scrypt","ssh","ssh/agent","ssh/terminal"]
revision = "13931e22f9e72ea58bb73048bc752b48c6d4d4ac"
[[projects]]
branch = "master"
name = "golang.org/x/net"
packages = [
"context",
"context/ctxhttp",
"html",
"html/atom",
"webdav",
"webdav/internal/xml"
]
packages = ["context","context/ctxhttp","html","html/atom","webdav","webdav/internal/xml"]
revision = "5ccada7d0a7ba9aeb5d3aca8d3501b4c2a509fec"
[[projects]]
branch = "master"
name = "golang.org/x/oauth2"
packages = [
".",
"google",
"internal",
"jws",
"jwt"
]
packages = [".","google","internal","jws","jwt"]
revision = "30785a2c434e431ef7c507b54617d6a951d5f2b4"
[[projects]]
branch = "master"
name = "golang.org/x/sys"
packages = [
"unix",
"windows"
]
packages = ["unix","windows"]
revision = "fff93fa7cd278d84afc205751523809c464168ab"
[[projects]]
branch = "master"
name = "golang.org/x/text"
packages = [
"internal/gen",
"internal/triegen",
"internal/ucd",
"transform",
"unicode/cldr",
"unicode/norm"
]
packages = ["internal/gen","internal/triegen","internal/ucd","transform","unicode/cldr","unicode/norm"]
revision = "e19ae1496984b1c655b8044a65c0300a3c878dd3"
[[projects]]
@ -399,30 +308,12 @@
[[projects]]
branch = "master"
name = "google.golang.org/api"
packages = [
"drive/v3",
"gensupport",
"googleapi",
"googleapi/internal/uritemplates",
"storage/v1"
]
packages = ["drive/v3","gensupport","googleapi","googleapi/internal/uritemplates","storage/v1"]
revision = "de3aa2cfa7f1c18dcb7f91738099bad280117b8e"
[[projects]]
name = "google.golang.org/appengine"
packages = [
".",
"internal",
"internal/app_identity",
"internal/base",
"internal/datastore",
"internal/log",
"internal/modules",
"internal/remote_api",
"internal/urlfetch",
"log",
"urlfetch"
]
packages = [".","internal","internal/app_identity","internal/base","internal/datastore","internal/log","internal/modules","internal/remote_api","internal/urlfetch","log","urlfetch"]
revision = "150dc57a1b433e64154302bdc40b6bb8aefa313a"
version = "v1.0.0"
@ -435,6 +326,6 @@
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "bbb981a57fa3540cbfdf3f4255a8eb6b7b9980af2259cffab2f0eddcc3818bcc"
inputs-digest = "b055fbeaf874ae057930914057a0c6b9f76272af6d736500fe1ea03b0a386860"
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -148,3 +148,7 @@
[[constraint]]
branch = "master"
name = "github.com/okzk/sdnotify"
[[constraint]]
name = "github.com/sevlyar/go-daemon"
version = "0.1.2"

27
vendor/github.com/kardianos/osext/LICENSE generated vendored Normal file
View File

@ -0,0 +1,27 @@
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

21
vendor/github.com/kardianos/osext/README.md generated vendored Normal file
View File

@ -0,0 +1,21 @@
### Extensions to the "os" package.
[![GoDoc](https://godoc.org/github.com/kardianos/osext?status.svg)](https://godoc.org/github.com/kardianos/osext)
## Find the current Executable and ExecutableFolder.
As of go1.8 the Executable function may be found in `os`. The Executable function
in the std lib `os` package is used if available.
There is sometimes utility in finding the current executable file
that is running. This can be used for upgrading the current executable
or finding resources located relative to the executable file. Both
working directory and the os.Args[0] value are arbitrary and cannot
be relied on; os.Args[0] can be "faked".
Multi-platform and supports:
* Linux
* OS X
* Windows
* Plan 9
* BSDs.

33
vendor/github.com/kardianos/osext/osext.go generated vendored Normal file
View File

@ -0,0 +1,33 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Extensions to the standard "os" package.
package osext // import "github.com/kardianos/osext"
import "path/filepath"
var cx, ce = executableClean()
func executableClean() (string, error) {
p, err := executable()
return filepath.Clean(p), err
}
// Executable returns an absolute path that can be used to
// re-invoke the current program.
// It may not be valid after the current program exits.
func Executable() (string, error) {
return cx, ce
}
// Returns same path as Executable, returns just the folder
// path. Excludes the executable name and any trailing slash.
func ExecutableFolder() (string, error) {
p, err := Executable()
if err != nil {
return "", err
}
return filepath.Dir(p), nil
}

9
vendor/github.com/kardianos/osext/osext_go18.go generated vendored Normal file
View File

@ -0,0 +1,9 @@
//+build go1.8,!openbsd
package osext
import "os"
func executable() (string, error) {
return os.Executable()
}

22
vendor/github.com/kardianos/osext/osext_plan9.go generated vendored Normal file
View File

@ -0,0 +1,22 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//+build !go1.8
package osext
import (
"os"
"strconv"
"syscall"
)
func executable() (string, error) {
f, err := os.Open("/proc/" + strconv.Itoa(os.Getpid()) + "/text")
if err != nil {
return "", err
}
defer f.Close()
return syscall.Fd2path(int(f.Fd()))
}

36
vendor/github.com/kardianos/osext/osext_procfs.go generated vendored Normal file
View File

@ -0,0 +1,36 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !go1.8,android !go1.8,linux !go1.8,netbsd !go1.8,solaris !go1.8,dragonfly
package osext
import (
"errors"
"fmt"
"os"
"runtime"
"strings"
)
func executable() (string, error) {
switch runtime.GOOS {
case "linux", "android":
const deletedTag = " (deleted)"
execpath, err := os.Readlink("/proc/self/exe")
if err != nil {
return execpath, err
}
execpath = strings.TrimSuffix(execpath, deletedTag)
execpath = strings.TrimPrefix(execpath, deletedTag)
return execpath, nil
case "netbsd":
return os.Readlink("/proc/curproc/exe")
case "dragonfly":
return os.Readlink("/proc/curproc/file")
case "solaris":
return os.Readlink(fmt.Sprintf("/proc/%d/path/a.out", os.Getpid()))
}
return "", errors.New("ExecPath not implemented for " + runtime.GOOS)
}

126
vendor/github.com/kardianos/osext/osext_sysctl.go generated vendored Normal file
View File

@ -0,0 +1,126 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !go1.8,darwin !go1.8,freebsd openbsd
package osext
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"syscall"
"unsafe"
)
var initCwd, initCwdErr = os.Getwd()
func executable() (string, error) {
var mib [4]int32
switch runtime.GOOS {
case "freebsd":
mib = [4]int32{1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1}
case "darwin":
mib = [4]int32{1 /* CTL_KERN */, 38 /* KERN_PROCARGS */, int32(os.Getpid()), -1}
case "openbsd":
mib = [4]int32{1 /* CTL_KERN */, 55 /* KERN_PROC_ARGS */, int32(os.Getpid()), 1 /* KERN_PROC_ARGV */}
}
n := uintptr(0)
// Get length.
_, _, errNum := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, 0, uintptr(unsafe.Pointer(&n)), 0, 0)
if errNum != 0 {
return "", errNum
}
if n == 0 { // This shouldn't happen.
return "", nil
}
buf := make([]byte, n)
_, _, errNum = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)), 0, 0)
if errNum != 0 {
return "", errNum
}
if n == 0 { // This shouldn't happen.
return "", nil
}
var execPath string
switch runtime.GOOS {
case "openbsd":
// buf now contains **argv, with pointers to each of the C-style
// NULL terminated arguments.
var args []string
argv := uintptr(unsafe.Pointer(&buf[0]))
Loop:
for {
argp := *(**[1 << 20]byte)(unsafe.Pointer(argv))
if argp == nil {
break
}
for i := 0; uintptr(i) < n; i++ {
// we don't want the full arguments list
if string(argp[i]) == " " {
break Loop
}
if argp[i] != 0 {
continue
}
args = append(args, string(argp[:i]))
n -= uintptr(i)
break
}
if n < unsafe.Sizeof(argv) {
break
}
argv += unsafe.Sizeof(argv)
n -= unsafe.Sizeof(argv)
}
execPath = args[0]
// There is no canonical way to get an executable path on
// OpenBSD, so check PATH in case we are called directly
if execPath[0] != '/' && execPath[0] != '.' {
execIsInPath, err := exec.LookPath(execPath)
if err == nil {
execPath = execIsInPath
}
}
default:
for i, v := range buf {
if v == 0 {
buf = buf[:i]
break
}
}
execPath = string(buf)
}
var err error
// execPath will not be empty due to above checks.
// Try to get the absolute path if the execPath is not rooted.
if execPath[0] != '/' {
execPath, err = getAbs(execPath)
if err != nil {
return execPath, err
}
}
// For darwin KERN_PROCARGS may return the path to a symlink rather than the
// actual executable.
if runtime.GOOS == "darwin" {
if execPath, err = filepath.EvalSymlinks(execPath); err != nil {
return execPath, err
}
}
return execPath, nil
}
func getAbs(execPath string) (string, error) {
if initCwdErr != nil {
return execPath, initCwdErr
}
// The execPath may begin with a "../" or a "./" so clean it first.
// Join the two paths, trailing and starting slashes undetermined, so use
// the generic Join function.
return filepath.Join(initCwd, filepath.Clean(execPath)), nil
}

203
vendor/github.com/kardianos/osext/osext_test.go generated vendored Normal file
View File

@ -0,0 +1,203 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin linux freebsd netbsd windows openbsd
package osext
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
)
const (
executableEnvVar = "OSTEST_OUTPUT_EXECUTABLE"
executableEnvValueMatch = "match"
executableEnvValueDelete = "delete"
)
func TestPrintExecutable(t *testing.T) {
ef, err := Executable()
if err != nil {
t.Fatalf("Executable failed: %v", err)
}
t.Log("Executable:", ef)
}
func TestPrintExecutableFolder(t *testing.T) {
ef, err := ExecutableFolder()
if err != nil {
t.Fatalf("ExecutableFolder failed: %v", err)
}
t.Log("Executable Folder:", ef)
}
func TestExecutableFolder(t *testing.T) {
ef, err := ExecutableFolder()
if err != nil {
t.Fatalf("ExecutableFolder failed: %v", err)
}
if ef[len(ef)-1] == filepath.Separator {
t.Fatal("ExecutableFolder ends with a trailing slash.")
}
}
func TestExecutableMatch(t *testing.T) {
ep, err := Executable()
if err != nil {
t.Fatalf("Executable failed: %v", err)
}
// fullpath to be of the form "dir/prog".
dir := filepath.Dir(filepath.Dir(ep))
fullpath, err := filepath.Rel(dir, ep)
if err != nil {
t.Fatalf("filepath.Rel: %v", err)
}
// Make child start with a relative program path.
// Alter argv[0] for child to verify getting real path without argv[0].
cmd := &exec.Cmd{
Dir: dir,
Path: fullpath,
Env: []string{fmt.Sprintf("%s=%s", executableEnvVar, executableEnvValueMatch)},
}
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("exec(self) failed: %v", err)
}
outs := string(out)
if !filepath.IsAbs(outs) {
t.Fatalf("Child returned %q, want an absolute path", out)
}
if !sameFile(outs, ep) {
t.Fatalf("Child returned %q, not the same file as %q", out, ep)
}
}
func TestExecutableDelete(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip()
}
fpath, err := Executable()
if err != nil {
t.Fatalf("Executable failed: %v", err)
}
r, w := io.Pipe()
stderrBuff := &bytes.Buffer{}
stdoutBuff := &bytes.Buffer{}
cmd := &exec.Cmd{
Path: fpath,
Env: []string{fmt.Sprintf("%s=%s", executableEnvVar, executableEnvValueDelete)},
Stdin: r,
Stderr: stderrBuff,
Stdout: stdoutBuff,
}
err = cmd.Start()
if err != nil {
t.Fatalf("exec(self) start failed: %v", err)
}
tempPath := fpath + "_copy"
_ = os.Remove(tempPath)
err = copyFile(tempPath, fpath)
if err != nil {
t.Fatalf("copy file failed: %v", err)
}
err = os.Remove(fpath)
if err != nil {
t.Fatalf("remove running test file failed: %v", err)
}
err = os.Rename(tempPath, fpath)
if err != nil {
t.Fatalf("rename copy to previous name failed: %v", err)
}
w.Write([]byte{0})
w.Close()
err = cmd.Wait()
if err != nil {
t.Fatalf("exec wait failed: %v", err)
}
childPath := stderrBuff.String()
if !filepath.IsAbs(childPath) {
t.Fatalf("Child returned %q, want an absolute path", childPath)
}
if !sameFile(childPath, fpath) {
t.Fatalf("Child returned %q, not the same file as %q", childPath, fpath)
}
}
func sameFile(fn1, fn2 string) bool {
fi1, err := os.Stat(fn1)
if err != nil {
return false
}
fi2, err := os.Stat(fn2)
if err != nil {
return false
}
return os.SameFile(fi1, fi2)
}
func copyFile(dest, src string) error {
df, err := os.Create(dest)
if err != nil {
return err
}
defer df.Close()
sf, err := os.Open(src)
if err != nil {
return err
}
defer sf.Close()
_, err = io.Copy(df, sf)
return err
}
func TestMain(m *testing.M) {
env := os.Getenv(executableEnvVar)
switch env {
case "":
os.Exit(m.Run())
case executableEnvValueMatch:
// First chdir to another path.
dir := "/"
if runtime.GOOS == "windows" {
dir = filepath.VolumeName(".")
}
os.Chdir(dir)
if ep, err := Executable(); err != nil {
fmt.Fprint(os.Stderr, "ERROR: ", err)
} else {
fmt.Fprint(os.Stderr, ep)
}
case executableEnvValueDelete:
bb := make([]byte, 1)
var err error
n, err := os.Stdin.Read(bb)
if err != nil {
fmt.Fprint(os.Stderr, "ERROR: ", err)
os.Exit(2)
}
if n != 1 {
fmt.Fprint(os.Stderr, "ERROR: n != 1, n == ", n)
os.Exit(2)
}
if ep, err := Executable(); err != nil {
fmt.Fprint(os.Stderr, "ERROR: ", err)
} else {
fmt.Fprint(os.Stderr, ep)
}
}
os.Exit(0)
}

36
vendor/github.com/kardianos/osext/osext_windows.go generated vendored Normal file
View File

@ -0,0 +1,36 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//+build !go1.8
package osext
import (
"syscall"
"unicode/utf16"
"unsafe"
)
var (
kernel = syscall.MustLoadDLL("kernel32.dll")
getModuleFileNameProc = kernel.MustFindProc("GetModuleFileNameW")
)
// GetModuleFileName() with hModule = NULL
func executable() (exePath string, err error) {
return getModuleFileName()
}
func getModuleFileName() (string, error) {
var n uint32
b := make([]uint16, syscall.MAX_PATH)
size := uint32(len(b))
r0, _, e1 := getModuleFileNameProc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size))
n = uint32(r0)
if n == 0 {
return "", e1
}
return string(utf16.Decode(b[0:n])), nil
}

14
vendor/github.com/sevlyar/go-daemon/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,14 @@
language: go
go:
- 1.3
- tip
before_install:
- go get -t -v ./...
script:
- go test -coverprofile=coverage.txt -covermode=atomic
after_success:
- bash <(curl -s https://codecov.io/bash)

7
vendor/github.com/sevlyar/go-daemon/LICENSE generated vendored Normal file
View File

@ -0,0 +1,7 @@
Copyright (C) 2013 Sergey Yarmonov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

63
vendor/github.com/sevlyar/go-daemon/README.md generated vendored Normal file
View File

@ -0,0 +1,63 @@
# go-daemon [![Build Status](https://travis-ci.org/sevlyar/go-daemon.svg?branch=master)](https://travis-ci.org/sevlyar/go-daemon) [![GoDoc](https://godoc.org/github.com/sevlyar/go-daemon?status.svg)](https://godoc.org/github.com/sevlyar/go-daemon)
Library for writing system daemons in Go.
Now supported only UNIX-based OS (Windows is not supported). But the library was tested only on Linux
and OSX, so that if you have an ability to test the library on other platforms, give me feedback, please (#26).
*Please, feel free to send me bug reports and fixes. Many thanks to all contributors.*
## Features
* Goroutine-safe daemonization;
* Out of box work with pid-files;
* Easy handling of system signals;
* The control of a daemon.
## Installation
go get github.com/sevlyar/go-daemon
You can use [gopkg.in](http://labix.org/gopkg.in):
go get gopkg.in/sevlyar/go-daemon.v0
If you want to use the library in production project, please use vendoring,
because i can not ensure backward compatibility before release v1.0.
## Examples
* [Simple](examples/cmd/gd-simple/)
* [Log rotation](examples/cmd/gd-log-rotation/)
* [Signal handling](examples/cmd/gd-signal-handling/)
## Documentation
[godoc.org/github.com/sevlyar/go-daemon](https://godoc.org/github.com/sevlyar/go-daemon)
## How it works
We can not use `fork` syscall in Golang's runtime, because child process doesn't inherit
threads and goroutines in that case. The library uses a simple trick: it runs its own copy with
a mark - a predefined environment variable. Availability of the variable for the process means
an execution in the child's copy. So that if the mark is not setted - the library executes
parent's operations and runs its own copy with mark, and if the mark is setted - the library
executes child's operations:
```go
func main() {
Pre()
context := new(Context)
child, _ := context.Reborn()
if child != nil {
PostParent()
} else {
defer context.Release()
PostChild()
}
}
```
![](img/idea.png)

99
vendor/github.com/sevlyar/go-daemon/command.go generated vendored Normal file
View File

@ -0,0 +1,99 @@
package daemon
import (
"os"
)
// AddCommand is wrapper on AddFlag and SetSigHandler functions.
func AddCommand(f Flag, sig os.Signal, handler SignalHandlerFunc) {
if f != nil {
AddFlag(f, sig)
}
if handler != nil {
SetSigHandler(handler, sig)
}
}
// Flag is the interface implemented by an object that has two state:
// 'set' and 'unset'.
type Flag interface {
IsSet() bool
}
// BoolFlag returns new object that implements interface Flag and
// has state 'set' when var with the given address is true.
func BoolFlag(f *bool) Flag {
return &boolFlag{f}
}
// StringFlag returns new object that implements interface Flag and
// has state 'set' when var with the given address equals given value of v.
func StringFlag(f *string, v string) Flag {
return &stringFlag{f, v}
}
type boolFlag struct {
b *bool
}
func (f *boolFlag) IsSet() bool {
if f == nil {
return false
}
return *f.b
}
type stringFlag struct {
s *string
v string
}
func (f *stringFlag) IsSet() bool {
if f == nil {
return false
}
return *f.s == f.v
}
var flags = make(map[Flag]os.Signal)
// Flags returns flags that was added by the function AddFlag.
func Flags() map[Flag]os.Signal {
return flags
}
// AddFlag adds the flag and signal to the internal map.
func AddFlag(f Flag, sig os.Signal) {
flags[f] = sig
}
// SendCommands sends active signals to the given process.
func SendCommands(p *os.Process) (err error) {
for _, sig := range signals() {
if err = p.Signal(sig); err != nil {
return
}
}
return
}
// ActiveFlags returns flags that has the state 'set'.
func ActiveFlags() (ret []Flag) {
ret = make([]Flag, 0, 1)
for f := range flags {
if f.IsSet() {
ret = append(ret, f)
}
}
return
}
func signals() (ret []os.Signal) {
ret = make([]os.Signal, 0, 1)
for f, sig := range flags {
if f.IsSet() {
ret = append(ret, sig)
}
}
return
}

88
vendor/github.com/sevlyar/go-daemon/daemon.go generated vendored Normal file
View File

@ -0,0 +1,88 @@
package daemon
import (
"errors"
"os"
"syscall"
)
var errNotSupported = errors.New("daemon: Non-POSIX OS is not supported")
// Mark of daemon process - system environment variable _GO_DAEMON=1
const (
MARK_NAME = "_GO_DAEMON"
MARK_VALUE = "1"
)
// Default file permissions for log and pid files.
const FILE_PERM = os.FileMode(0640)
// A Context describes daemon context.
type Context struct {
// If PidFileName is non-empty, parent process will try to create and lock
// pid file with given name. Child process writes process id to file.
PidFileName string
// Permissions for new pid file.
PidFilePerm os.FileMode
// If LogFileName is non-empty, parent process will create file with given name
// and will link to fd 2 (stderr) for child process.
LogFileName string
// Permissions for new log file.
LogFilePerm os.FileMode
// If WorkDir is non-empty, the child changes into the directory before
// creating the process.
WorkDir string
// If Chroot is non-empty, the child changes root directory
Chroot string
// If Env is non-nil, it gives the environment variables for the
// daemon-process in the form returned by os.Environ.
// If it is nil, the result of os.Environ will be used.
Env []string
// If Args is non-nil, it gives the command-line args for the
// daemon-process. If it is nil, the result of os.Args will be used
// (without program name).
Args []string
// Credential holds user and group identities to be assumed by a daemon-process.
Credential *syscall.Credential
// If Umask is non-zero, the daemon-process call Umask() func with given value.
Umask int
// Struct contains only serializable public fields (!!!)
abspath string
pidFile *LockFile
logFile *os.File
nullFile *os.File
rpipe, wpipe *os.File
}
// WasReborn returns true in child process (daemon) and false in parent process.
func WasReborn() bool {
return os.Getenv(MARK_NAME) == MARK_VALUE
}
// Reborn runs second copy of current process in the given context.
// function executes separate parts of code in child process and parent process
// and provides demonization of child process. It look similar as the
// fork-daemonization, but goroutine-safe.
// In success returns *os.Process in parent process and nil in child process.
// Otherwise returns error.
func (d *Context) Reborn() (child *os.Process, err error) {
return d.reborn()
}
// Search search daemons process by given in context pid file name.
// If success returns pointer on daemons os.Process structure,
// else returns error. Returns nil if filename is empty.
func (d *Context) Search() (daemon *os.Process, err error) {
return d.search()
}
// Release provides correct pid-file release in daemon.
func (d *Context) Release() (err error) {
return d.release()
}

19
vendor/github.com/sevlyar/go-daemon/daemon_stub.go generated vendored Normal file
View File

@ -0,0 +1,19 @@
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!plan9,!solaris
package daemon
import (
"os"
)
func (d *Context) reborn() (child *os.Process, err error) {
return nil, errNotSupported
}
func (d *Context) search() (daemon *os.Process, err error) {
return nil, errNotSupported
}
func (d *Context) release() (err error) {
return nil, errNotSupported
}

68
vendor/github.com/sevlyar/go-daemon/daemon_test.go generated vendored Normal file
View File

@ -0,0 +1,68 @@
package daemon
import (
"flag"
"log"
"os"
"syscall"
"time"
)
func Example() {
signal := flag.String("s", "", "send signal to daemon")
handler := func(sig os.Signal) error {
log.Println("signal:", sig)
if sig == syscall.SIGTERM {
return ErrStop
}
return nil
}
// Define command: command-line arg, system signal and handler
AddCommand(StringFlag(signal, "term"), syscall.SIGTERM, handler)
AddCommand(StringFlag(signal, "reload"), syscall.SIGHUP, handler)
flag.Parse()
// Define daemon context
dmn := &Context{
PidFileName: "/var/run/daemon.pid",
PidFilePerm: 0644,
LogFileName: "/var/log/daemon.log",
LogFilePerm: 0640,
WorkDir: "/",
Umask: 027,
}
// Send commands if needed
if len(ActiveFlags()) > 0 {
d, err := dmn.Search()
if err != nil {
log.Fatalln("Unable send signal to the daemon:", err)
}
SendCommands(d)
return
}
// Process daemon operations - send signal if present flag or daemonize
child, err := dmn.Reborn()
if err != nil {
log.Fatalln(err)
}
if child != nil {
return
}
defer dmn.Release()
// Run main operation
go func() {
for {
time.Sleep(0)
}
}()
err = ServeSignals()
if err != nil {
log.Println("Error:", err)
}
}

208
vendor/github.com/sevlyar/go-daemon/daemon_unix.go generated vendored Normal file
View File

@ -0,0 +1,208 @@
// +build darwin dragonfly freebsd linux netbsd openbsd plan9 solaris
package daemon
import (
"encoding/json"
"fmt"
"os"
"syscall"
"github.com/kardianos/osext"
)
func (d *Context) reborn() (child *os.Process, err error) {
if !WasReborn() {
child, err = d.parent()
} else {
err = d.child()
}
return
}
func (d *Context) search() (daemon *os.Process, err error) {
if len(d.PidFileName) > 0 {
var pid int
if pid, err = ReadPidFile(d.PidFileName); err != nil {
return
}
daemon, err = os.FindProcess(pid)
}
return
}
func (d *Context) parent() (child *os.Process, err error) {
if err = d.prepareEnv(); err != nil {
return
}
defer d.closeFiles()
if err = d.openFiles(); err != nil {
return
}
attr := &os.ProcAttr{
Dir: d.WorkDir,
Env: d.Env,
Files: d.files(),
Sys: &syscall.SysProcAttr{
//Chroot: d.Chroot,
Credential: d.Credential,
Setsid: true,
},
}
if child, err = os.StartProcess(d.abspath, d.Args, attr); err != nil {
if d.pidFile != nil {
d.pidFile.Remove()
}
return
}
d.rpipe.Close()
encoder := json.NewEncoder(d.wpipe)
err = encoder.Encode(d)
return
}
func (d *Context) openFiles() (err error) {
if d.PidFilePerm == 0 {
d.PidFilePerm = FILE_PERM
}
if d.LogFilePerm == 0 {
d.LogFilePerm = FILE_PERM
}
if d.nullFile, err = os.Open(os.DevNull); err != nil {
return
}
if len(d.PidFileName) > 0 {
if d.pidFile, err = OpenLockFile(d.PidFileName, d.PidFilePerm); err != nil {
return
}
if err = d.pidFile.Lock(); err != nil {
return
}
}
if len(d.LogFileName) > 0 {
if d.logFile, err = os.OpenFile(d.LogFileName,
os.O_WRONLY|os.O_CREATE|os.O_APPEND, d.LogFilePerm); err != nil {
return
}
}
d.rpipe, d.wpipe, err = os.Pipe()
return
}
func (d *Context) closeFiles() (err error) {
cl := func(file **os.File) {
if *file != nil {
(*file).Close()
*file = nil
}
}
cl(&d.rpipe)
cl(&d.wpipe)
cl(&d.logFile)
cl(&d.nullFile)
if d.pidFile != nil {
d.pidFile.Close()
d.pidFile = nil
}
return
}
func (d *Context) prepareEnv() (err error) {
if d.abspath, err = osext.Executable(); err != nil {
return
}
if len(d.Args) == 0 {
d.Args = os.Args
}
mark := fmt.Sprintf("%s=%s", MARK_NAME, MARK_VALUE)
if len(d.Env) == 0 {
d.Env = os.Environ()
}
d.Env = append(d.Env, mark)
return
}
func (d *Context) files() (f []*os.File) {
log := d.nullFile
if d.logFile != nil {
log = d.logFile
}
f = []*os.File{
d.rpipe, // (0) stdin
log, // (1) stdout
log, // (2) stderr
d.nullFile, // (3) dup on fd 0 after initialization
}
if d.pidFile != nil {
f = append(f, d.pidFile.File) // (4) pid file
}
return
}
var initialized = false
func (d *Context) child() (err error) {
if initialized {
return os.ErrInvalid
}
initialized = true
if len(d.PidFileName) > 0 {
d.pidFile = NewLockFile(os.NewFile(4, d.PidFileName))
if err = d.pidFile.WritePid(); err != nil {
return
}
}
decoder := json.NewDecoder(os.Stdin)
if err = decoder.Decode(d); err != nil {
d.pidFile.Remove()
return
}
if err = syscall.Close(0); err != nil {
d.pidFile.Remove()
return
}
if err = syscallDup(3, 0); err != nil {
d.pidFile.Remove()
return
}
if d.Umask != 0 {
syscall.Umask(int(d.Umask))
}
if len(d.Chroot) > 0 {
err = syscall.Chroot(d.Chroot)
if err != nil {
d.pidFile.Remove()
return
}
}
return
}
func (d *Context) release() (err error) {
if !initialized {
return
}
if d.pidFile != nil {
err = d.pidFile.Remove()
}
return
}

View File

@ -0,0 +1,61 @@
package main
import (
"os"
"sync"
"time"
)
type LogFile struct {
mu sync.Mutex
name string
file *os.File
}
// NewLogFile creates a new LogFile. The file is optional - it will be created if needed.
func NewLogFile(name string, file *os.File) (*LogFile, error) {
rw := &LogFile{
file: file,
name: name,
}
if file == nil {
if err := rw.Rotate(); err != nil {
return nil, err
}
}
return rw, nil
}
func (l *LogFile) Write(b []byte) (n int, err error) {
l.mu.Lock()
n, err = l.file.Write(b)
l.mu.Unlock()
return
}
// Rotate renames old log file, creates new one, switches log and closes the old file.
func (l *LogFile) Rotate() error {
// rename dest file if it already exists.
if _, err := os.Stat(l.name); err == nil {
name := l.name + "." + time.Now().Format(time.RFC3339)
if err = os.Rename(l.name, name); err != nil {
return err
}
}
// create new file.
file, err := os.Create(l.name)
if err != nil {
return err
}
// switch dest file safely.
l.mu.Lock()
file, l.file = l.file, file
l.mu.Unlock()
// close old file if open.
if file != nil {
if err := file.Close(); err != nil {
return err
}
}
return nil
}

View File

@ -0,0 +1,110 @@
package main
import (
"flag"
"github.com/sevlyar/go-daemon"
"log"
"os"
"syscall"
"time"
)
var (
signal = flag.String("s", "", `send signal to the daemon
stop shutdown`)
)
const logFileName = "log"
func main() {
flag.Parse()
daemon.AddCommand(daemon.StringFlag(signal, "stop"), syscall.SIGTERM, termHandler)
cntxt := &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
LogFileName: logFileName,
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[go-daemon sample]"},
}
if len(daemon.ActiveFlags()) > 0 {
d, err := cntxt.Search()
if err != nil {
log.Fatalln("Unable send signal to the daemon:", err)
}
daemon.SendCommands(d)
return
}
d, err := cntxt.Reborn()
if err != nil {
log.Fatalln(err)
}
if d != nil {
return
}
defer cntxt.Release()
log.Println("- - - - - - - - - - - - - - -")
log.Println("daemon started")
setupLog()
go worker()
err = daemon.ServeSignals()
if err != nil {
log.Println("Error:", err)
}
log.Println("daemon terminated")
}
func setupLog() {
lf, err := NewLogFile(logFileName, os.Stderr)
if err != nil {
log.Fatal("Unable to create log file: ", err)
}
log.SetOutput(lf)
// rotate log every 30 seconds.
rotateLogSignal := time.Tick(30 * time.Second)
go func() {
for {
<-rotateLogSignal
if err := lf.Rotate(); err != nil {
log.Fatal("Unable to rotate log: ", err)
}
}
}()
}
var (
stop = make(chan struct{})
done = make(chan struct{})
)
func worker() {
LOOP:
for {
// spam to log every one second (as payload).
log.Print("+ ", time.Now().Unix())
time.Sleep(time.Second)
select {
case <-stop:
break LOOP
default:
}
}
done <- struct{}{}
}
func termHandler(sig os.Signal) error {
log.Println("terminating...")
stop <- struct{}{}
if sig == syscall.SIGQUIT {
<-done
}
return daemon.ErrStop
}

View File

@ -0,0 +1,92 @@
package main
import (
"flag"
"github.com/sevlyar/go-daemon"
"log"
"os"
"syscall"
"time"
)
var (
signal = flag.String("s", "", `send signal to the daemon
quit graceful shutdown
stop fast shutdown
reload reloading the configuration file`)
)
func main() {
flag.Parse()
daemon.AddCommand(daemon.StringFlag(signal, "quit"), syscall.SIGQUIT, termHandler)
daemon.AddCommand(daemon.StringFlag(signal, "stop"), syscall.SIGTERM, termHandler)
daemon.AddCommand(daemon.StringFlag(signal, "reload"), syscall.SIGHUP, reloadHandler)
cntxt := &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
LogFileName: "log",
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[go-daemon sample]"},
}
if len(daemon.ActiveFlags()) > 0 {
d, err := cntxt.Search()
if err != nil {
log.Fatalln("Unable send signal to the daemon:", err)
}
daemon.SendCommands(d)
return
}
d, err := cntxt.Reborn()
if err != nil {
log.Fatalln(err)
}
if d != nil {
return
}
defer cntxt.Release()
log.Println("- - - - - - - - - - - - - - -")
log.Println("daemon started")
go worker()
err = daemon.ServeSignals()
if err != nil {
log.Println("Error:", err)
}
log.Println("daemon terminated")
}
var (
stop = make(chan struct{})
done = make(chan struct{})
)
func worker() {
for {
time.Sleep(time.Second)
if _, ok := <-stop; ok {
break
}
}
done <- struct{}{}
}
func termHandler(sig os.Signal) error {
log.Println("terminating...")
stop <- struct{}{}
if sig == syscall.SIGQUIT {
<-done
}
return daemon.ErrStop
}
func reloadHandler(sig os.Signal) error {
log.Println("configuration reloaded")
return nil
}

View File

@ -0,0 +1,48 @@
package main
import (
"fmt"
"github.com/sevlyar/go-daemon"
"html"
"log"
"net/http"
)
// To terminate the daemon use:
// kill `cat pid`
func main() {
cntxt := &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
LogFileName: "log",
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[go-daemon sample]"},
}
d, err := cntxt.Reborn()
if err != nil {
log.Fatal("Unable to run: ", err)
}
if d != nil {
return
}
defer cntxt.Release()
log.Print("- - - - - - - - - - - - - - -")
log.Print("daemon started")
serveHttp()
}
func serveHttp() {
http.HandleFunc("/", httpHandler)
http.ListenAndServe("127.0.0.1:8080", nil)
}
func httpHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("request from %s: %s %q", r.RemoteAddr, r.Method, r.URL)
fmt.Fprintf(w, "go-daemon: %q", html.EscapeString(r.URL.Path))
}

BIN
vendor/github.com/sevlyar/go-daemon/img/idea.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

124
vendor/github.com/sevlyar/go-daemon/lock_file.go generated vendored Normal file
View File

@ -0,0 +1,124 @@
package daemon
import (
"errors"
"fmt"
"os"
"syscall"
)
var (
// ErrWoldBlock indicates on locking pid-file by another process.
ErrWouldBlock = errors.New("daemon: Resource temporarily unavailable")
)
// LockFile wraps *os.File and provide functions for locking of files.
type LockFile struct {
*os.File
}
// NewLockFile returns a new LockFile with the given File.
func NewLockFile(file *os.File) *LockFile {
return &LockFile{file}
}
// CreatePidFile opens the named file, applies exclusive lock and writes
// current process id to file.
func CreatePidFile(name string, perm os.FileMode) (lock *LockFile, err error) {
if lock, err = OpenLockFile(name, perm); err != nil {
return
}
if err = lock.Lock(); err != nil {
lock.Remove()
return
}
if err = lock.WritePid(); err != nil {
lock.Remove()
}
return
}
// OpenLockFile opens the named file with flags os.O_RDWR|os.O_CREATE and specified perm.
// If successful, function returns LockFile for opened file.
func OpenLockFile(name string, perm os.FileMode) (lock *LockFile, err error) {
var file *os.File
if file, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm); err == nil {
lock = &LockFile{file}
}
return
}
// Lock apply exclusive lock on an open file. If file already locked, returns error.
func (file *LockFile) Lock() error {
return lockFile(file.Fd())
}
// Unlock remove exclusive lock on an open file.
func (file *LockFile) Unlock() error {
return unlockFile(file.Fd())
}
// ReadPidFile reads process id from file with give name and returns pid.
// If unable read from a file, returns error.
func ReadPidFile(name string) (pid int, err error) {
var file *os.File
if file, err = os.OpenFile(name, os.O_RDONLY, 0640); err != nil {
return
}
defer file.Close()
lock := &LockFile{file}
pid, err = lock.ReadPid()
return
}
// WritePid writes current process id to an open file.
func (file *LockFile) WritePid() (err error) {
if _, err = file.Seek(0, os.SEEK_SET); err != nil {
return
}
var fileLen int
if fileLen, err = fmt.Fprint(file, os.Getpid()); err != nil {
return
}
if err = file.Truncate(int64(fileLen)); err != nil {
return
}
err = file.Sync()
return
}
// ReadPid reads process id from file and returns pid.
// If unable read from a file, returns error.
func (file *LockFile) ReadPid() (pid int, err error) {
if _, err = file.Seek(0, os.SEEK_SET); err != nil {
return
}
_, err = fmt.Fscan(file, &pid)
return
}
// Remove removes lock, closes and removes an open file.
func (file *LockFile) Remove() error {
defer file.Close()
if err := file.Unlock(); err != nil {
return err
}
// TODO(yar): keep filename?
name, err := GetFdName(file.Fd())
if err != nil {
return err
}
err = syscall.Unlink(name)
return err
}
// GetFdName returns file name for given descriptor.
//
// BUG(yar): GetFdName returns an error for some *nix platforms when full name length of the file is greater than 0x1000.
func GetFdName(fd uintptr) (name string, err error) {
return getFdName(fd)
}

View File

@ -0,0 +1,38 @@
// +build darwin
package daemon
import (
"syscall"
"unsafe"
)
import "C"
// darwin's MAXPATHLEN
const maxpathlen = 1024
func lockFile(fd uintptr) error {
err := syscall.Flock(int(fd), syscall.LOCK_EX|syscall.LOCK_NB)
if err == syscall.EWOULDBLOCK {
err = ErrWouldBlock
}
return err
}
func unlockFile(fd uintptr) error {
err := syscall.Flock(int(fd), syscall.LOCK_UN)
if err == syscall.EWOULDBLOCK {
err = ErrWouldBlock
}
return err
}
func getFdName(fd uintptr) (name string, err error) {
buf := make([]C.char, maxpathlen+1)
_, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fd, syscall.F_GETPATH, uintptr(unsafe.Pointer(&buf[0])))
if errno == 0 {
return C.GoString(&buf[0]), nil
}
return "", errno
}

15
vendor/github.com/sevlyar/go-daemon/lock_file_stub.go generated vendored Normal file
View File

@ -0,0 +1,15 @@
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!plan9,!solaris
package daemon
func lockFile(fd uintptr) error {
return errNotSupported
}
func unlockFile(fd uintptr) error {
return errNotSupported
}
func getFdName(fd uintptr) (name string, err error) {
return "", errNotSupported
}

106
vendor/github.com/sevlyar/go-daemon/lock_file_test.go generated vendored Normal file
View File

@ -0,0 +1,106 @@
package daemon
import (
"fmt"
"io/ioutil"
"os"
"testing"
)
var (
filename = os.TempDir() + "/test.lock"
fileperm os.FileMode = 0644
invalidname = "/x/y/unknown"
)
func TestCreatePidFile(test *testing.T) {
if _, err := CreatePidFile(invalidname, fileperm); err == nil {
test.Fatal("CreatePidFile(): Error was not detected on invalid name")
}
lock, err := CreatePidFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
defer lock.Remove()
data, err := ioutil.ReadFile(filename)
if err != nil {
test.Fatal(err)
}
if string(data) != fmt.Sprint(os.Getpid()) {
test.Fatal("pids not equal")
}
file, err := os.OpenFile(filename, os.O_RDONLY, fileperm)
if err != nil {
test.Fatal(err)
}
if err = NewLockFile(file).WritePid(); err == nil {
test.Fatal("WritePid(): Error was not detected on invalid permissions")
}
}
func TestNewLockFile(test *testing.T) {
lock := NewLockFile(os.NewFile(1001, ""))
err := lock.Remove()
if err == nil {
test.Fatal("Remove(): Error was not detected on invalid fd")
}
err = lock.WritePid()
if err == nil {
test.Fatal("WritePid(): Error was not detected on invalid fd")
}
}
func TestGetFdName(test *testing.T) {
name, err := GetFdName(0)
if err != nil {
test.Error(err)
} else {
if name != "/dev/null" {
test.Errorf("Filename of fd 0: `%s'", name)
}
}
name, err = GetFdName(1011)
if err == nil {
test.Errorf("GetFdName(): Error was not detected on invalid fd, name: `%s'", name)
}
}
func TestReadPid(test *testing.T) {
lock, err := CreatePidFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
defer lock.Remove()
pid, err := lock.ReadPid()
if err != nil {
test.Fatal("ReadPid(): Unable read pid from file:", err)
}
if pid != os.Getpid() {
test.Fatal("Pid not equal real pid")
}
}
func TestLockFileLock(test *testing.T) {
lock1, err := OpenLockFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
if err := lock1.Lock(); err != nil {
test.Fatal(err)
}
defer lock1.Remove()
lock2, err := OpenLockFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
if err := lock2.Lock(); err != ErrWouldBlock {
test.Fatal("To lock file more than once must be unavailable.")
}
}

40
vendor/github.com/sevlyar/go-daemon/lock_file_unix.go generated vendored Normal file
View File

@ -0,0 +1,40 @@
// +build dragonfly freebsd linux netbsd openbsd plan9 solaris
package daemon
import (
"fmt"
"syscall"
)
func lockFile(fd uintptr) error {
err := syscall.Flock(int(fd), syscall.LOCK_EX|syscall.LOCK_NB)
if err == syscall.EWOULDBLOCK {
err = ErrWouldBlock
}
return err
}
func unlockFile(fd uintptr) error {
err := syscall.Flock(int(fd), syscall.LOCK_UN)
if err == syscall.EWOULDBLOCK {
err = ErrWouldBlock
}
return err
}
const pathMax = 0x1000
func getFdName(fd uintptr) (name string, err error) {
path := fmt.Sprintf("/proc/self/fd/%d", int(fd))
// We use predefined pathMax const because /proc directory contains special files
// so that unable to get correct size of pseudo-symlink through lstat.
// please see notes and example for readlink syscall:
// http://man7.org/linux/man-pages/man2/readlink.2.html#NOTES
buf := make([]byte, pathMax)
var n int
if n, err = syscall.Readlink(path, buf); err == nil {
name = string(buf[:n])
}
return
}

View File

@ -0,0 +1,88 @@
// Package daemon provides function to daemonization processes.
// And such as the handling of system signals and the pid-file creation.
package daemon
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"syscall"
)
const (
envVarName = "_GO_DAEMON"
envVarValue = "1"
)
// func Reborn daemonize process. Function Reborn calls ForkExec
// in the parent process and terminates him. In the child process,
// function sets umask, work dir and calls Setsid. Function sets
// for child process environment variable _GO_DAEMON=1 - the mark,
// might used for debug.
func Reborn(umask uint32, workDir string) (err error) {
if !WasReborn() {
// parent process - fork and exec
var path string
if path, err = filepath.Abs(os.Args[0]); err != nil {
return
}
cmd := prepareCommand(path)
if err = cmd.Start(); err != nil {
return
}
os.Exit(0)
}
// child process - daemon
syscall.Umask(int(umask))
if len(workDir) != 0 {
if err = os.Chdir(workDir); err != nil {
return
}
}
_, err = syscall.Setsid()
// Do not required redirect std
// to /dev/null, this work was
// done function ForkExec
return
}
// func WasReborn, return true if the process has environment
// variable _GO_DAEMON=1 (child process).
func WasReborn() bool {
return os.Getenv(envVarName) == envVarValue
}
func prepareCommand(path string) (cmd *exec.Cmd) {
// prepare command-line arguments
cmd = exec.Command(path, os.Args[1:]...)
// prepare environment variables
envVar := fmt.Sprintf("%s=%s", envVarName, envVarValue)
cmd.Env = append(os.Environ(), envVar)
return
}
// func RedirectStream redirects file s to file target.
func RedirectStream(s, target *os.File) (err error) {
stdoutFd := int(s.Fd())
if err = syscall.Close(stdoutFd); err != nil {
return
}
err = syscall.Dup2(int(target.Fd()), stdoutFd)
return
}

View File

@ -0,0 +1,72 @@
package daemon_test
import (
"fmt"
"github.com/sevlyar/go-daemon/oldapi"
"log"
"os"
"syscall"
)
func ExampleReborn() {
err := daemon.Reborn(027, "/")
if err != nil {
log.Println("Error:", err)
os.Exit(1)
}
daemon.ServeSignals()
}
func ExampleRedirectStream() {
file, err := os.OpenFile("/tmp/daemon-log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
os.Exit(1)
}
if err = daemon.RedirectStream(os.Stdout, file); err != nil {
os.Exit(2)
}
if err = daemon.RedirectStream(os.Stderr, file); err != nil {
os.Exit(2)
}
file.Close()
fmt.Println("some message")
log.Println("some message")
}
func ExampleServeSignals() {
TermHandler := func(sig os.Signal) error {
log.Println("SIGTERM:", sig)
return daemon.ErrStop
}
HupHandler := func(sig os.Signal) error {
log.Println("SIGHUP:", sig)
return nil
}
daemon.SetHandler(TermHandler, syscall.SIGTERM, syscall.SIGKILL)
daemon.SetHandler(HupHandler, syscall.SIGHUP)
err := daemon.ServeSignals()
if err != nil {
log.Println("Error:", err)
}
}
func ExampleLockPidFile() {
pidf, err := daemon.LockPidFile("name.pid", 0600)
if err != nil {
if err == daemon.ErrWouldBlock {
log.Println("daemon already exists")
} else {
log.Println("pid file creation error:", err)
}
return
}
defer pidf.Unlock()
daemon.ServeSignals()
}

View File

@ -0,0 +1,67 @@
package daemon
import (
"fmt"
"os"
"syscall"
)
// PidFile contains information of pid-file.
type PidFile struct {
file *os.File
path string
}
// ErrWoldBlock indicates on locking pid-file by another process.
var ErrWouldBlock = syscall.EWOULDBLOCK
// func LockPidFile trys create and lock pid-file.
func LockPidFile(path string, perm os.FileMode) (pidf *PidFile, err error) {
var fileLen int
var file *os.File
file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, perm)
if err != nil {
return
}
if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
if err == syscall.EWOULDBLOCK {
// allready locked by other process instance
file.Close()
return
}
goto SKIP
}
if fileLen, err = fmt.Fprint(file, os.Getpid()); err != nil {
goto SKIP
}
if err = file.Truncate(int64(fileLen)); err != nil {
goto SKIP
}
SKIP:
if err != nil {
syscall.Unlink(path)
file.Close()
} else {
pidf = &PidFile{file, path}
}
return
}
// func Unlock unlocks and removes pid-file.
func (pidf *PidFile) Unlock() (err error) {
err = syscall.Unlink(pidf.path)
err2 := pidf.file.Close()
// return one of two errors
if err == nil {
err = err2
}
return
}

View File

@ -0,0 +1,3 @@
[
"/var/log/syslog"
]

View File

@ -0,0 +1,198 @@
package main
import (
"encoding/json"
"flag"
daemon "github.com/sevlyar/go-daemon/oldapi"
"log"
"os"
"syscall"
"time"
)
const (
pidFileName = "dmn.pid"
logFileName = "dmn.log"
fileMask = 0600
)
const (
ret_OK = iota
ret_ALREADYRUN
ret_PIDFERROR
ret_REBORNERROR
ret_CONFERROR
)
var (
status = flag.Bool("status", false,
`Check status of the daemon. The program immediately exits after these
checks with either a return code of 0 (Daemon Stopped) or return code
not equal to 0 (Daemon Running)`)
silent = flag.Bool("silent", false, "Don't write in stdout")
test = flag.Bool("t", false,
`Run syntax tests for configuration files only. The program
immediately exits after these syntax parsing tests with either
a return code of 0 (Syntax OK) or return code not equal to 0
(Syntax Error)`)
configFileName = flag.String("f", "dmn.conf",
`Specifies the name of the configuration file. The default is dmn.conf.
Daemon refuses to start if there is no configuration file.`)
)
var confProv = make(chan Config, 8)
func main() {
flag.Parse()
setupLogging()
conf, err := loadConfig(*configFileName)
if err != nil {
log.Println("Config error:", err)
os.Exit(ret_CONFERROR)
}
if *test {
os.Exit(ret_OK)
}
pidf := lockPidFile()
err = daemon.Reborn(027, "./")
if err != nil {
log.Println("Reborn error:", err)
os.Exit(ret_REBORNERROR)
}
confProv <- conf
go watchdog(confProv)
serveSignals()
pidf.Unlock()
}
func setupLogging() {
if daemon.WasReborn() {
file, _ := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, fileMask)
daemon.RedirectStream(os.Stdout, file)
daemon.RedirectStream(os.Stderr, file)
file.Close()
log.Println("--- log ---")
} else {
log.SetFlags(0)
if *silent {
file, _ := os.OpenFile(os.DevNull, os.O_WRONLY, fileMask)
daemon.RedirectStream(os.Stdout, file)
daemon.RedirectStream(os.Stderr, file)
file.Close()
}
}
}
type Config []string
func loadConfig(path string) (config Config, err error) {
var file *os.File
file, err = os.OpenFile(path, os.O_RDONLY, 0700)
if err != nil {
return
}
defer file.Close()
config = make([]string, 0)
err = json.NewDecoder(file).Decode(&config)
if err != nil {
return
}
for _, path = range config {
if _, err = os.Stat(path); os.IsNotExist(err) {
return
}
}
return
}
func lockPidFile() *daemon.PidFile {
pidf, err := daemon.LockPidFile(pidFileName, fileMask)
if err != nil {
if err == daemon.ErrWouldBlock {
log.Println("daemon copy is already running")
os.Exit(ret_ALREADYRUN)
} else {
log.Println("pid file creation error:", err)
os.Exit(ret_PIDFERROR)
}
}
if !daemon.WasReborn() {
pidf.Unlock()
}
if *status {
os.Exit(ret_OK)
}
return pidf
}
func watchdog(confProv <-chan Config) {
states := make(map[string]time.Time)
conf := <-confProv
for {
select {
case conf = <-confProv:
default:
}
for _, path := range conf {
fi, err := os.Stat(path)
if err != nil {
log.Println(err)
continue
}
cur := fi.ModTime()
if pre, exists := states[path]; exists {
if pre != cur {
log.Printf("file %s modified at %s", path, cur)
}
}
states[path] = cur
}
time.Sleep(time.Second)
}
}
func serveSignals() {
daemon.SetHandler(termHandler, syscall.SIGTERM, syscall.SIGKILL)
daemon.SetHandler(hupHandler, syscall.SIGHUP)
err := daemon.ServeSignals()
if err != nil {
log.Println("Error:", err)
}
log.Println("--- end ---")
}
func termHandler(sig os.Signal) error {
log.Println("SIGTERM:", sig)
return daemon.ErrStop
}
func hupHandler(sig os.Signal) error {
log.Println("SIGHUP:", sig)
conf, err := loadConfig(*configFileName)
if err != nil {
log.Println("Config error:", err)
} else {
confProv <- conf
}
return nil
}

63
vendor/github.com/sevlyar/go-daemon/oldapi/sample/dmn.sh generated vendored Executable file
View File

@ -0,0 +1,63 @@
#!/bin/bash
WORK_DIR=../../../bin
PID_FILE=dmn.pid
LOG_FILE=dmn.log
DMN="./sample"
DMN_STATUS="$DMN --status --silent"
cd $WORK_DIR
#export _GO_DAEMON=1
PID=
getpid() {
if $DMN_STATUS; then
echo "daemon is not running"
exit
else
PID=`cat $PID_FILE`
fi
}
case "$1" in
start)
if $DMN; then
echo "starting daemon: OK"
else
echo "daemon return error code: $?"
fi
;;
stop)
getpid
kill -TERM $PID
echo "stopping daemon: OK"
;;
status)
getpid
echo "daemon pid: $PID"
;;
reload)
getpid
kill -HUP $PID
echo "reloading daemon config: OK"
;;
clean)
if $DMN_STATUS; then
echo "" > $LOG_FILE
echo "log cleaned"
else
echo "unable clean"
fi
;;
log)
cat $LOG_FILE
;;
*)
echo "Usage: dmn.sh {start|stop|status|reload|clean|log}"
esac

59
vendor/github.com/sevlyar/go-daemon/oldapi/signals.go generated vendored Normal file
View File

@ -0,0 +1,59 @@
package daemon
import (
"errors"
"os"
"os/signal"
"syscall"
)
// ErrStop should be returned signal handler function
// for termination of handling signals.
var ErrStop = errors.New("stop serve signals")
// SignalHandlerFunc is the interface for signal handler functions.
type SignalHandlerFunc func(sig os.Signal) (err error)
// func SetHandler sets handler for the given signals.
// SIGTERM has the default handler, he returns ErrStop.
func SetHandler(handler SignalHandlerFunc, signals ...os.Signal) {
for _, sig := range signals {
handlers[sig] = handler
}
}
// func ServeSignals calls handlers for system signals.
func ServeSignals() (err error) {
signals := make([]os.Signal, 0, len(handlers))
for sig, _ := range handlers {
signals = append(signals, sig)
}
ch := make(chan os.Signal, 8)
signal.Notify(ch, signals...)
for sig := range ch {
err = handlers[sig](sig)
if err != nil {
break
}
}
signal.Stop(ch)
if err == ErrStop {
err = nil
}
return
}
var handlers = make(map[os.Signal]SignalHandlerFunc)
func init() {
handlers[syscall.SIGTERM] = sigtermDefaultHandler
}
func sigtermDefaultHandler(sig os.Signal) error {
return ErrStop
}

59
vendor/github.com/sevlyar/go-daemon/signal.go generated vendored Normal file
View File

@ -0,0 +1,59 @@
package daemon
import (
"errors"
"os"
"os/signal"
"syscall"
)
// ErrStop should be returned signal handler function
// for termination of handling signals.
var ErrStop = errors.New("stop serve signals")
// SignalHandlerFunc is the interface for signal handler functions.
type SignalHandlerFunc func(sig os.Signal) (err error)
// func SetSigHandler sets handler for the given signals.
// SIGTERM has the default handler, he returns ErrStop.
func SetSigHandler(handler SignalHandlerFunc, signals ...os.Signal) {
for _, sig := range signals {
handlers[sig] = handler
}
}
// func ServeSignals calls handlers for system signals.
func ServeSignals() (err error) {
signals := make([]os.Signal, 0, len(handlers))
for sig, _ := range handlers {
signals = append(signals, sig)
}
ch := make(chan os.Signal, 8)
signal.Notify(ch, signals...)
for sig := range ch {
err = handlers[sig](sig)
if err != nil {
break
}
}
signal.Stop(ch)
if err == ErrStop {
err = nil
}
return
}
var handlers = make(map[os.Signal]SignalHandlerFunc)
func init() {
handlers[syscall.SIGTERM] = sigtermDefaultHandler
}
func sigtermDefaultHandler(sig os.Signal) error {
return ErrStop
}

12
vendor/github.com/sevlyar/go-daemon/syscall_dup.go generated vendored Normal file
View File

@ -0,0 +1,12 @@
// +build !linux !arm64
// +build !windows
package daemon
import (
"syscall"
)
func syscallDup(oldfd int, newfd int) (err error) {
return syscall.Dup2(oldfd, newfd)
}

View File

@ -0,0 +1,11 @@
// +build linux,arm64
package daemon
import "syscall"
func syscallDup(oldfd int, newfd int) (err error) {
// linux_arm64 platform doesn't have syscall.Dup2
// so use the nearly identical syscall.Dup3 instead.
return syscall.Dup3(oldfd, newfd, 0)
}