├── vendor ├── github.com │ ├── rs │ │ └── zerolog │ │ │ ├── CNAME │ │ │ ├── go.mod │ │ │ ├── _config.yml │ │ │ ├── pretty.png │ │ │ ├── .travis.yml │ │ │ ├── internal │ │ │ ├── cbor │ │ │ │ ├── base.go │ │ │ │ ├── string.go │ │ │ │ ├── time.go │ │ │ │ ├── cbor.go │ │ │ │ └── README.md │ │ │ └── json │ │ │ │ ├── base.go │ │ │ │ ├── bytes.go │ │ │ │ ├── time.go │ │ │ │ └── string.go │ │ │ ├── .gitignore │ │ │ ├── encoder_json.go │ │ │ ├── encoder_cbor.go │ │ │ ├── LICENSE │ │ │ ├── ctx.go │ │ │ ├── syslog.go │ │ │ ├── hook.go │ │ │ ├── globals.go │ │ │ ├── encoder.go │ │ │ ├── writer.go │ │ │ ├── sampler.go │ │ │ └── console.go │ ├── prometheus │ │ ├── procfs │ │ │ ├── .gitignore │ │ │ ├── MAINTAINERS.md │ │ │ ├── .travis.yml │ │ │ ├── NOTICE │ │ │ ├── README.md │ │ │ ├── CONTRIBUTING.md │ │ │ ├── internal │ │ │ │ └── util │ │ │ │ │ └── parse.go │ │ │ ├── doc.go │ │ │ ├── proc_io.go │ │ │ ├── nfs │ │ │ │ ├── parse_nfs.go │ │ │ │ └── parse_nfsd.go │ │ │ ├── proc_ns.go │ │ │ ├── fs.go │ │ │ ├── Makefile │ │ │ └── buddyinfo.go │ │ ├── client_golang │ │ │ ├── prometheus │ │ │ │ ├── .gitignore │ │ │ │ ├── README.md │ │ │ │ ├── fnv.go │ │ │ │ ├── collector.go │ │ │ │ └── expvar_collector.go │ │ │ ├── AUTHORS.md │ │ │ └── NOTICE │ │ ├── client_model │ │ │ └── NOTICE │ │ └── common │ │ │ ├── NOTICE │ │ │ ├── model │ │ │ ├── model.go │ │ │ ├── fnv.go │ │ │ ├── fingerprinting.go │ │ │ ├── silence.go │ │ │ ├── metric.go │ │ │ └── alert.go │ │ │ ├── expfmt │ │ │ ├── fuzz.go │ │ │ ├── expfmt.go │ │ │ └── encode.go │ │ │ └── internal │ │ │ └── bitbucket.org │ │ │ └── ww │ │ │ └── goautoneg │ │ │ └── README.txt │ ├── matttproud │ │ └── golang_protobuf_extensions │ │ │ ├── pbutil │ │ │ ├── .gitignore │ │ │ ├── Makefile │ │ │ ├── doc.go │ │ │ ├── encode.go │ │ │ └── decode.go │ │ │ └── NOTICE │ ├── natefinch │ │ └── lumberjack │ │ │ ├── .travis.yml │ │ │ ├── chown.go │ │ │ ├── .gitignore │ │ │ ├── chown_linux.go │ │ │ └── LICENSE │ ├── golang │ │ └── protobuf │ │ │ ├── AUTHORS │ │ │ ├── CONTRIBUTORS │ │ │ └── LICENSE │ ├── pkg │ │ └── errors │ │ │ ├── .travis.yml │ │ │ ├── .gitignore │ │ │ ├── appveyor.yml │ │ │ ├── LICENSE │ │ │ └── README.md │ └── beorn7 │ │ └── perks │ │ └── LICENSE ├── golang.org │ └── x │ │ └── sys │ │ ├── AUTHORS │ │ ├── CONTRIBUTORS │ │ ├── windows │ │ ├── mksyscall.go │ │ ├── aliases.go │ │ ├── asm_windows_386.s │ │ ├── asm_windows_amd64.s │ │ ├── race0.go │ │ ├── types_windows_386.go │ │ ├── types_windows_amd64.go │ │ ├── str.go │ │ ├── env_windows.go │ │ ├── race.go │ │ ├── memory_windows.go │ │ ├── eventlog.go │ │ ├── exec_windows.go │ │ └── syscall.go │ │ ├── PATENTS │ │ └── LICENSE └── modules.txt ├── .vscode └── settings.json ├── .golangci.yml ├── .gitignore ├── testcmd ├── log.go ├── memory.go ├── cpu.go ├── user.go ├── diskio.go ├── netio.go └── main.go ├── appveyor.yml ├── HEADER ├── win32 ├── lsa_test.go ├── utils_test.go ├── resources_test.go ├── registry_test.go ├── string_utils_test.go ├── sid_test.go ├── logger.go ├── userenv_win32.go ├── ip_helper_test.go ├── resources.go ├── lsa.go ├── tokens_test.go ├── registry.go ├── string_utils.go ├── process_test.go ├── resources_win32.go └── base_types_win32.go ├── go.mod ├── examples ├── damon-test-locally.ps1 └── damon-job.nomad ├── version └── version.go ├── SECURITY.md ├── metrics └── metrics_test.go ├── log ├── log.go └── log_test.go ├── make.ps1 ├── go.sum └── main.go /vendor/github.com/rs/zerolog/CNAME: -------------------------------------------------------------------------------- 1 | zerolog.io -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/.gitignore: -------------------------------------------------------------------------------- 1 | /fixtures/ 2 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/rs/zerolog 2 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/_config.yml: -------------------------------------------------------------------------------- 1 | remote_theme: rs/gh-readme 2 | -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/.gitignore: -------------------------------------------------------------------------------- 1 | cover.dat 2 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/MAINTAINERS.md: -------------------------------------------------------------------------------- 1 | * Tobias Schmidt 2 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/.gitignore: -------------------------------------------------------------------------------- 1 | command-line-arguments.test 2 | -------------------------------------------------------------------------------- /vendor/github.com/natefinch/lumberjack/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.8 5 | - 1.7 6 | - 1.6 -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2012 Matt T. Proud (matt.proud@gmail.com) 2 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/pretty.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apis/damon/master/vendor/github.com/rs/zerolog/pretty.png -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "go.lintTool": "golangci-lint", 3 | "go.lintFlags": [ 4 | "--config=${workspaceRoot}\\.golangci.yml" 5 | ] 6 | } -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | 3 | cover: 4 | go test -cover -v -coverprofile=cover.dat ./... 5 | go tool cover -func cover.dat 6 | 7 | .PHONY: cover 8 | -------------------------------------------------------------------------------- /vendor/github.com/natefinch/lumberjack/chown.go: -------------------------------------------------------------------------------- 1 | // +build !linux 2 | 3 | package lumberjack 4 | 5 | import ( 6 | "os" 7 | ) 8 | 9 | func chown(_ string, _ os.FileInfo) error { 10 | return nil 11 | } 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/AUTHORS: -------------------------------------------------------------------------------- 1 | # This source code refers to The Go Authors for copyright purposes. 2 | # The master list of authors is in the main Go distribution, 3 | # visible at http://tip.golang.org/AUTHORS. 4 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This source code was written by the Go contributors. 2 | # The master list of contributors is in the main Go distribution, 3 | # visible at http://tip.golang.org/CONTRIBUTORS. 4 | -------------------------------------------------------------------------------- /vendor/github.com/golang/protobuf/AUTHORS: -------------------------------------------------------------------------------- 1 | # This source code refers to The Go Authors for copyright purposes. 2 | # The master list of authors is in the main Go distribution, 3 | # visible at http://tip.golang.org/AUTHORS. 4 | -------------------------------------------------------------------------------- /vendor/github.com/golang/protobuf/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This source code was written by the Go contributors. 2 | # The master list of contributors is in the main Go distribution, 3 | # visible at http://tip.golang.org/CONTRIBUTORS. 4 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/README.md: -------------------------------------------------------------------------------- 1 | See [![go-doc](https://godoc.org/github.com/prometheus/client_golang/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/prometheus). 2 | -------------------------------------------------------------------------------- /vendor/github.com/pkg/errors/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go_import_path: github.com/pkg/errors 3 | go: 4 | - 1.4.3 5 | - 1.5.4 6 | - 1.6.2 7 | - 1.7.1 8 | - tip 9 | 10 | script: 11 | - go test -v ./... 12 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_model/NOTICE: -------------------------------------------------------------------------------- 1 | Data model artifacts for Prometheus. 2 | Copyright 2012-2015 The Prometheus Authors 3 | 4 | This product includes software developed at 5 | SoundCloud Ltd. (http://soundcloud.com/). 6 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/NOTICE: -------------------------------------------------------------------------------- 1 | Common libraries shared by Prometheus Go components. 2 | Copyright 2015 The Prometheus Authors 3 | 4 | This product includes software developed at 5 | SoundCloud Ltd. (http://soundcloud.com/). 6 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: go 4 | 5 | go: 6 | - 1.9.x 7 | - 1.10.x 8 | 9 | go_import_path: github.com/prometheus/procfs 10 | 11 | script: 12 | - make style check_license vet test staticcheck 13 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | run: 3 | issues-exit-code: 1 4 | skip-files: 5 | - '.*_win32.go$' # Windows API has a lot of C-isms 6 | skip-dirs: 7 | - 'testcmd' 8 | 9 | output: 10 | format: tab 11 | print-issued-lines: true 12 | print-linter-name: true 13 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/NOTICE: -------------------------------------------------------------------------------- 1 | procfs provides functions to retrieve system, kernel and process 2 | metrics from the pseudo-filesystem proc. 3 | 4 | Copyright 2014-2015 The Prometheus Authors 5 | 6 | This product includes software developed at 7 | SoundCloud Ltd. (http://soundcloud.com/). 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Don't check in any log files 15 | *.log 16 | -------------------------------------------------------------------------------- /testcmd/log.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "io" 8 | "log" 9 | ) 10 | 11 | func LogErrorf(err error, format string, v ...interface{}) { 12 | if err != nil { 13 | if err == io.EOF { 14 | return 15 | } 16 | log.Println("ERROR", fmt.Sprintf(format, v...), err) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - "1.7" 4 | - "1.8" 5 | - "1.9" 6 | - "1.10" 7 | - "master" 8 | matrix: 9 | allow_failures: 10 | - go: "master" 11 | script: 12 | - go test -v -race -cpu=1,2,4 -bench . -benchmem ./... 13 | - go test -v -tags binary_log -race -cpu=1,2,4 -bench . -benchmem ./... 14 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/cbor/base.go: -------------------------------------------------------------------------------- 1 | package cbor 2 | 3 | type Encoder struct{} 4 | 5 | // AppendKey adds a key (string) to the binary encoded log message 6 | func (e Encoder) AppendKey(dst []byte, key string) []byte { 7 | if len(dst) < 1 { 8 | dst = e.AppendBeginMarker(dst) 9 | } 10 | return e.AppendString(dst, key) 11 | } -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/json/base.go: -------------------------------------------------------------------------------- 1 | package json 2 | 3 | type Encoder struct{} 4 | 5 | // AppendKey appends a new key to the output JSON. 6 | func (e Encoder) AppendKey(dst []byte, key string) []byte { 7 | if len(dst) > 1 && dst[len(dst)-1] != '{' { 8 | dst = append(dst, ',') 9 | } 10 | dst = e.AppendString(dst, key) 11 | return append(dst, ':') 12 | } -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/mksyscall.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package windows 6 | 7 | //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go 8 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/aliases.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | // +build go1.9 7 | 8 | package windows 9 | 10 | import "syscall" 11 | 12 | type Errno = syscall.Errno 13 | type SysProcAttr = syscall.SysProcAttr 14 | -------------------------------------------------------------------------------- /vendor/github.com/natefinch/lumberjack/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | -------------------------------------------------------------------------------- /vendor/github.com/pkg/errors/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/asm_windows_386.s: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // 6 | // System calls for 386, Windows are implemented in runtime/syscall_windows.goc 7 | // 8 | 9 | TEXT ·getprocaddress(SB), 7, $0-16 10 | JMP syscall·getprocaddress(SB) 11 | 12 | TEXT ·loadlibrary(SB), 7, $0-12 13 | JMP syscall·loadlibrary(SB) 14 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/asm_windows_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // 6 | // System calls for amd64, Windows are implemented in runtime/syscall_windows.goc 7 | // 8 | 9 | TEXT ·getprocaddress(SB), 7, $0-32 10 | JMP syscall·getprocaddress(SB) 11 | 12 | TEXT ·loadlibrary(SB), 7, $0-24 13 | JMP syscall·loadlibrary(SB) 14 | -------------------------------------------------------------------------------- /testcmd/memory.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package main 4 | 5 | import ( 6 | "math/rand" 7 | "time" 8 | ) 9 | 10 | func eatMemory(exitCh <-chan struct{}, doneCh chan struct{}) { 11 | defer close(doneCh) 12 | memory := make([]byte, 0) 13 | for { 14 | select { 15 | case <-exitCh: 16 | return 17 | case <-time.After(100 * time.Millisecond): 18 | block := make([]byte, 512*1024) // 512k 19 | rand.Read(block) 20 | memory = append(memory, block...) 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /vendor/github.com/natefinch/lumberjack/chown_linux.go: -------------------------------------------------------------------------------- 1 | package lumberjack 2 | 3 | import ( 4 | "os" 5 | "syscall" 6 | ) 7 | 8 | // os_Chown is a var so we can mock it out during tests. 9 | var os_Chown = os.Chown 10 | 11 | func chown(name string, info os.FileInfo) error { 12 | f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, info.Mode()) 13 | if err != nil { 14 | return err 15 | } 16 | f.Close() 17 | stat := info.Sys().(*syscall.Stat_t) 18 | return os_Chown(name, int(stat.Uid), int(stat.Gid)) 19 | } 20 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | --- 2 | version: "build-{branch}-{build}" 3 | clone_folder: c:\gopath\src\github.com\jet\damon 4 | environment: 5 | GOPATH: c:\gopath 6 | GOBIN: c:\gopath\bin 7 | image: Visual Studio 2017 8 | install: 9 | - cmd: set PATH=%GOBIN%;c:\go\bin;%PATH% 10 | - cmd: echo %Path% 11 | - cmd: go version 12 | - cmd: go env 13 | test_script: 14 | - cmd: powershell.exe -ExecutionPolicy Bypass .\make.ps1 -Lint 15 | - cmd: powershell.exe -ExecutionPolicy Bypass .\make.ps1 -Test 16 | build_script: 17 | - cmd: powershell.exe -ExecutionPolicy Bypass .\make.ps1 -Build 18 | deploy: off -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/race0.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows,!race 6 | 7 | package windows 8 | 9 | import ( 10 | "unsafe" 11 | ) 12 | 13 | const raceenabled = false 14 | 15 | func raceAcquire(addr unsafe.Pointer) { 16 | } 17 | 18 | func raceReleaseMerge(addr unsafe.Pointer) { 19 | } 20 | 21 | func raceReadRange(addr unsafe.Pointer, len int) { 22 | } 23 | 24 | func raceWriteRange(addr unsafe.Pointer, len int) { 25 | } 26 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/types_windows_386.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package windows 6 | 7 | type WSAData struct { 8 | Version uint16 9 | HighVersion uint16 10 | Description [WSADESCRIPTION_LEN + 1]byte 11 | SystemStatus [WSASYS_STATUS_LEN + 1]byte 12 | MaxSockets uint16 13 | MaxUdpDg uint16 14 | VendorInfo *byte 15 | } 16 | 17 | type Servent struct { 18 | Name *byte 19 | Aliases **byte 20 | Port uint16 21 | Proto *byte 22 | } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/types_windows_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package windows 6 | 7 | type WSAData struct { 8 | Version uint16 9 | HighVersion uint16 10 | MaxSockets uint16 11 | MaxUdpDg uint16 12 | VendorInfo *byte 13 | Description [WSADESCRIPTION_LEN + 1]byte 14 | SystemStatus [WSASYS_STATUS_LEN + 1]byte 15 | } 16 | 17 | type Servent struct { 18 | Name *byte 19 | Aliases **byte 20 | Proto *byte 21 | Port uint16 22 | } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/str.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package windows 8 | 9 | func itoa(val int) string { // do it here rather than with fmt to avoid dependency 10 | if val < 0 { 11 | return "-" + itoa(-val) 12 | } 13 | var buf [32]byte // big enough for int64 14 | i := len(buf) - 1 15 | for val >= 10 { 16 | buf[i] = byte(val%10 + '0') 17 | i-- 18 | val /= 10 19 | } 20 | buf[i] = byte(val + '0') 21 | return string(buf[i:]) 22 | } 23 | -------------------------------------------------------------------------------- /HEADER: -------------------------------------------------------------------------------- 1 | SPDX-License-Identifier: Apache-2.0 2 | 3 | Copyright (c) 2018-present, Jet.com, Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http:www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License." 16 | -------------------------------------------------------------------------------- /testcmd/cpu.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "os" 8 | "runtime" 9 | "time" 10 | ) 11 | 12 | func eatCPU(exitCh <-chan struct{}, doneCh chan struct{}) { 13 | defer close(doneCh) 14 | for cpu := 0; cpu < runtime.NumCPU(); cpu++ { 15 | go func(cpu int) { 16 | t0 := time.Now() 17 | for { 18 | select { 19 | case <-exitCh: 20 | return 21 | default: 22 | // hot loop 23 | t1 := time.Now() 24 | if t1.Sub(t0) > (1 * time.Second) { 25 | // tick every second 26 | fmt.Fprintf(os.Stderr, ".") 27 | t0 = t1 28 | } 29 | } 30 | } 31 | }(cpu) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/AUTHORS.md: -------------------------------------------------------------------------------- 1 | The Prometheus project was started by Matt T. Proud (emeritus) and 2 | Julius Volz in 2012. 3 | 4 | Maintainers of this repository: 5 | 6 | * Björn Rabenstein 7 | 8 | The following individuals have contributed code to this repository 9 | (listed in alphabetical order): 10 | 11 | * Bernerd Schaefer 12 | * Björn Rabenstein 13 | * Daniel Bornkessel 14 | * Jeff Younker 15 | * Julius Volz 16 | * Matt T. Proud 17 | * Tobias Schmidt 18 | 19 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/encoder_json.go: -------------------------------------------------------------------------------- 1 | // +build !binary_log 2 | 3 | package zerolog 4 | 5 | // encoder_json.go file contains bindings to generate 6 | // JSON encoded byte stream. 7 | 8 | import ( 9 | "github.com/rs/zerolog/internal/json" 10 | ) 11 | 12 | var ( 13 | _ encoder = (*json.Encoder)(nil) 14 | 15 | enc = json.Encoder{} 16 | ) 17 | 18 | func appendJSON(dst []byte, j []byte) []byte { 19 | return append(dst, j...) 20 | } 21 | 22 | func decodeIfBinaryToString(in []byte) string { 23 | return string(in) 24 | } 25 | 26 | func decodeObjectToStr(in []byte) string { 27 | return string(in) 28 | } 29 | 30 | func decodeIfBinaryToBytes(in []byte) []byte { 31 | return in 32 | } 33 | -------------------------------------------------------------------------------- /win32/lsa_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "syscall" 7 | "testing" 8 | "unsafe" 9 | ) 10 | 11 | func TestLSA(t *testing.T) { 12 | login := SetupUserLogin(t) 13 | pol, err := lsaOpenPolicy("", _POLICY_ALL_ACCESS) 14 | if err != nil { 15 | t.Fatal("lsaOpenPolicy", err) 16 | } 17 | defer lsaClose(*pol) 18 | s, err := LookupAccountSID("", login.Username) 19 | if err != nil { 20 | t.Fatal("LookupAccountSID", err) 21 | } 22 | sid := (*syscall.SID)(unsafe.Pointer(s)) 23 | rights, err := lsaEnumerateAccountRights(*pol, sid) 24 | if err != nil { 25 | t.Fatal("lsaEnumerateAccountRights", err) 26 | } 27 | for _, r := range rights { 28 | t.Logf(r) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /testcmd/user.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package main 4 | 5 | import ( 6 | "github.com/jet/damon/win32" 7 | ) 8 | 9 | func addTestUserRights(user string, rights []string) error { 10 | sid, err := win32.LookupAccountSID("", user) 11 | if err != nil { 12 | return err 13 | } 14 | privs, err := win32.EnumerateAccountRights(sid) 15 | if err != nil { 16 | return err 17 | } 18 | privMap := make(map[string]bool) 19 | for _, p := range privs { 20 | privMap[p] = true 21 | } 22 | var addPrivs []string 23 | for _, r := range rights { 24 | if _, ok := privMap[r]; !ok { 25 | addPrivs = append(addPrivs, r) 26 | privMap[r] = true 27 | } 28 | } 29 | return win32.AddAccountRights(sid, addPrivs) 30 | } 31 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/env_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Windows environment variables. 6 | 7 | package windows 8 | 9 | import "syscall" 10 | 11 | func Getenv(key string) (value string, found bool) { 12 | return syscall.Getenv(key) 13 | } 14 | 15 | func Setenv(key, value string) error { 16 | return syscall.Setenv(key, value) 17 | } 18 | 19 | func Clearenv() { 20 | syscall.Clearenv() 21 | } 22 | 23 | func Environ() []string { 24 | return syscall.Environ() 25 | } 26 | 27 | func Unsetenv(key string) error { 28 | return syscall.Unsetenv(key) 29 | } 30 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/README.md: -------------------------------------------------------------------------------- 1 | # procfs 2 | 3 | This procfs package provides functions to retrieve system, kernel and process 4 | metrics from the pseudo-filesystem proc. 5 | 6 | *WARNING*: This package is a work in progress. Its API may still break in 7 | backwards-incompatible ways without warnings. Use it at your own risk. 8 | 9 | [![GoDoc](https://godoc.org/github.com/prometheus/procfs?status.png)](https://godoc.org/github.com/prometheus/procfs) 10 | [![Build Status](https://travis-ci.org/prometheus/procfs.svg?branch=master)](https://travis-ci.org/prometheus/procfs) 11 | [![Go Report Card](https://goreportcard.com/badge/github.com/prometheus/procfs)](https://goreportcard.com/report/github.com/prometheus/procfs) 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/race.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows,race 6 | 7 | package windows 8 | 9 | import ( 10 | "runtime" 11 | "unsafe" 12 | ) 13 | 14 | const raceenabled = true 15 | 16 | func raceAcquire(addr unsafe.Pointer) { 17 | runtime.RaceAcquire(addr) 18 | } 19 | 20 | func raceReleaseMerge(addr unsafe.Pointer) { 21 | runtime.RaceReleaseMerge(addr) 22 | } 23 | 24 | func raceReadRange(addr unsafe.Pointer, len int) { 25 | runtime.RaceReadRange(addr, len) 26 | } 27 | 28 | func raceWriteRange(addr unsafe.Pointer, len int) { 29 | runtime.RaceWriteRange(addr, len) 30 | } 31 | -------------------------------------------------------------------------------- /win32/utils_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "os" 7 | "path/filepath" 8 | "testing" 9 | ) 10 | 11 | func SetupTestExe(t *testing.T) string { 12 | if exe := os.Getenv("TEST_EXE_PATH"); exe != "" { 13 | stat, err := os.Stat(exe) 14 | if err != nil { 15 | t.Skipf("unable to stat test.exe: %v", err) 16 | } 17 | if stat.IsDir() { 18 | t.Skipf("test.exe is a directory") 19 | } 20 | abs, err := filepath.Abs(exe) 21 | if err != nil { 22 | t.Skipf("unable to get absolute path of test.exe: %v", err) 23 | } 24 | return abs 25 | } 26 | t.Skip("TEST_EXE_PATH not set") 27 | return "" 28 | } 29 | 30 | func LogTestError(t *testing.T, err error) { 31 | if err != nil { 32 | t.Error(err) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/fnv.go: -------------------------------------------------------------------------------- 1 | package prometheus 2 | 3 | // Inline and byte-free variant of hash/fnv's fnv64a. 4 | 5 | const ( 6 | offset64 = 14695981039346656037 7 | prime64 = 1099511628211 8 | ) 9 | 10 | // hashNew initializies a new fnv64a hash value. 11 | func hashNew() uint64 { 12 | return offset64 13 | } 14 | 15 | // hashAdd adds a string to a fnv64a hash value, returning the updated hash. 16 | func hashAdd(h uint64, s string) uint64 { 17 | for i := 0; i < len(s); i++ { 18 | h ^= uint64(s[i]) 19 | h *= prime64 20 | } 21 | return h 22 | } 23 | 24 | // hashAddByte adds a byte to a fnv64a hash value, returning the updated hash. 25 | func hashAddByte(h uint64, b byte) uint64 { 26 | h ^= uint64(b) 27 | h *= prime64 28 | return h 29 | } 30 | -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Matt T. Proud 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package pbutil provides record length-delimited Protocol Buffer streaming. 16 | package pbutil 17 | -------------------------------------------------------------------------------- /vendor/github.com/pkg/errors/appveyor.yml: -------------------------------------------------------------------------------- 1 | version: build-{build}.{branch} 2 | 3 | clone_folder: C:\gopath\src\github.com\pkg\errors 4 | shallow_clone: true # for startup speed 5 | 6 | environment: 7 | GOPATH: C:\gopath 8 | 9 | platform: 10 | - x64 11 | 12 | # http://www.appveyor.com/docs/installed-software 13 | install: 14 | # some helpful output for debugging builds 15 | - go version 16 | - go env 17 | # pre-installed MinGW at C:\MinGW is 32bit only 18 | # but MSYS2 at C:\msys64 has mingw64 19 | - set PATH=C:\msys64\mingw64\bin;%PATH% 20 | - gcc --version 21 | - g++ --version 22 | 23 | build_script: 24 | - go install -v ./... 25 | 26 | test_script: 27 | - set PATH=C:\gopath\bin;%PATH% 28 | - go test -v ./... 29 | 30 | #artifacts: 31 | # - path: '%GOPATH%\bin\*.exe' 32 | deploy: off 33 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/model/model.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package model contains common data structures that are shared across 15 | // Prometheus components and libraries. 16 | package model 17 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/memory_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package windows 6 | 7 | const ( 8 | MEM_COMMIT = 0x00001000 9 | MEM_RESERVE = 0x00002000 10 | MEM_DECOMMIT = 0x00004000 11 | MEM_RELEASE = 0x00008000 12 | MEM_RESET = 0x00080000 13 | MEM_TOP_DOWN = 0x00100000 14 | MEM_WRITE_WATCH = 0x00200000 15 | MEM_PHYSICAL = 0x00400000 16 | MEM_RESET_UNDO = 0x01000000 17 | MEM_LARGE_PAGES = 0x20000000 18 | 19 | PAGE_NOACCESS = 0x01 20 | PAGE_READONLY = 0x02 21 | PAGE_READWRITE = 0x04 22 | PAGE_WRITECOPY = 0x08 23 | PAGE_EXECUTE_READ = 0x20 24 | PAGE_EXECUTE_READWRITE = 0x40 25 | PAGE_EXECUTE_WRITECOPY = 0x80 26 | ) 27 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/eventlog.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package windows 8 | 9 | const ( 10 | EVENTLOG_SUCCESS = 0 11 | EVENTLOG_ERROR_TYPE = 1 12 | EVENTLOG_WARNING_TYPE = 2 13 | EVENTLOG_INFORMATION_TYPE = 4 14 | EVENTLOG_AUDIT_SUCCESS = 8 15 | EVENTLOG_AUDIT_FAILURE = 16 16 | ) 17 | 18 | //sys RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) [failretval==0] = advapi32.RegisterEventSourceW 19 | //sys DeregisterEventSource(handle Handle) (err error) = advapi32.DeregisterEventSource 20 | //sys ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) = advapi32.ReportEventW 21 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/encoder_cbor.go: -------------------------------------------------------------------------------- 1 | // +build binary_log 2 | 3 | package zerolog 4 | 5 | // This file contains bindings to do binary encoding. 6 | 7 | import ( 8 | "github.com/rs/zerolog/internal/cbor" 9 | ) 10 | 11 | var ( 12 | _ encoder = (*cbor.Encoder)(nil) 13 | 14 | enc = cbor.Encoder{} 15 | ) 16 | 17 | func appendJSON(dst []byte, j []byte) []byte { 18 | return cbor.AppendEmbeddedJSON(dst, j) 19 | } 20 | 21 | // decodeIfBinaryToString - converts a binary formatted log msg to a 22 | // JSON formatted String Log message. 23 | func decodeIfBinaryToString(in []byte) string { 24 | return cbor.DecodeIfBinaryToString(in) 25 | } 26 | 27 | func decodeObjectToStr(in []byte) string { 28 | return cbor.DecodeObjectToStr(in) 29 | } 30 | 31 | // decodeIfBinaryToBytes - converts a binary formatted log msg to a 32 | // JSON formatted Bytes Log message. 33 | func decodeIfBinaryToBytes(in []byte) []byte { 34 | return cbor.DecodeIfBinaryToBytes(in) 35 | } 36 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jet/damon 2 | 3 | require ( 4 | github.com/BurntSushi/toml v0.3.0 // indirect 5 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 // indirect 6 | github.com/golang/protobuf v1.2.0 // indirect 7 | github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect 8 | github.com/natefinch/lumberjack v2.0.0+incompatible 9 | github.com/pkg/errors v0.8.0 10 | github.com/prometheus/client_golang v0.8.0 11 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 // indirect 12 | github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e // indirect 13 | github.com/prometheus/procfs v0.0.0-20180920065004-418d78d0b9a7 // indirect 14 | github.com/rs/zerolog v1.9.1 15 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect 16 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e 17 | gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect 18 | gopkg.in/yaml.v2 v2.2.1 // indirect 19 | ) 20 | 21 | go 1.13 22 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/NOTICE: -------------------------------------------------------------------------------- 1 | Prometheus instrumentation library for Go applications 2 | Copyright 2012-2015 The Prometheus Authors 3 | 4 | This product includes software developed at 5 | SoundCloud Ltd. (http://soundcloud.com/). 6 | 7 | 8 | The following components are included in this product: 9 | 10 | perks - a fork of https://github.com/bmizerany/perks 11 | https://github.com/beorn7/perks 12 | Copyright 2013-2015 Blake Mizerany, Björn Rabenstein 13 | See https://github.com/beorn7/perks/blob/master/README.md for license details. 14 | 15 | Go support for Protocol Buffers - Google's data interchange format 16 | http://github.com/golang/protobuf/ 17 | Copyright 2010 The Go Authors 18 | See source code for license details. 19 | 20 | Support for streaming Protocol Buffer messages for the Go language (golang). 21 | https://github.com/matttproud/golang_protobuf_extensions 22 | Copyright 2013 Matt T. Proud 23 | Licensed under the Apache License, Version 2.0 24 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Prometheus uses GitHub to manage reviews of pull requests. 4 | 5 | * If you have a trivial fix or improvement, go ahead and create a pull request, 6 | addressing (with `@...`) the maintainer of this repository (see 7 | [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request. 8 | 9 | * If you plan to do something more involved, first discuss your ideas 10 | on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). 11 | This will avoid unnecessary work and surely give you and us a good deal 12 | of inspiration. 13 | 14 | * Relevant coding style guidelines are the [Go Code Review 15 | Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) 16 | and the _Formatting and style_ section of Peter Bourgon's [Go: Best 17 | Practices for Production 18 | Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style). 19 | -------------------------------------------------------------------------------- /examples/damon-test-locally.ps1: -------------------------------------------------------------------------------- 1 | #!powershell 2 | 3 | ### 4 | # Set up some environment variable to simulate a Nomad Environment 5 | ### 6 | 7 | 8 | $env:DAMON_LOG_MAX_SIZE=100 9 | $env:DAMON_LOG_MAX_FILES=3 10 | $env:DAMON_LOG_DIR=$pwd.Path 11 | $env:DAMON_LOG_NAME="damon.log" 12 | 13 | $env:NOMAD_ALLOC_DIR = $pwd.Path 14 | $env:NOMAD_ALLOC_ID = "3f07eca7-adbc-454c-9e97-06d78ff28e28" 15 | $env:NOMAD_ALLOC_INDEX = "1" 16 | $env:NOMAD_TASK_NAME = "damon-test-task" 17 | $env:NOMAD_GROUP_NAME ="damon-group" 18 | $env:NOMAD_JOB_NAME = "damon-job" 19 | $env:NOMAD_DC="dev" 20 | $env:NOMAD_REGION="eastus2" 21 | $env:NOMAD_CPU_LIMIT="1024" 22 | $env:NOMAD_MEMORY_LIMIT="1024" 23 | 24 | $env:DAMON_ENFORCE_CPU_LIMIT="Y" 25 | $env:DAMON_CPU_LIMIT=2048 26 | 27 | $env:DAMON_ENFORCE_MEMORY_LIMIT="Y" 28 | $env:DAMON_MEMORY_LIMIT=128 29 | 30 | $env:DAMON_RESTRICTED_TOKEN = "Y" 31 | 32 | $env:DAMON_ADDR = "localhost:8080" 33 | $env:DAMON_METRICS_ENDPOINT = "/metrics" 34 | 35 | ### 36 | # Run Damon with your executable 37 | ### 38 | 39 | # Replace with location of your actual executables 40 | # or put them both in your PATH 41 | & damon.exe myservice.exe -------------------------------------------------------------------------------- /vendor/github.com/beorn7/perks/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2013 Blake Mizerany 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Olivier Poitrey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/natefinch/lumberjack/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Nate Finch 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/expfmt/fuzz.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Build only when actually fuzzing 15 | // +build gofuzz 16 | 17 | package expfmt 18 | 19 | import "bytes" 20 | 21 | // Fuzz text metric parser with with github.com/dvyukov/go-fuzz: 22 | // 23 | // go-fuzz-build github.com/prometheus/common/expfmt 24 | // go-fuzz -bin expfmt-fuzz.zip -workdir fuzz 25 | // 26 | // Further input samples should go in the folder fuzz/corpus. 27 | func Fuzz(in []byte) int { 28 | parser := TextParser{} 29 | _, err := parser.TextToMetricFamilies(bytes.NewReader(in)) 30 | 31 | if err != nil { 32 | return 0 33 | } 34 | 35 | return 1 36 | } 37 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/ctx.go: -------------------------------------------------------------------------------- 1 | package zerolog 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | var disabledLogger *Logger 8 | 9 | func init() { 10 | l := Nop() 11 | disabledLogger = &l 12 | } 13 | 14 | type ctxKey struct{} 15 | 16 | // WithContext returns a copy of ctx with l associated. If an instance of Logger 17 | // is already in the context, the context is not updated. 18 | // 19 | // For instance, to add a field to an existing logger in the context, use this 20 | // notation: 21 | // 22 | // ctx := r.Context() 23 | // l := zerolog.Ctx(ctx) 24 | // l.UpdateContext(func(c Context) Context { 25 | // return c.Str("bar", "baz") 26 | // }) 27 | func (l *Logger) WithContext(ctx context.Context) context.Context { 28 | if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok { 29 | if lp == l { 30 | // Do not store same logger. 31 | return ctx 32 | } 33 | } else if l.level == Disabled { 34 | // Do not store disabled logger. 35 | return ctx 36 | } 37 | return context.WithValue(ctx, ctxKey{}, l) 38 | } 39 | 40 | // Ctx returns the Logger associated with the ctx. If no logger 41 | // is associated, a disabled logger is returned. 42 | func Ctx(ctx context.Context) *Logger { 43 | if l, ok := ctx.Value(ctxKey{}).(*Logger); ok { 44 | return l 45 | } 46 | return disabledLogger 47 | } 48 | -------------------------------------------------------------------------------- /testcmd/diskio.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package main 4 | 5 | import ( 6 | "io/ioutil" 7 | "log" 8 | "math/rand" 9 | "os" 10 | "time" 11 | ) 12 | 13 | const DiskBufferSize = 1024 14 | 15 | func eatDiskIO(exitCh <-chan struct{}, doneCh chan struct{}) { 16 | defer close(doneCh) 17 | fd, err := ioutil.TempFile("", "eatDiskIO-*.tmp") 18 | if err != nil { 19 | LogErrorf(err, "create temp file failed") 20 | return 21 | } 22 | defer func() { 23 | LogErrorf(fd.Close(), "closed failed") 24 | LogErrorf(os.Remove(fd.Name()), "remove file failed '%s'", fd.Name()) 25 | }() 26 | t0 := time.Now() 27 | var r, w int 28 | for { 29 | select { 30 | case <-exitCh: 31 | return 32 | default: 33 | t1 := time.Now() 34 | if d := t1.Sub(t0); d > (1 * time.Second) { 35 | log.Printf("Read/Write: %.2f/%.2f Kbps", float64(r)/float64(d.Seconds())/1024.0, float64(w)/float64(d.Seconds())/1024.0) 36 | t0 = t1 37 | w, r = 0, 0 38 | } 39 | block := make([]byte, DiskBufferSize) 40 | rand.Read(block) 41 | 42 | n, err := fd.Write(block) 43 | w += n 44 | LogErrorf(err, "write failed") 45 | _, err = fd.Seek(0, 0) 46 | LogErrorf(err, "seek failed") 47 | 48 | n, err = fd.Read(block) 49 | r += n 50 | LogErrorf(err, "read failed") 51 | _, err = fd.Seek(0, 0) 52 | LogErrorf(err, "seek failed") 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /win32/resources_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import "testing" 6 | 7 | func TestReadMHz(t *testing.T) { 8 | mhz, err := getProcessorMHz() 9 | if err != nil { 10 | t.Fatal(err) 11 | } 12 | t.Logf("MHz = %d", mhz) 13 | } 14 | 15 | func TestGetSystemInfo(t *testing.T) { 16 | si, err := getSystemInfo() 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | t.Logf("numprocs = %d", si.dwNumberOfProcessors) 21 | } 22 | 23 | func TestGlobalMemoryStatusEx(t *testing.T) { 24 | ms, err := globalMemoryStatusEx() 25 | if err != nil { 26 | t.Fatal(err) 27 | } 28 | t.Logf("memory used %%: %d%%", ms.dwMemoryLoad) 29 | t.Logf("total physical memory: %d", ms.ullTotalPhys) 30 | t.Logf("avail physical memory: %d", ms.ullAvailPhys) 31 | t.Logf("total virtual memory: %d", ms.ullTotalVirtual) 32 | t.Logf("avail virtual memory: %d", ms.ullAvailVirtual) 33 | t.Logf("total page file: %d", ms.ullTotalPageFile) 34 | t.Logf("avail page file: %d", ms.ullAvailPageFile) 35 | } 36 | 37 | func TestGetResources(t *testing.T) { 38 | res := GetSystemResources() 39 | t.Logf("CPU Count = %d", res.CPUNumCores) 40 | t.Logf("CPU MHz = %.2f", res.CPUMhzPercore) 41 | t.Logf("Total CPU MHz = %.2f", res.CPUTotalTicks) 42 | t.Logf("Total Physical Memory MiB = %.2f", res.MemoryTotalPhysicalKB/1024.0) 43 | t.Logf("Total Virtual Memory MiB = %.2f", res.MemoryTotalVirtualKB/1024.0) 44 | } 45 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/model/fnv.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package model 15 | 16 | // Inline and byte-free variant of hash/fnv's fnv64a. 17 | 18 | const ( 19 | offset64 = 14695981039346656037 20 | prime64 = 1099511628211 21 | ) 22 | 23 | // hashNew initializies a new fnv64a hash value. 24 | func hashNew() uint64 { 25 | return offset64 26 | } 27 | 28 | // hashAdd adds a string to a fnv64a hash value, returning the updated hash. 29 | func hashAdd(h uint64, s string) uint64 { 30 | for i := 0; i < len(s); i++ { 31 | h ^= uint64(s[i]) 32 | h *= prime64 33 | } 34 | return h 35 | } 36 | 37 | // hashAddByte adds a byte to a fnv64a hash value, returning the updated hash. 38 | func hashAddByte(h uint64, b byte) uint64 { 39 | h ^= uint64(b) 40 | h *= prime64 41 | return h 42 | } 43 | -------------------------------------------------------------------------------- /vendor/modules.txt: -------------------------------------------------------------------------------- 1 | # github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 2 | github.com/beorn7/perks/quantile 3 | # github.com/golang/protobuf v1.2.0 4 | github.com/golang/protobuf/proto 5 | # github.com/matttproud/golang_protobuf_extensions v1.0.1 6 | github.com/matttproud/golang_protobuf_extensions/pbutil 7 | # github.com/natefinch/lumberjack v2.0.0+incompatible 8 | github.com/natefinch/lumberjack 9 | # github.com/pkg/errors v0.8.0 10 | github.com/pkg/errors 11 | # github.com/prometheus/client_golang v0.8.0 12 | github.com/prometheus/client_golang/prometheus 13 | github.com/prometheus/client_golang/prometheus/promhttp 14 | # github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 15 | github.com/prometheus/client_model/go 16 | # github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e 17 | github.com/prometheus/common/expfmt 18 | github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg 19 | github.com/prometheus/common/model 20 | # github.com/prometheus/procfs v0.0.0-20180920065004-418d78d0b9a7 21 | github.com/prometheus/procfs 22 | github.com/prometheus/procfs/internal/util 23 | github.com/prometheus/procfs/nfs 24 | github.com/prometheus/procfs/xfs 25 | # github.com/rs/zerolog v1.9.1 26 | github.com/rs/zerolog 27 | github.com/rs/zerolog/internal/cbor 28 | github.com/rs/zerolog/internal/json 29 | # golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e 30 | golang.org/x/sys/windows 31 | -------------------------------------------------------------------------------- /vendor/github.com/pkg/errors/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Dave Cheney 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 17 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 18 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 20 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 21 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 22 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 23 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 24 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/syslog.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | // +build !binary_log 3 | 4 | package zerolog 5 | 6 | import ( 7 | "io" 8 | ) 9 | 10 | // SyslogWriter is an interface matching a syslog.Writer struct. 11 | type SyslogWriter interface { 12 | io.Writer 13 | Debug(m string) error 14 | Info(m string) error 15 | Warning(m string) error 16 | Err(m string) error 17 | Emerg(m string) error 18 | Crit(m string) error 19 | } 20 | 21 | type syslogWriter struct { 22 | w SyslogWriter 23 | } 24 | 25 | // SyslogLevelWriter wraps a SyslogWriter and call the right syslog level 26 | // method matching the zerolog level. 27 | func SyslogLevelWriter(w SyslogWriter) LevelWriter { 28 | return syslogWriter{w} 29 | } 30 | 31 | func (sw syslogWriter) Write(p []byte) (n int, err error) { 32 | return sw.w.Write(p) 33 | } 34 | 35 | // WriteLevel implements LevelWriter interface. 36 | func (sw syslogWriter) WriteLevel(level Level, p []byte) (n int, err error) { 37 | switch level { 38 | case DebugLevel: 39 | err = sw.w.Debug(string(p)) 40 | case InfoLevel: 41 | err = sw.w.Info(string(p)) 42 | case WarnLevel: 43 | err = sw.w.Warning(string(p)) 44 | case ErrorLevel: 45 | err = sw.w.Err(string(p)) 46 | case FatalLevel: 47 | err = sw.w.Emerg(string(p)) 48 | case PanicLevel: 49 | err = sw.w.Crit(string(p)) 50 | case NoLevel: 51 | err = sw.w.Info(string(p)) 52 | default: 53 | panic("invalid level") 54 | } 55 | n = len(p) 56 | return 57 | } 58 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/internal/util/parse.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package util 15 | 16 | import "strconv" 17 | 18 | // ParseUint32s parses a slice of strings into a slice of uint32s. 19 | func ParseUint32s(ss []string) ([]uint32, error) { 20 | us := make([]uint32, 0, len(ss)) 21 | for _, s := range ss { 22 | u, err := strconv.ParseUint(s, 10, 32) 23 | if err != nil { 24 | return nil, err 25 | } 26 | 27 | us = append(us, uint32(u)) 28 | } 29 | 30 | return us, nil 31 | } 32 | 33 | // ParseUint64s parses a slice of strings into a slice of uint64s. 34 | func ParseUint64s(ss []string) ([]uint64, error) { 35 | us := make([]uint64, 0, len(ss)) 36 | for _, s := range ss { 37 | u, err := strconv.ParseUint(s, 10, 64) 38 | if err != nil { 39 | return nil, err 40 | } 41 | 42 | us = append(us, u) 43 | } 44 | 45 | return us, nil 46 | } 47 | -------------------------------------------------------------------------------- /win32/registry_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import "testing" 6 | 7 | func TestRegistryKeyRead(t *testing.T) { 8 | val := "CurrentMajorVersionNumber" 9 | key, err := OpenRegistryKey("HKEY_LOCAL_MACHINE", `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, RegistryKeyPermissions{Read: true}) 10 | if err != nil { 11 | t.Fatal("OpenRegistryKey", err) 12 | } 13 | defer key.Close() 14 | dw, err := key.ReadDWORDValue("CurrentMajorVersionNumber") 15 | if err != nil { 16 | t.Fatal("ReadDWORDValue('CurrentMajorVersionNumber')", err) 17 | } 18 | t.Logf("%v['%s'] = 0x%x", key, val, dw) 19 | } 20 | 21 | func TestRegistryKeyReadBadType(t *testing.T) { 22 | val := "SystemRoot" 23 | key, err := OpenRegistryKey("HKEY_LOCAL_MACHINE", `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, RegistryKeyPermissions{Read: true}) 24 | if err != nil { 25 | t.Fatal("OpenRegistryKey", err) 26 | } 27 | defer key.Close() 28 | if _, err = key.ReadDWORDValue(val); err == nil { 29 | t.Fatal("expected ReadDWORDValue to fail") 30 | } 31 | } 32 | 33 | func TestRegistryKeyBadKey(t *testing.T) { 34 | key, err := OpenRegistryKey("HKEY_LOCAL_MACHINE", `DOES_NOT_EXIST`, RegistryKeyPermissions{Read: true}) 35 | if err == nil { 36 | key.Close() 37 | t.Fatal("expected error") 38 | } 39 | } 40 | 41 | func TestRegistryKeyBadRootKey(t *testing.T) { 42 | key, err := OpenRegistryKey("HKEY_ROOT_DOES_NOT_EXIST", `DOES_NOT_EXIST`, RegistryKeyPermissions{Read: true}) 43 | if err == nil { 44 | key.Close() 45 | t.Fatal("expected error") 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Prometheus Team 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package procfs provides functions to retrieve system, kernel and process 15 | // metrics from the pseudo-filesystem proc. 16 | // 17 | // Example: 18 | // 19 | // package main 20 | // 21 | // import ( 22 | // "fmt" 23 | // "log" 24 | // 25 | // "github.com/prometheus/procfs" 26 | // ) 27 | // 28 | // func main() { 29 | // p, err := procfs.Self() 30 | // if err != nil { 31 | // log.Fatalf("could not get process: %s", err) 32 | // } 33 | // 34 | // stat, err := p.NewStat() 35 | // if err != nil { 36 | // log.Fatalf("could not get process stat: %s", err) 37 | // } 38 | // 39 | // fmt.Printf("command: %s\n", stat.Comm) 40 | // fmt.Printf("cpu time: %fs\n", stat.CPUTime()) 41 | // fmt.Printf("vsize: %dB\n", stat.VirtualMemory()) 42 | // fmt.Printf("rss: %dB\n", stat.ResidentMemory()) 43 | // } 44 | // 45 | package procfs 46 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/github.com/golang/protobuf/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2010 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/expfmt/expfmt.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package expfmt contains tools for reading and writing Prometheus metrics. 15 | package expfmt 16 | 17 | // Format specifies the HTTP content type of the different wire protocols. 18 | type Format string 19 | 20 | // Constants to assemble the Content-Type values for the different wire protocols. 21 | const ( 22 | TextVersion = "0.0.4" 23 | ProtoType = `application/vnd.google.protobuf` 24 | ProtoProtocol = `io.prometheus.client.MetricFamily` 25 | ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" 26 | 27 | // The Content-Type values for the different wire protocols. 28 | FmtUnknown Format = `` 29 | FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` 30 | FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` 31 | FmtProtoText Format = ProtoFmt + ` encoding=text` 32 | FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` 33 | ) 34 | 35 | const ( 36 | hdrContentType = "Content-Type" 37 | hdrAccept = "Accept" 38 | ) 39 | -------------------------------------------------------------------------------- /testcmd/netio.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package main 4 | 5 | import ( 6 | "log" 7 | "math/rand" 8 | "net" 9 | "time" 10 | ) 11 | 12 | const NetBufferSize = 1024 13 | 14 | func eatNetIO(exitCh <-chan struct{}, doneCh chan struct{}) { 15 | defer close(doneCh) 16 | listener, err := net.Listen("tcp", ":") 17 | defer listener.Close() 18 | if err != nil { 19 | return 20 | } 21 | // Reader 22 | go func() { 23 | conn, err := listener.Accept() 24 | if err != nil { 25 | return 26 | } 27 | var r int 28 | t0 := time.Now() 29 | for { 30 | select { 31 | case <-doneCh: 32 | return 33 | default: 34 | t1 := time.Now() 35 | if d := t1.Sub(t0); d > (1 * time.Second) { 36 | log.Printf("Read: %.2f/Kbps", float64(r)/float64(d.Seconds())/1024.0) 37 | t0 = t1 38 | r = 0 39 | } 40 | buffer := make([]byte, NetBufferSize) 41 | n, err := conn.Read(buffer) 42 | LogErrorf(err, "read failed") 43 | r += n 44 | } 45 | } 46 | }() 47 | // Writer 48 | addr := listener.Addr() 49 | conn, err := net.Dial(addr.Network(), addr.String()) 50 | defer conn.Close() 51 | if err != nil { 52 | return 53 | } 54 | t0 := time.Now() 55 | var w int 56 | for { 57 | select { 58 | case <-exitCh: 59 | return 60 | default: 61 | t1 := time.Now() 62 | if d := t1.Sub(t0); d > (1 * time.Second) { 63 | log.Printf("Write: %.2f/Kbps", float64(w)/float64(d.Seconds())/1024.0) 64 | t0 = t1 65 | w = 0 66 | } 67 | block := make([]byte, NetBufferSize) 68 | _, err := rand.Read(block) 69 | LogErrorf(err, "read failed") 70 | n, err := conn.Write(block) 71 | LogErrorf(err, "write failed") 72 | w += n 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/hook.go: -------------------------------------------------------------------------------- 1 | package zerolog 2 | 3 | // Hook defines an interface to a log hook. 4 | type Hook interface { 5 | // Run runs the hook with the event. 6 | Run(e *Event, level Level, message string) 7 | } 8 | 9 | // HookFunc is an adaptor to allow the use of an ordinary function 10 | // as a Hook. 11 | type HookFunc func(e *Event, level Level, message string) 12 | 13 | // Run implements the Hook interface. 14 | func (h HookFunc) Run(e *Event, level Level, message string) { 15 | h(e, level, message) 16 | } 17 | 18 | // LevelHook applies a different hook for each level. 19 | type LevelHook struct { 20 | NoLevelHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook 21 | } 22 | 23 | // Run implements the Hook interface. 24 | func (h LevelHook) Run(e *Event, level Level, message string) { 25 | switch level { 26 | case DebugLevel: 27 | if h.DebugHook != nil { 28 | h.DebugHook.Run(e, level, message) 29 | } 30 | case InfoLevel: 31 | if h.InfoHook != nil { 32 | h.InfoHook.Run(e, level, message) 33 | } 34 | case WarnLevel: 35 | if h.WarnHook != nil { 36 | h.WarnHook.Run(e, level, message) 37 | } 38 | case ErrorLevel: 39 | if h.ErrorHook != nil { 40 | h.ErrorHook.Run(e, level, message) 41 | } 42 | case FatalLevel: 43 | if h.FatalHook != nil { 44 | h.FatalHook.Run(e, level, message) 45 | } 46 | case PanicLevel: 47 | if h.PanicHook != nil { 48 | h.PanicHook.Run(e, level, message) 49 | } 50 | case NoLevel: 51 | if h.NoLevelHook != nil { 52 | h.NoLevelHook.Run(e, level, message) 53 | } 54 | } 55 | } 56 | 57 | // NewLevelHook returns a new LevelHook. 58 | func NewLevelHook() LevelHook { 59 | return LevelHook{} 60 | } 61 | -------------------------------------------------------------------------------- /win32/string_utils_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "bufio" 7 | "fmt" 8 | "io" 9 | "os" 10 | "strings" 11 | "testing" 12 | "unicode/utf16" 13 | "unicode/utf8" 14 | ) 15 | 16 | type StringTestFunc func(t *testing.T, str string) 17 | 18 | func RunTestStrings(t *testing.T, fn StringTestFunc) { 19 | t.Helper() 20 | fd, err := os.Open("./testdata/strings.txt") 21 | if err != nil { 22 | t.Fatal(err) 23 | } 24 | defer fd.Close() 25 | br := bufio.NewReader(fd) 26 | var eof bool 27 | var lineno int 28 | for !eof { 29 | lineno++ 30 | line, err := br.ReadString('\n') 31 | if err != nil { 32 | if err == io.EOF { 33 | eof = true 34 | } else { 35 | t.Error("error reading test data", err) 36 | } 37 | } 38 | if line == "" || strings.HasPrefix(line, "#") { 39 | continue 40 | } 41 | if !utf8.ValidString(line) { 42 | // not valid unicode this line 43 | continue 44 | } 45 | t.Run(fmt.Sprintf("testdata/strings.txt:%d", lineno), func(t *testing.T) { 46 | t.Helper() 47 | fn(t, line) 48 | }) 49 | } 50 | } 51 | 52 | func TestTextCharPtrToString(t *testing.T) { 53 | RunTestStrings(t, func(t *testing.T, str string) { 54 | text := Text(str) 55 | if cstr := CharPtrToString(text.Chars()); cstr != str { 56 | t.Errorf("CharPtrToString(text.Chars()) != str: %s != %s", text, str) 57 | } 58 | }) 59 | } 60 | func TestUTF16PtrToString(t *testing.T) { 61 | RunTestStrings(t, func(t *testing.T, str string) { 62 | utf16Str := append(utf16.Encode([]rune(str)), 0) // convert to UTF-16, NULL-terminated string 63 | if wstr := UTF16PtrToString(&utf16Str[0]); wstr != str { 64 | t.Errorf("UTF16PtrToString(&utf16Str[0]) != str: %s != %s", wstr, str) 65 | } 66 | }) 67 | } 68 | -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Matt T. Proud 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package pbutil 16 | 17 | import ( 18 | "encoding/binary" 19 | "io" 20 | 21 | "github.com/golang/protobuf/proto" 22 | ) 23 | 24 | // WriteDelimited encodes and dumps a message to the provided writer prefixed 25 | // with a 32-bit varint indicating the length of the encoded message, producing 26 | // a length-delimited record stream, which can be used to chain together 27 | // encoded messages of the same type together in a file. It returns the total 28 | // number of bytes written and any applicable error. This is roughly 29 | // equivalent to the companion Java API's MessageLite#writeDelimitedTo. 30 | func WriteDelimited(w io.Writer, m proto.Message) (n int, err error) { 31 | buffer, err := proto.Marshal(m) 32 | if err != nil { 33 | return 0, err 34 | } 35 | 36 | var buf [binary.MaxVarintLen32]byte 37 | encodedLength := binary.PutUvarint(buf[:], uint64(len(buffer))) 38 | 39 | sync, err := w.Write(buf[:encodedLength]) 40 | if err != nil { 41 | return sync, err 42 | } 43 | 44 | n, err = w.Write(buffer) 45 | return n + sync, err 46 | } 47 | -------------------------------------------------------------------------------- /version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | var ( 8 | // GitCommit is filled in by the compiler / build script 9 | GitCommit string 10 | 11 | // GitDescribe is filled in by the compiler / build script 12 | GitDescribe string 13 | 14 | // Number is the base semantic version number of the project 15 | Number = "0.1.1" 16 | 17 | // PreRelease is the pre-release information for this version 18 | PreRelease = "" 19 | 20 | // BuildMetadata is the build-metadata of this version 21 | BuildMetadata = "" 22 | 23 | // BuildTime is the build timestamp in ISO-8601 format 24 | BuildTime = "" 25 | ) 26 | 27 | // Info about the version 28 | type Info struct { 29 | Revision string 30 | Number string 31 | PreRelease string 32 | BuildMetadata string 33 | } 34 | 35 | // GetInfo gets the version information 36 | func GetInfo() Info { 37 | num := Number 38 | pre := PreRelease 39 | meta := BuildMetadata 40 | 41 | return Info{ 42 | Revision: GitCommit, 43 | Number: num, 44 | PreRelease: pre, 45 | BuildMetadata: meta, 46 | } 47 | } 48 | 49 | // String returns the semantic version 50 | func (i Info) String() string { 51 | version := i.Number 52 | 53 | if i.PreRelease != "" { 54 | version = fmt.Sprintf("%s-%s", version, i.PreRelease) 55 | } 56 | 57 | if i.BuildMetadata != "" { 58 | version = fmt.Sprintf("%s+%s", version, i.BuildMetadata) 59 | } 60 | return version 61 | } 62 | 63 | // FullString returns the full version string optionally including the git revision 64 | func (i Info) FullString(rev bool) string { 65 | str := i.String() 66 | if rev && i.Revision != "" { 67 | return fmt.Sprintf("Damon v%s (%s)", str, i.Revision) 68 | } 69 | return fmt.Sprintf("Damon v%s", str) 70 | } 71 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Guidelines for this Project 2 | 3 | ## How the Walmart Security team manages security for this project 4 | Walmart takes security seriously and wants to ensure that we maintain a secure environment for our customers and that we also provide secure solutions for the open source community. To help us achieve these goals, please note the following before using this software: 5 | 6 | - Review the software license to understand Walmart's obligations in terms of warranties and suitability for purpose 7 | - Review our Responsible Disclosure Policy: https://corporate.walmart.com/article/responsible-disclosure-policy 8 | - Report any security concerns or questions using our reporting form at the bottom of our Responsible Disclosure Policy page: https://corporate.walmart.com/article/responsible-disclosure-policy 9 | - We enforce SLAs on our security team and software engineers to remediate security bugs in a timely manner 10 | - Please monitor this repository and update your environment in a timely manner as we release patches and updates 11 | 12 | ## Responsibly Disclosing Security Bugs to Walmart 13 | If you find a security bug in this repository, please work with Walmart's security team following responsible disclosure principles and these guidelines: 14 | 15 | - Do not submit a normal issue or pull request in our public repository, instead report directly on our reporting form found at the bottom of our Responsible Disclosure Policy page: https://corporate.walmart.com/article/responsible-disclosure-policy 16 | - We will review your submission and may follow up for additional details 17 | - If you have a patch, we will review it and approve it privately; once approved for release you can submit it as a pull request publicly in our repos (we give credit where credit is due) 18 | -------------------------------------------------------------------------------- /testcmd/main.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "os" 8 | "os/signal" 9 | "time" 10 | ) 11 | 12 | func getArgDuration(i int, def time.Duration) time.Duration { 13 | if len(os.Args) > i { 14 | d, err := time.ParseDuration(os.Args[i]) 15 | if err != nil { 16 | fmt.Fprintf(os.Stderr, "error parsing arg %d [%s]: %v", i, os.Args[i], err) 17 | os.Exit(1) 18 | } 19 | return d 20 | } 21 | return def 22 | } 23 | 24 | func dieOnError(err error) { 25 | if err != nil { 26 | fmt.Fprintln(os.Stderr, err) 27 | os.Exit(1) 28 | } 29 | } 30 | 31 | func main() { 32 | if len(os.Args) <= 1 { 33 | fmt.Println("PID:", os.Getpid()) 34 | os.Exit(0) 35 | } 36 | rc := realMain() 37 | fmt.Println("rc", rc) 38 | os.Exit(rc) 39 | } 40 | 41 | func realMain() int { 42 | cmd := os.Args[1] 43 | doneCh := make(chan struct{}) 44 | exitCh := make(chan struct{}) 45 | sigCh := make(chan os.Signal) 46 | signal.Notify(sigCh) 47 | rc := 0 48 | switch cmd { 49 | case "err": 50 | close(doneCh) 51 | rc = 1 52 | case "wait": 53 | close(doneCh) 54 | break 55 | case "wait_nosig": 56 | time.Sleep(getArgDuration(2, 10*time.Second)) 57 | return 0 58 | case "batch_login": 59 | if len(os.Args) > 2 { 60 | dieOnError(addTestUserRights(os.Args[2], []string{"SeBatchLogonRight"})) 61 | } 62 | return 0 63 | case "cpu": 64 | go eatCPU(exitCh, doneCh) 65 | case "mem": 66 | go eatMemory(exitCh, doneCh) 67 | case "diskio": 68 | go eatDiskIO(exitCh, doneCh) 69 | case "netio": 70 | go eatNetIO(exitCh, doneCh) 71 | case "env": 72 | for _, env := range os.Environ() { 73 | fmt.Println(env) 74 | } 75 | } 76 | dur := getArgDuration(2, 10*time.Second) 77 | select { 78 | case <-sigCh: 79 | close(exitCh) 80 | rc = 1 81 | case <-time.After(dur): 82 | close(exitCh) 83 | } 84 | <-doneCh 85 | return rc 86 | } 87 | -------------------------------------------------------------------------------- /win32/sid_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "testing" 7 | ) 8 | 9 | func TestLookupAccountSID(t *testing.T) { 10 | adminSID, err := LookupAccountSID("", "BUILTIN\\Administrators") 11 | if err != nil { 12 | t.Fatal("LookupAccountSID('BUILTIN\\Administrators')", err) 13 | } 14 | actual := adminSID.String() 15 | expected := string(SIDAdministrators) 16 | if actual != expected { 17 | t.Fatalf("expected '%s', actual '%s", expected, actual) 18 | } 19 | } 20 | 21 | func TestLookupAccountSIDBadName(t *testing.T) { 22 | if _, err := LookupAccountSID("", "DOESNOT\\EXIST"); err == nil { 23 | t.Fatal("expected error") 24 | } 25 | } 26 | 27 | func TestSIDs(t *testing.T) { 28 | sidStrings := []StringSID{ 29 | SIDAdministrators, 30 | SIDUsers, 31 | SIDGuests, 32 | SIDPowerUsers, 33 | SIDAccountOperators, 34 | SIDServerOperators, 35 | SIDPrintOperators, 36 | SIDBackupOperators, 37 | SIDReplicators, 38 | SIDNTLMAuthentication, 39 | SIDSChannelAuthentication, 40 | SIDDigestAuthentication, 41 | SIDAllServices, 42 | SIDNTVirtualMachines, 43 | } 44 | for _, s := range sidStrings { 45 | t.Run(string(s), func(t *testing.T) { 46 | sid, err := s.ConvertToSID() 47 | if err != nil { 48 | t.Error("ConvertToSID failed", err) 49 | } 50 | sidCopy, err := sid.Copy() 51 | if err != nil { 52 | t.Error("sid.Copy failed", err) 53 | } 54 | if sidCopy == sid { 55 | t.Error("expected sidCopy != sid") 56 | } 57 | str, err := sid.StringErr() 58 | if err != nil { 59 | t.Error("sid.StringErr failed", err) 60 | } 61 | if str != string(s) { 62 | t.Errorf("sid.StringErr(): expected '%s', actual '%s", string(s), str) 63 | } 64 | str2 := sidCopy.String() 65 | if str2 != string(s) { 66 | t.Errorf("sidCopy.String(): expected '%s', actual '%s", string(s), str2) 67 | } 68 | }) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /win32/logger.go: -------------------------------------------------------------------------------- 1 | package win32 2 | 3 | import ( 4 | "sync" 5 | "sync/atomic" 6 | ) 7 | 8 | // Logger interface for allowing the internal window api calls to make 9 | // log entries in any external logging system 10 | // 11 | // Implementers should implement this simple interface and call SetLogger to enable 12 | // error logging of the win32 package 13 | type Logger interface { 14 | Error(err error, msg string) 15 | Logln(v ...interface{}) 16 | Logf(format string, args ...interface{}) 17 | } 18 | 19 | var globalLoggerLock sync.Mutex 20 | var globalLogger atomic.Value 21 | 22 | // SetLogger sets the logger to be used by the win32 api package 23 | // for errors and warnings 24 | func SetLogger(l Logger) { 25 | globalLoggerLock.Lock() 26 | defer globalLoggerLock.Unlock() 27 | globalLogger.Store(logWrapper{logger: l}) 28 | } 29 | 30 | func init() { 31 | SetLogger(logWrapper{logger: noopLogger{}}) 32 | } 33 | 34 | func logger() Logger { 35 | v := globalLogger.Load() 36 | return v.(Logger) 37 | } 38 | 39 | func Logf(format string, v ...interface{}) { 40 | logger().Logf(format, v...) 41 | } 42 | 43 | func Logln(v ...interface{}) { 44 | logger().Logln(v...) 45 | } 46 | 47 | func LogError(err error, msg string) { 48 | if err != nil { 49 | logger().Error(err, msg) 50 | } 51 | } 52 | 53 | type logWrapper struct { 54 | logger Logger 55 | } 56 | 57 | func (n logWrapper) Logf(format string, v ...interface{}) { 58 | n.logger.Logf(format, v...) 59 | } 60 | 61 | func (n logWrapper) Logln(v ...interface{}) { 62 | n.logger.Logln(v...) 63 | } 64 | 65 | func (n logWrapper) Error(err error, msg string) { 66 | n.logger.Error(err, msg) 67 | } 68 | 69 | // noopLogger silently discards logs 70 | type noopLogger struct{} 71 | 72 | func (n noopLogger) Logf(format string, v ...interface{}) { 73 | 74 | } 75 | 76 | func (n noopLogger) Logln(v ...interface{}) { 77 | 78 | } 79 | 80 | func (n noopLogger) Error(err error, msg string) { 81 | 82 | } 83 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/proc_io.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package procfs 15 | 16 | import ( 17 | "fmt" 18 | "io/ioutil" 19 | "os" 20 | ) 21 | 22 | // ProcIO models the content of /proc//io. 23 | type ProcIO struct { 24 | // Chars read. 25 | RChar uint64 26 | // Chars written. 27 | WChar uint64 28 | // Read syscalls. 29 | SyscR uint64 30 | // Write syscalls. 31 | SyscW uint64 32 | // Bytes read. 33 | ReadBytes uint64 34 | // Bytes written. 35 | WriteBytes uint64 36 | // Bytes written, but taking into account truncation. See 37 | // Documentation/filesystems/proc.txt in the kernel sources for 38 | // detailed explanation. 39 | CancelledWriteBytes int64 40 | } 41 | 42 | // NewIO creates a new ProcIO instance from a given Proc instance. 43 | func (p Proc) NewIO() (ProcIO, error) { 44 | pio := ProcIO{} 45 | 46 | f, err := os.Open(p.path("io")) 47 | if err != nil { 48 | return pio, err 49 | } 50 | defer f.Close() 51 | 52 | data, err := ioutil.ReadAll(f) 53 | if err != nil { 54 | return pio, err 55 | } 56 | 57 | ioFormat := "rchar: %d\nwchar: %d\nsyscr: %d\nsyscw: %d\n" + 58 | "read_bytes: %d\nwrite_bytes: %d\n" + 59 | "cancelled_write_bytes: %d\n" 60 | 61 | _, err = fmt.Sscanf(string(data), ioFormat, &pio.RChar, &pio.WChar, &pio.SyscR, 62 | &pio.SyscW, &pio.ReadBytes, &pio.WriteBytes, &pio.CancelledWriteBytes) 63 | 64 | return pio, err 65 | } 66 | -------------------------------------------------------------------------------- /metrics/metrics_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "math" 5 | "math/rand" 6 | "reflect" 7 | "testing" 8 | "testing/quick" 9 | "time" 10 | ) 11 | 12 | type testSensor struct { 13 | StartTime time.Time 14 | Cores int 15 | TimeScale float64 16 | KernelPerc float64 17 | UserPerc float64 18 | } 19 | 20 | func (s testSensor) MeasureCPU() CPUMeasurement { 21 | d := time.Duration(float64(time.Since(s.StartTime)) * s.TimeScale) 22 | return CPUMeasurement{ 23 | TotalTime: d, 24 | KernelTime: time.Duration(float64(d) * s.KernelPerc * float64(s.Cores)), 25 | UserTime: time.Duration(float64(d) * s.UserPerc * float64(s.Cores)), 26 | } 27 | } 28 | 29 | func TestCPUSampler(t *testing.T) { 30 | err := quick.Check(func(kernPerc float64, userPerc float64, cores int64, mhz float64) bool { 31 | sensor := testSensor{ 32 | StartTime: time.Now(), 33 | Cores: int(cores), 34 | TimeScale: 1000.0, 35 | KernelPerc: kernPerc, 36 | UserPerc: userPerc, 37 | } 38 | s := &CPUCollector{ 39 | Cores: int(cores), 40 | MHzPerCore: mhz, 41 | } 42 | // nolint 43 | for i := 0; i < 5; i++ { 44 | select { 45 | case <-time.After(1 * time.Millisecond): 46 | sample := s.Sample(sensor.MeasureCPU()) 47 | if math.Abs(sample.UserPercent-userPerc) > 0.01 { 48 | t.Errorf("user percent expected delta too great: expected=%.5f, actual=%.5f", userPerc, sample.UserPercent) 49 | return false 50 | } 51 | if math.Abs(sample.KernelPercent-kernPerc) > 0.01 { 52 | t.Errorf("kernel percent expected delta too great: expected=%.5f, actual=%.5f", userPerc, sample.UserPercent) 53 | return false 54 | } 55 | } 56 | } 57 | return true 58 | }, &quick.Config{ 59 | Values: func(v []reflect.Value, r *rand.Rand) { 60 | v[0] = reflect.ValueOf(r.Float64()) 61 | v[1] = reflect.ValueOf(r.Float64()) 62 | v[2] = reflect.ValueOf(1 + r.Int63n(64)) 63 | v[3] = reflect.ValueOf(1000 + r.Float64()*2000) 64 | }, 65 | }) 66 | if err != nil { 67 | t.Fatal(err) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/cbor/string.go: -------------------------------------------------------------------------------- 1 | package cbor 2 | 3 | // AppendStrings encodes and adds an array of strings to the dst byte array. 4 | func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { 5 | major := majorTypeArray 6 | l := len(vals) 7 | if l <= additionalMax { 8 | lb := byte(l) 9 | dst = append(dst, byte(major|lb)) 10 | } else { 11 | dst = appendCborTypePrefix(dst, major, uint64(l)) 12 | } 13 | for _, v := range vals { 14 | dst = e.AppendString(dst, v) 15 | } 16 | return dst 17 | } 18 | 19 | // AppendString encodes and adds a string to the dst byte array. 20 | func (Encoder) AppendString(dst []byte, s string) []byte { 21 | major := majorTypeUtf8String 22 | 23 | l := len(s) 24 | if l <= additionalMax { 25 | lb := byte(l) 26 | dst = append(dst, byte(major|lb)) 27 | } else { 28 | dst = appendCborTypePrefix(dst, majorTypeUtf8String, uint64(l)) 29 | } 30 | return append(dst, s...) 31 | } 32 | 33 | // AppendBytes encodes and adds an array of bytes to the dst byte array. 34 | func (Encoder) AppendBytes(dst, s []byte) []byte { 35 | major := majorTypeByteString 36 | 37 | l := len(s) 38 | if l <= additionalMax { 39 | lb := byte(l) 40 | dst = append(dst, byte(major|lb)) 41 | } else { 42 | dst = appendCborTypePrefix(dst, major, uint64(l)) 43 | } 44 | return append(dst, s...) 45 | } 46 | 47 | // AppendEmbeddedJSON adds a tag and embeds input JSON as such. 48 | func AppendEmbeddedJSON(dst, s []byte) []byte { 49 | major := majorTypeTags 50 | minor := additionalTypeEmbeddedJSON 51 | 52 | // Append the TAG to indicate this is Embedded JSON. 53 | dst = append(dst, byte(major|additionalTypeIntUint16)) 54 | dst = append(dst, byte(minor>>8)) 55 | dst = append(dst, byte(minor&0xff)) 56 | 57 | // Append the JSON Object as Byte String. 58 | major = majorTypeByteString 59 | 60 | l := len(s) 61 | if l <= additionalMax { 62 | lb := byte(l) 63 | dst = append(dst, byte(major|lb)) 64 | } else { 65 | dst = appendCborTypePrefix(dst, major, uint64(l)) 66 | } 67 | return append(dst, s...) 68 | } 69 | -------------------------------------------------------------------------------- /examples/damon-job.nomad: -------------------------------------------------------------------------------- 1 | job "damon-job" { 2 | region = "eastus2" 3 | datacenters = ["dev"] 4 | type = "service" 5 | group "damon-group" { 6 | count = 1 7 | task "damon-test-task" { 8 | artifact { 9 | ## Replace whith wheverer damon is hosted 10 | source = "https://example.com/damon.exe.zip" 11 | } 12 | artifact { 13 | ## Replace with wherever your service artifact is hosted 14 | source = "https://example.com/myservice.exe.zip" 15 | } 16 | driver = "raw_exec" 17 | config { 18 | # Damon is the task entrypoint 19 | command = "${NOMAD_TASK_DIR}/damon.exe" 20 | # Your command and services should be in the 'args' section 21 | args = ["${NOMAD_TASK_DIR}/myservice.exe"] 22 | } 23 | resources { 24 | cpu = 1024 25 | memory = 1024 26 | network { 27 | mbits = 100 28 | 29 | ## For your own http endpoint 30 | port "http" {} 31 | 32 | ## For metrics exposed by Damon 33 | port "damon" {} 34 | } 35 | } 36 | env { 37 | ## Example of overriding NOMAD_CPU_LIMIT to give it more CPU than allocated 38 | "DAMON_CPU_LIMIT" = "2048" 39 | } 40 | ## For your own HTTP endpoint service 41 | service { 42 | port = "http" 43 | check { 44 | type = "http" 45 | path = "/health" 46 | interval = "10s" 47 | timeout = "2s" 48 | } 49 | } 50 | ## For damon's metrics endpoint 51 | service { 52 | port = "damon" 53 | name = "${NOMAD_TASK_NAME}-damon" 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /win32/userenv_win32.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "syscall" 7 | "unicode/utf16" 8 | "unsafe" 9 | ) 10 | 11 | var ( 12 | procCreateEnvironmentBlock = userenvDLL.NewProc("CreateEnvironmentBlock") 13 | procDestroyEnvironmentBlock = userenvDLL.NewProc("DestroyEnvironmentBlock") 14 | ) 15 | 16 | // BOOL CreateEnvironmentBlock( 17 | // LPVOID *lpEnvironment, 18 | // HANDLE hToken, 19 | // BOOL bInherit 20 | // ); 21 | // https://docs.microsoft.com/en-us/windows/desktop/api/userenv/nf-userenv-createenvironmentblock 22 | func createEnvironmentBlock(hToken syscall.Token, inherit bool) (syscall.Handle, error) { 23 | var lpEnvironment syscall.Handle 24 | ret, _, errno := procCreateEnvironmentBlock.Call( 25 | uintptr(unsafe.Pointer(&lpEnvironment)), 26 | uintptr(hToken), 27 | uintptr(toBOOL(inherit)), 28 | ) 29 | if err := testReturnCodeTrue(ret, errno); err != nil { 30 | return 0, err 31 | } 32 | return lpEnvironment, nil 33 | } 34 | 35 | // BOOL DestroyEnvironmentBlock( 36 | // LPVOID lpEnvironment 37 | // ); 38 | // https://docs.microsoft.com/en-us/windows/desktop/api/userenv/nf-userenv-destroyenvironmentblock 39 | func destroyEnvironmentBlock(lpEnvironment syscall.Handle) error { 40 | ret, _, errno := procDestroyEnvironmentBlock.Call(uintptr(lpEnvironment)) 41 | return testReturnCodeTrue(ret, errno) 42 | } 43 | 44 | // readEnvironmentBlock reads the environment block into a golang string-array 45 | // The environment block is an array of null-terminated Unicode (UTF-16) strings. 46 | // The list ends with two nulls (\0\0). 47 | func readEnvironmentBlock(lpEnvironment syscall.Handle) []string { 48 | var envs []string 49 | var nulls int 50 | var env []uint16 51 | for p := lpEnvironment; ; p += 2 { 52 | u := *(*uint16)(unsafe.Pointer(p)) 53 | if u == 0 { 54 | nulls++ 55 | if len(env) > 0 { 56 | envs = append(envs, string(utf16.Decode(env))) 57 | env = nil 58 | continue 59 | } 60 | if nulls == 2 { 61 | break 62 | } 63 | } 64 | env = append(env, u) 65 | nulls = 0 66 | } 67 | return envs 68 | } 69 | -------------------------------------------------------------------------------- /win32/ip_helper_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import "testing" 6 | 7 | func TestTCPTableeOwnerPID(t *testing.T) { 8 | table, err := GetTCPTableIP4OwnerPID(true, TCPTableAll) 9 | if err != nil { 10 | t.Fatal(err) 11 | } 12 | for i, row := range table { 13 | if row.State != TcpListen { 14 | t.Logf("%d: %d: %v:%d => %v:%d %s", i, row.PID, row.LocalAddress, row.LocalPort, row.RemoteAddress, row.RemotePort, row.State) 15 | } else { 16 | t.Logf("%d: %d: %v:%d %s", i, row.PID, row.LocalAddress, row.LocalPort, row.State) 17 | } 18 | } 19 | } 20 | 21 | func TestTCP6TableOwnerPID(t *testing.T) { 22 | table, err := GetTCPTableIP6OwnerPID(true, TCPTableAll) 23 | if err != nil { 24 | t.Fatal(err) 25 | } 26 | for i, row := range table { 27 | if row.State != TcpListen { 28 | t.Logf("%d: %d: [%v]:%d => [%v]:%d %s", i, row.PID, row.LocalAddress, row.LocalPort, row.RemoteAddress, row.RemotePort, row.State) 29 | } else { 30 | t.Logf("%d: %d: [%v]:%d %s", i, row.PID, row.LocalAddress, row.LocalPort, row.State) 31 | } 32 | } 33 | } 34 | 35 | func TestTCPTableOwnerModule(t *testing.T) { 36 | table, err := GetTCPTableIP4OwnerModule(true, TCPTableAll) 37 | if err != nil { 38 | t.Fatal(err) 39 | } 40 | for i, row := range table { 41 | if row.State != TcpListen { 42 | t.Logf("%d: %d (%s,%s): %v:%d => %v:%d %s", i, row.PID, row.ModuleName, row.ModulePath, row.LocalAddress, row.LocalPort, row.RemoteAddress, row.RemotePort, row.State) 43 | } else { 44 | t.Logf("%d: %d (%s,%s): %v:%d %s", i, row.PID, row.ModuleName, row.ModulePath, row.LocalAddress, row.LocalPort, row.State) 45 | } 46 | } 47 | } 48 | 49 | func TestTCP6TableOwnerModule(t *testing.T) { 50 | table, err := GetTCPTableIP6OwnerModule(true, TCPTableAll) 51 | if err != nil { 52 | t.Fatal(err) 53 | } 54 | for i, row := range table { 55 | if row.State != TcpListen { 56 | t.Logf("%d: %d (%s,%s): [%v]:%d => [%v]:%d %s", i, row.PID, row.ModuleName, row.ModulePath, row.LocalAddress, row.LocalPort, row.RemoteAddress, row.RemotePort, row.State) 57 | } else { 58 | t.Logf("%d: %d (%s,%s): [%v]:%d %s", i, row.PID, row.ModuleName, row.ModulePath, row.LocalAddress, row.LocalPort, row.State) 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/nfs/parse_nfs.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package nfs 15 | 16 | import ( 17 | "bufio" 18 | "fmt" 19 | "io" 20 | "strings" 21 | 22 | "github.com/prometheus/procfs/internal/util" 23 | ) 24 | 25 | // ParseClientRPCStats returns stats read from /proc/net/rpc/nfs 26 | func ParseClientRPCStats(r io.Reader) (*ClientRPCStats, error) { 27 | stats := &ClientRPCStats{} 28 | 29 | scanner := bufio.NewScanner(r) 30 | for scanner.Scan() { 31 | line := scanner.Text() 32 | parts := strings.Fields(scanner.Text()) 33 | // require at least 34 | if len(parts) < 2 { 35 | return nil, fmt.Errorf("invalid NFS metric line %q", line) 36 | } 37 | 38 | values, err := util.ParseUint64s(parts[1:]) 39 | if err != nil { 40 | return nil, fmt.Errorf("error parsing NFS metric line: %s", err) 41 | } 42 | 43 | switch metricLine := parts[0]; metricLine { 44 | case "net": 45 | stats.Network, err = parseNetwork(values) 46 | case "rpc": 47 | stats.ClientRPC, err = parseClientRPC(values) 48 | case "proc2": 49 | stats.V2Stats, err = parseV2Stats(values) 50 | case "proc3": 51 | stats.V3Stats, err = parseV3Stats(values) 52 | case "proc4": 53 | stats.ClientV4Stats, err = parseClientV4Stats(values) 54 | default: 55 | return nil, fmt.Errorf("unknown NFS metric line %q", metricLine) 56 | } 57 | if err != nil { 58 | return nil, fmt.Errorf("errors parsing NFS metric line: %s", err) 59 | } 60 | } 61 | 62 | if err := scanner.Err(); err != nil { 63 | return nil, fmt.Errorf("error scanning NFS file: %s", err) 64 | } 65 | 66 | return stats, nil 67 | } 68 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/globals.go: -------------------------------------------------------------------------------- 1 | package zerolog 2 | 3 | import "time" 4 | import "sync/atomic" 5 | 6 | var ( 7 | // TimestampFieldName is the field name used for the timestamp field. 8 | TimestampFieldName = "time" 9 | 10 | // LevelFieldName is the field name used for the level field. 11 | LevelFieldName = "level" 12 | 13 | // MessageFieldName is the field name used for the message field. 14 | MessageFieldName = "message" 15 | 16 | // ErrorFieldName is the field name used for error fields. 17 | ErrorFieldName = "error" 18 | 19 | // CallerFieldName is the field name used for caller field. 20 | CallerFieldName = "caller" 21 | 22 | // CallerSkipFrameCount is the number of stack frames to skip to find the caller. 23 | CallerSkipFrameCount = 2 24 | 25 | // TimeFieldFormat defines the time format of the Time field type. 26 | // If set to an empty string, the time is formatted as an UNIX timestamp 27 | // as integer. 28 | TimeFieldFormat = time.RFC3339 29 | 30 | // TimestampFunc defines the function called to generate a timestamp. 31 | TimestampFunc = time.Now 32 | 33 | // DurationFieldUnit defines the unit for time.Duration type fields added 34 | // using the Dur method. 35 | DurationFieldUnit = time.Millisecond 36 | 37 | // DurationFieldInteger renders Dur fields as integer instead of float if 38 | // set to true. 39 | DurationFieldInteger = false 40 | ) 41 | 42 | var ( 43 | gLevel = new(uint32) 44 | disableSampling = new(uint32) 45 | ) 46 | 47 | // SetGlobalLevel sets the global override for log level. If this 48 | // values is raised, all Loggers will use at least this value. 49 | // 50 | // To globally disable logs, set GlobalLevel to Disabled. 51 | func SetGlobalLevel(l Level) { 52 | atomic.StoreUint32(gLevel, uint32(l)) 53 | } 54 | 55 | // GlobalLevel returns the current global log level 56 | func GlobalLevel() Level { 57 | return Level(atomic.LoadUint32(gLevel)) 58 | } 59 | 60 | // DisableSampling will disable sampling in all Loggers if true. 61 | func DisableSampling(v bool) { 62 | var i uint32 63 | if v { 64 | i = 1 65 | } 66 | atomic.StoreUint32(disableSampling, i) 67 | } 68 | 69 | func samplingDisabled() bool { 70 | return atomic.LoadUint32(disableSampling) == 1 71 | } 72 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/proc_ns.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package procfs 15 | 16 | import ( 17 | "fmt" 18 | "os" 19 | "strconv" 20 | "strings" 21 | ) 22 | 23 | // Namespace represents a single namespace of a process. 24 | type Namespace struct { 25 | Type string // Namespace type. 26 | Inode uint32 // Inode number of the namespace. If two processes are in the same namespace their inodes will match. 27 | } 28 | 29 | // Namespaces contains all of the namespaces that the process is contained in. 30 | type Namespaces map[string]Namespace 31 | 32 | // NewNamespaces reads from /proc/[pid/ns/* to get the namespaces of which the 33 | // process is a member. 34 | func (p Proc) NewNamespaces() (Namespaces, error) { 35 | d, err := os.Open(p.path("ns")) 36 | if err != nil { 37 | return nil, err 38 | } 39 | defer d.Close() 40 | 41 | names, err := d.Readdirnames(-1) 42 | if err != nil { 43 | return nil, fmt.Errorf("failed to read contents of ns dir: %v", err) 44 | } 45 | 46 | ns := make(Namespaces, len(names)) 47 | for _, name := range names { 48 | target, err := os.Readlink(p.path("ns", name)) 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | fields := strings.SplitN(target, ":", 2) 54 | if len(fields) != 2 { 55 | return nil, fmt.Errorf("failed to parse namespace type and inode from '%v'", target) 56 | } 57 | 58 | typ := fields[0] 59 | inode, err := strconv.ParseUint(strings.Trim(fields[1], "[]"), 10, 32) 60 | if err != nil { 61 | return nil, fmt.Errorf("failed to parse inode from '%v': %v", fields[1], err) 62 | } 63 | 64 | ns[name] = Namespace{typ, uint32(inode)} 65 | } 66 | 67 | return ns, nil 68 | } 69 | -------------------------------------------------------------------------------- /win32/resources.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "fmt" 7 | "math" 8 | "sync" 9 | 10 | "github.com/pkg/errors" 11 | ) 12 | 13 | type SystemResources struct { 14 | CPUMhzPercore float64 15 | CPUNumCores int 16 | CPUTotalTicks float64 17 | MemoryTotalPhysicalKB float64 18 | MemoryTotalVirtualKB float64 19 | } 20 | 21 | var ( 22 | systemResources SystemResources 23 | 24 | onceInit sync.Once 25 | ) 26 | 27 | func getNumCores() (int, error) { 28 | si, err := getSystemInfo() 29 | if err != nil { 30 | return 0, err 31 | } 32 | return int(si.dwNumberOfProcessors), nil 33 | } 34 | 35 | func GetSystemResources() SystemResources { 36 | var err error 37 | onceInit.Do(func() { 38 | var cpuNumCores int 39 | cpuNumCores, err = getNumCores() 40 | if err != nil { 41 | err = fmt.Errorf("Unable to determine the number of CPU cores available: %v", err) 42 | return 43 | } 44 | var mhz uint32 45 | mhz, err = getProcessorMHz() 46 | if err != nil { 47 | err = fmt.Errorf("Unable to obtain CPU MHz: %v", err) 48 | return 49 | } 50 | var mem *_MEMORYSTATUSEX 51 | mem, err = globalMemoryStatusEx() 52 | if err != nil { 53 | err = fmt.Errorf("Unable to obtain total system memory: %v", err) 54 | return 55 | } 56 | systemResources = SystemResources{ 57 | MemoryTotalPhysicalKB: float64(mem.ullTotalPhys) / float64(1024), 58 | MemoryTotalVirtualKB: float64(mem.ullTotalVirtual) / float64(1024), 59 | CPUMhzPercore: float64(mhz), 60 | CPUTotalTicks: math.Floor(float64(cpuNumCores) * float64(mhz)), 61 | CPUNumCores: cpuNumCores, 62 | } 63 | }) 64 | if err != nil { 65 | panic(err) 66 | } 67 | return systemResources 68 | } 69 | 70 | func getProcessorMHz() (uint32, error) { 71 | subKey := `HARDWARE\DESCRIPTION\System\CentralProcessor\0` 72 | key, err := OpenRegistryKey("HKLM", subKey, RegistryKeyPermissions{Read: true}) 73 | if err != nil { 74 | return 0, errors.Wrapf(err, "getProcessorMHz: could not open HKLM:%s", subKey) 75 | } 76 | defer CloseLogErr(key, fmt.Sprintf("getProcessorMHz: could not close key HKLM:%s", subKey)) 77 | mhz, err := key.ReadDWORDValue("~MHz") 78 | if err != nil { 79 | return 0, errors.Wrapf(err, "getProcessorMHz: could not open HKLM:%s", subKey) 80 | } 81 | return mhz, nil 82 | } 83 | -------------------------------------------------------------------------------- /win32/lsa.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "syscall" 7 | "unsafe" 8 | 9 | "github.com/pkg/errors" 10 | ) 11 | 12 | // RemoveAllAccountRights removes all of the privilege assignments for the given SID in the Local Security Policy 13 | func RemoveAllAccountRights(s *SID) error { 14 | sid := (*syscall.SID)(unsafe.Pointer(s)) 15 | phPolicy, err := lsaOpenPolicy("", _POLICY_WRITE) 16 | if err != nil { 17 | return errors.Wrapf(err, "lsaOpenPolicy") 18 | } 19 | defer lsaClose(*phPolicy) 20 | if err = lsaRemoveAccountRights(*phPolicy, sid, true, nil); err != nil { 21 | return errors.Wrapf(err, "lsaRemoveAccountRights") 22 | } 23 | return nil 24 | } 25 | 26 | // RemoveAccountRights removes the given privileges from the given SID in the Local Security Policy 27 | func RemoveAccountRights(s *SID, privs []string) error { 28 | sid := (*syscall.SID)(unsafe.Pointer(s)) 29 | phPolicy, err := lsaOpenPolicy("", _POLICY_WRITE) 30 | if err != nil { 31 | return errors.Wrapf(err, "lsaOpenPolicy") 32 | } 33 | defer lsaClose(*phPolicy) 34 | if err = lsaRemoveAccountRights(*phPolicy, sid, false, privs); err != nil { 35 | return errors.Wrapf(err, "lsaRemoveAccountRights") 36 | } 37 | return nil 38 | } 39 | 40 | // AddAccountRights adds the given privileges from the given SID in the Local Security Policy 41 | func AddAccountRights(s *SID, privs []string) error { 42 | sid := (*syscall.SID)(unsafe.Pointer(s)) 43 | phPolicy, err := lsaOpenPolicy("", _POLICY_WRITE) 44 | if err != nil { 45 | return errors.Wrapf(err, "lsaOpenPolicy") 46 | } 47 | defer lsaClose(*phPolicy) 48 | if err = lsaAddAccountRights(*phPolicy, sid, privs); err != nil { 49 | return errors.Wrapf(err, "lsaAddAccountRights") 50 | } 51 | return nil 52 | } 53 | 54 | // EnumerateAccountRights returns the list of account privileges assigned to the given SID 55 | func EnumerateAccountRights(s *SID) ([]string, error) { 56 | sid := (*syscall.SID)(unsafe.Pointer(s)) 57 | phPolicy, err := lsaOpenPolicy("", _POLICY_READ) 58 | if err != nil { 59 | return nil, errors.Wrapf(err, "lsaOpenPolicy") 60 | } 61 | defer lsaClose(*phPolicy) 62 | rights, err := lsaEnumerateAccountRights(*phPolicy, sid) 63 | if err != nil { 64 | str, _ := sid.String() 65 | return nil, errors.Wrapf(err, "lsaEnumerateAccountRights(%s)", str) 66 | } 67 | return rights, nil 68 | } 69 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/json/bytes.go: -------------------------------------------------------------------------------- 1 | package json 2 | 3 | import "unicode/utf8" 4 | 5 | // AppendBytes is a mirror of appendString with []byte arg 6 | func (Encoder) AppendBytes(dst, s []byte) []byte { 7 | dst = append(dst, '"') 8 | for i := 0; i < len(s); i++ { 9 | if !noEscapeTable[s[i]] { 10 | dst = appendBytesComplex(dst, s, i) 11 | return append(dst, '"') 12 | } 13 | } 14 | dst = append(dst, s...) 15 | return append(dst, '"') 16 | } 17 | 18 | // AppendHex encodes the input bytes to a hex string and appends 19 | // the encoded string to the input byte slice. 20 | // 21 | // The operation loops though each byte and encodes it as hex using 22 | // the hex lookup table. 23 | func (Encoder) AppendHex(dst, s []byte) []byte { 24 | dst = append(dst, '"') 25 | for _, v := range s { 26 | dst = append(dst, hex[v>>4], hex[v&0x0f]) 27 | } 28 | return append(dst, '"') 29 | } 30 | 31 | // appendBytesComplex is a mirror of the appendStringComplex 32 | // with []byte arg 33 | func appendBytesComplex(dst, s []byte, i int) []byte { 34 | start := 0 35 | for i < len(s) { 36 | b := s[i] 37 | if b >= utf8.RuneSelf { 38 | r, size := utf8.DecodeRune(s[i:]) 39 | if r == utf8.RuneError && size == 1 { 40 | if start < i { 41 | dst = append(dst, s[start:i]...) 42 | } 43 | dst = append(dst, `\ufffd`...) 44 | i += size 45 | start = i 46 | continue 47 | } 48 | i += size 49 | continue 50 | } 51 | if noEscapeTable[b] { 52 | i++ 53 | continue 54 | } 55 | // We encountered a character that needs to be encoded. 56 | // Let's append the previous simple characters to the byte slice 57 | // and switch our operation to read and encode the remainder 58 | // characters byte-by-byte. 59 | if start < i { 60 | dst = append(dst, s[start:i]...) 61 | } 62 | switch b { 63 | case '"', '\\': 64 | dst = append(dst, '\\', b) 65 | case '\b': 66 | dst = append(dst, '\\', 'b') 67 | case '\f': 68 | dst = append(dst, '\\', 'f') 69 | case '\n': 70 | dst = append(dst, '\\', 'n') 71 | case '\r': 72 | dst = append(dst, '\\', 'r') 73 | case '\t': 74 | dst = append(dst, '\\', 't') 75 | default: 76 | dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) 77 | } 78 | i++ 79 | start = i 80 | } 81 | if start < len(s) { 82 | dst = append(dst, s[start:]...) 83 | } 84 | return dst 85 | } 86 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/exec_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Fork, exec, wait, etc. 6 | 7 | package windows 8 | 9 | // EscapeArg rewrites command line argument s as prescribed 10 | // in http://msdn.microsoft.com/en-us/library/ms880421. 11 | // This function returns "" (2 double quotes) if s is empty. 12 | // Alternatively, these transformations are done: 13 | // - every back slash (\) is doubled, but only if immediately 14 | // followed by double quote ("); 15 | // - every double quote (") is escaped by back slash (\); 16 | // - finally, s is wrapped with double quotes (arg -> "arg"), 17 | // but only if there is space or tab inside s. 18 | func EscapeArg(s string) string { 19 | if len(s) == 0 { 20 | return "\"\"" 21 | } 22 | n := len(s) 23 | hasSpace := false 24 | for i := 0; i < len(s); i++ { 25 | switch s[i] { 26 | case '"', '\\': 27 | n++ 28 | case ' ', '\t': 29 | hasSpace = true 30 | } 31 | } 32 | if hasSpace { 33 | n += 2 34 | } 35 | if n == len(s) { 36 | return s 37 | } 38 | 39 | qs := make([]byte, n) 40 | j := 0 41 | if hasSpace { 42 | qs[j] = '"' 43 | j++ 44 | } 45 | slashes := 0 46 | for i := 0; i < len(s); i++ { 47 | switch s[i] { 48 | default: 49 | slashes = 0 50 | qs[j] = s[i] 51 | case '\\': 52 | slashes++ 53 | qs[j] = s[i] 54 | case '"': 55 | for ; slashes > 0; slashes-- { 56 | qs[j] = '\\' 57 | j++ 58 | } 59 | qs[j] = '\\' 60 | j++ 61 | qs[j] = s[i] 62 | } 63 | j++ 64 | } 65 | if hasSpace { 66 | for ; slashes > 0; slashes-- { 67 | qs[j] = '\\' 68 | j++ 69 | } 70 | qs[j] = '"' 71 | j++ 72 | } 73 | return string(qs[:j]) 74 | } 75 | 76 | func CloseOnExec(fd Handle) { 77 | SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0) 78 | } 79 | 80 | // FullPath retrieves the full path of the specified file. 81 | func FullPath(name string) (path string, err error) { 82 | p, err := UTF16PtrFromString(name) 83 | if err != nil { 84 | return "", err 85 | } 86 | n := uint32(100) 87 | for { 88 | buf := make([]uint16, n) 89 | n, err = GetFullPathName(p, uint32(len(buf)), &buf[0], nil) 90 | if err != nil { 91 | return "", err 92 | } 93 | if n <= uint32(len(buf)) { 94 | return UTF16ToString(buf[:n]), nil 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /vendor/github.com/pkg/errors/README.md: -------------------------------------------------------------------------------- 1 | # errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) 2 | 3 | Package errors provides simple error handling primitives. 4 | 5 | `go get github.com/pkg/errors` 6 | 7 | The traditional error handling idiom in Go is roughly akin to 8 | ```go 9 | if err != nil { 10 | return err 11 | } 12 | ``` 13 | which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. 14 | 15 | ## Adding context to an error 16 | 17 | The errors.Wrap function returns a new error that adds context to the original error. For example 18 | ```go 19 | _, err := ioutil.ReadAll(r) 20 | if err != nil { 21 | return errors.Wrap(err, "read failed") 22 | } 23 | ``` 24 | ## Retrieving the cause of an error 25 | 26 | Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. 27 | ```go 28 | type causer interface { 29 | Cause() error 30 | } 31 | ``` 32 | `errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: 33 | ```go 34 | switch err := errors.Cause(err).(type) { 35 | case *MyError: 36 | // handle specifically 37 | default: 38 | // unknown error 39 | } 40 | ``` 41 | 42 | [Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). 43 | 44 | ## Contributing 45 | 46 | We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. 47 | 48 | Before proposing a change, please discuss your change by raising an issue. 49 | 50 | ## Licence 51 | 52 | BSD-2-Clause 53 | -------------------------------------------------------------------------------- /win32/tokens_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "os" 7 | "testing" 8 | ) 9 | 10 | func SetupUserLogin(t *testing.T) UserLogin { 11 | t.Helper() 12 | login := UserLogin{ 13 | Domain: os.Getenv("TEST_WIN32_USER_DOMAIN"), 14 | Username: os.Getenv("TEST_WIN32_USER_NAME"), 15 | Password: UnsafePasswordString(os.Getenv("TEST_WIN32_USER_PASSWORD")), 16 | } 17 | if login.Username == "" { 18 | t.Skip("TEST_WIN32_USER_NAME is empty") 19 | } 20 | return login 21 | } 22 | 23 | func TestCurrentProcessToken(t *testing.T) { 24 | token, err := CurrentProcessToken() 25 | if err != nil { 26 | t.Fatal(err) 27 | } 28 | defer token.Close() 29 | tt, err := token.TokenType() 30 | if err != nil { 31 | t.Fatal("TokenType", err) 32 | } 33 | if tt != TokenTypePrimary { 34 | t.Error("TokenType is Impersonation; should be TokenTypePrimary") 35 | } 36 | } 37 | 38 | func TestCreateBatchUserTokenBadPassword(t *testing.T) { 39 | login := SetupUserLogin(t) 40 | login.Password = UnsafePasswordString("___BAD_PASSWORD___") 41 | token, err := CreateBatchUserToken(login) 42 | if err == nil { 43 | defer token.Close() 44 | t.Fatal("CreateBatchUserToken: unexpected success") 45 | } 46 | t.Log(err) 47 | } 48 | 49 | func TestCreateBatchUserToken(t *testing.T) { 50 | login := SetupUserLogin(t) 51 | token, err := CreateBatchUserToken(login) 52 | if err != nil { 53 | t.Fatal("CreateBatchUserToken", err) 54 | } 55 | defer token.Close() 56 | tt, err := token.TokenType() 57 | if err != nil { 58 | t.Fatal("token.TokenType", err) 59 | } 60 | if tt != TokenTypePrimary { 61 | t.Error("token.TokenType is Impersonation; should be TokenTypePrimary") 62 | } 63 | envs, err := token.Environment(false) 64 | if err != nil { 65 | t.Error("token.Environment error", err) 66 | } 67 | for _, env := range envs { 68 | t.Logf(env) 69 | } 70 | restricted, err := token.CreateRestrictedToken(TokenRestrictions{ 71 | DisableMaxPrivilege: true, 72 | DisableSIDs: []string{ 73 | "BUILTIN\\Administrators", 74 | "BUILTIN\\Backup Operators", 75 | "BUILTIN\\Performance Log Users", 76 | }, 77 | }) 78 | if err != nil { 79 | t.Fatal("CreateRestrictedToken", err) 80 | } 81 | defer restricted.Close() 82 | rtt, err := restricted.TokenType() 83 | if err != nil { 84 | t.Fatal("restricted.TokenType", err) 85 | } 86 | if rtt != TokenTypePrimary { 87 | t.Error("restricted.TokenType is Impersonation; should be TokenTypePrimary") 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/encoder.go: -------------------------------------------------------------------------------- 1 | package zerolog 2 | 3 | import ( 4 | "net" 5 | "time" 6 | ) 7 | 8 | type encoder interface { 9 | AppendArrayDelim(dst []byte) []byte 10 | AppendArrayEnd(dst []byte) []byte 11 | AppendArrayStart(dst []byte) []byte 12 | AppendBeginMarker(dst []byte) []byte 13 | AppendBool(dst []byte, val bool) []byte 14 | AppendBools(dst []byte, vals []bool) []byte 15 | AppendBytes(dst, s []byte) []byte 16 | AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte 17 | AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte 18 | AppendEndMarker(dst []byte) []byte 19 | AppendFloat32(dst []byte, val float32) []byte 20 | AppendFloat64(dst []byte, val float64) []byte 21 | AppendFloats32(dst []byte, vals []float32) []byte 22 | AppendFloats64(dst []byte, vals []float64) []byte 23 | AppendHex(dst, s []byte) []byte 24 | AppendIPAddr(dst []byte, ip net.IP) []byte 25 | AppendIPPrefix(dst []byte, pfx net.IPNet) []byte 26 | AppendInt(dst []byte, val int) []byte 27 | AppendInt16(dst []byte, val int16) []byte 28 | AppendInt32(dst []byte, val int32) []byte 29 | AppendInt64(dst []byte, val int64) []byte 30 | AppendInt8(dst []byte, val int8) []byte 31 | AppendInterface(dst []byte, i interface{}) []byte 32 | AppendInts(dst []byte, vals []int) []byte 33 | AppendInts16(dst []byte, vals []int16) []byte 34 | AppendInts32(dst []byte, vals []int32) []byte 35 | AppendInts64(dst []byte, vals []int64) []byte 36 | AppendInts8(dst []byte, vals []int8) []byte 37 | AppendKey(dst []byte, key string) []byte 38 | AppendLineBreak(dst []byte) []byte 39 | AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte 40 | AppendNil(dst []byte) []byte 41 | AppendObjectData(dst []byte, o []byte) []byte 42 | AppendString(dst []byte, s string) []byte 43 | AppendStrings(dst []byte, vals []string) []byte 44 | AppendTime(dst []byte, t time.Time, format string) []byte 45 | AppendTimes(dst []byte, vals []time.Time, format string) []byte 46 | AppendUint(dst []byte, val uint) []byte 47 | AppendUint16(dst []byte, val uint16) []byte 48 | AppendUint32(dst []byte, val uint32) []byte 49 | AppendUint64(dst []byte, val uint64) []byte 50 | AppendUint8(dst []byte, val uint8) []byte 51 | AppendUints(dst []byte, vals []uint) []byte 52 | AppendUints16(dst []byte, vals []uint16) []byte 53 | AppendUints32(dst []byte, vals []uint32) []byte 54 | AppendUints64(dst []byte, vals []uint64) []byte 55 | AppendUints8(dst []byte, vals []uint8) []byte 56 | } 57 | -------------------------------------------------------------------------------- /win32/registry.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "encoding/binary" 7 | "fmt" 8 | "strings" 9 | 10 | "github.com/pkg/errors" 11 | ) 12 | 13 | // RegistryKey interfaces with the Windows Registry API 14 | type RegistryKey struct { 15 | str string 16 | hKey HKEY 17 | } 18 | 19 | // RegistryKeyPermissions selects the desired permissions 20 | type RegistryKeyPermissions struct { 21 | Read bool 22 | Write bool 23 | } 24 | 25 | // OpenRegistryKey opens the registry key with the desired permissions 26 | // The caller is responsible for closing it with the Close function 27 | func OpenRegistryKey(rootKey string, subKey string, perms RegistryKeyPermissions) (*RegistryKey, error) { 28 | hRootKey, ok := rootKeyHandles[strings.ToUpper(rootKey)] 29 | if !ok { 30 | return nil, errors.Errorf("win32: Root key name '%s' not valid", rootKey) 31 | } 32 | var access uint32 33 | if perms.Read { 34 | access |= _KEY_READ 35 | } 36 | if perms.Write { 37 | access |= _KEY_WRITE 38 | } 39 | hKey, err := regOpenKeyExW(hRootKey, subKey, access) 40 | if err != nil { 41 | return nil, errors.Wrapf(err, "win32: RegOpenKeyExW failed") 42 | } 43 | return &RegistryKey{hKey: hKey, str: fmt.Sprintf("%s\\%s", rootKeyNames[hRootKey], subKey)}, nil 44 | } 45 | 46 | // Close releases the registry key resource 47 | func (k *RegistryKey) Close() error { 48 | if err := regCloseKey(k.hKey); err != nil { 49 | return errors.Wrapf(err, "win32: regCloseKey failed") 50 | } 51 | return nil 52 | } 53 | 54 | // ReadValue reads a DWORD value out of the registry key 55 | // It will return an error if the value doesn't exist 56 | func (k *RegistryKey) ReadValue(name string) ([]byte, uint32, error) { 57 | return readRegValue(k.hKey, name) 58 | } 59 | 60 | // String prints the registry key path 61 | func (k *RegistryKey) String() string { 62 | return k.str 63 | } 64 | 65 | // ReadDWORDValue reads a DWORD value out of the registry key 66 | // It will return an error if the value doesn't exist 67 | // or if it is not one of the expected types: 68 | // - REG_DWORD 69 | // - REG_DWORD_BIG_ENDIAN 70 | func (k *RegistryKey) ReadDWORDValue(name string) (uint32, error) { 71 | kv, kt, err := k.ReadValue(name) 72 | if err != nil { 73 | return 0, err 74 | } 75 | switch kt { 76 | case _REG_DWORD: 77 | return (binary.LittleEndian.Uint32(kv)), nil 78 | case _REG_DWORD_BIG_ENDIAN: 79 | return (binary.BigEndian.Uint32(kv)), nil 80 | } 81 | return 0, errors.Wrapf(err, "value is not a DWORD") 82 | } 83 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/json/time.go: -------------------------------------------------------------------------------- 1 | package json 2 | 3 | import ( 4 | "strconv" 5 | "time" 6 | ) 7 | 8 | // AppendTime formats the input time with the given format 9 | // and appends the encoded string to the input byte slice. 10 | func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte { 11 | if format == "" { 12 | return e.AppendInt64(dst, t.Unix()) 13 | } 14 | return append(t.AppendFormat(append(dst, '"'), format), '"') 15 | } 16 | 17 | // AppendTimes converts the input times with the given format 18 | // and appends the encoded string list to the input byte slice. 19 | func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte { 20 | if format == "" { 21 | return appendUnixTimes(dst, vals) 22 | } 23 | if len(vals) == 0 { 24 | return append(dst, '[', ']') 25 | } 26 | dst = append(dst, '[') 27 | dst = append(vals[0].AppendFormat(append(dst, '"'), format), '"') 28 | if len(vals) > 1 { 29 | for _, t := range vals[1:] { 30 | dst = append(t.AppendFormat(append(dst, ',', '"'), format), '"') 31 | } 32 | } 33 | dst = append(dst, ']') 34 | return dst 35 | } 36 | 37 | func appendUnixTimes(dst []byte, vals []time.Time) []byte { 38 | if len(vals) == 0 { 39 | return append(dst, '[', ']') 40 | } 41 | dst = append(dst, '[') 42 | dst = strconv.AppendInt(dst, vals[0].Unix(), 10) 43 | if len(vals) > 1 { 44 | for _, t := range vals[1:] { 45 | dst = strconv.AppendInt(append(dst, ','), t.Unix(), 10) 46 | } 47 | } 48 | dst = append(dst, ']') 49 | return dst 50 | } 51 | 52 | // AppendDuration formats the input duration with the given unit & format 53 | // and appends the encoded string to the input byte slice. 54 | func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte { 55 | if useInt { 56 | return strconv.AppendInt(dst, int64(d/unit), 10) 57 | } 58 | return e.AppendFloat64(dst, float64(d)/float64(unit)) 59 | } 60 | 61 | // AppendDurations formats the input durations with the given unit & format 62 | // and appends the encoded string list to the input byte slice. 63 | func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte { 64 | if len(vals) == 0 { 65 | return append(dst, '[', ']') 66 | } 67 | dst = append(dst, '[') 68 | dst = e.AppendDuration(dst, vals[0], unit, useInt) 69 | if len(vals) > 1 { 70 | for _, d := range vals[1:] { 71 | dst = e.AppendDuration(append(dst, ','), d, unit, useInt) 72 | } 73 | } 74 | dst = append(dst, ']') 75 | return dst 76 | } 77 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt: -------------------------------------------------------------------------------- 1 | PACKAGE 2 | 3 | package goautoneg 4 | import "bitbucket.org/ww/goautoneg" 5 | 6 | HTTP Content-Type Autonegotiation. 7 | 8 | The functions in this package implement the behaviour specified in 9 | http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 10 | 11 | Copyright (c) 2011, Open Knowledge Foundation Ltd. 12 | All rights reserved. 13 | 14 | Redistribution and use in source and binary forms, with or without 15 | modification, are permitted provided that the following conditions are 16 | met: 17 | 18 | Redistributions of source code must retain the above copyright 19 | notice, this list of conditions and the following disclaimer. 20 | 21 | Redistributions in binary form must reproduce the above copyright 22 | notice, this list of conditions and the following disclaimer in 23 | the documentation and/or other materials provided with the 24 | distribution. 25 | 26 | Neither the name of the Open Knowledge Foundation Ltd. nor the 27 | names of its contributors may be used to endorse or promote 28 | products derived from this software without specific prior written 29 | permission. 30 | 31 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 32 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 33 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 34 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 35 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 36 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 37 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 38 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 39 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 40 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 41 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 42 | 43 | 44 | FUNCTIONS 45 | 46 | func Negotiate(header string, alternatives []string) (content_type string) 47 | Negotiate the most appropriate content_type given the accept header 48 | and a list of alternatives. 49 | 50 | func ParseAccept(header string) (accept []Accept) 51 | Parse an Accept Header string returning a sorted list 52 | of clauses 53 | 54 | 55 | TYPES 56 | 57 | type Accept struct { 58 | Type, SubType string 59 | Q float32 60 | Params map[string]string 61 | } 62 | Structure to represent a clause in an HTTP Accept Header 63 | 64 | 65 | SUBDIRECTORIES 66 | 67 | .hg 68 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/fs.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package procfs 15 | 16 | import ( 17 | "fmt" 18 | "os" 19 | "path" 20 | 21 | "github.com/prometheus/procfs/nfs" 22 | "github.com/prometheus/procfs/xfs" 23 | ) 24 | 25 | // FS represents the pseudo-filesystem proc, which provides an interface to 26 | // kernel data structures. 27 | type FS string 28 | 29 | // DefaultMountPoint is the common mount point of the proc filesystem. 30 | const DefaultMountPoint = "/proc" 31 | 32 | // NewFS returns a new FS mounted under the given mountPoint. It will error 33 | // if the mount point can't be read. 34 | func NewFS(mountPoint string) (FS, error) { 35 | info, err := os.Stat(mountPoint) 36 | if err != nil { 37 | return "", fmt.Errorf("could not read %s: %s", mountPoint, err) 38 | } 39 | if !info.IsDir() { 40 | return "", fmt.Errorf("mount point %s is not a directory", mountPoint) 41 | } 42 | 43 | return FS(mountPoint), nil 44 | } 45 | 46 | // Path returns the path of the given subsystem relative to the procfs root. 47 | func (fs FS) Path(p ...string) string { 48 | return path.Join(append([]string{string(fs)}, p...)...) 49 | } 50 | 51 | // XFSStats retrieves XFS filesystem runtime statistics. 52 | func (fs FS) XFSStats() (*xfs.Stats, error) { 53 | f, err := os.Open(fs.Path("fs/xfs/stat")) 54 | if err != nil { 55 | return nil, err 56 | } 57 | defer f.Close() 58 | 59 | return xfs.ParseStats(f) 60 | } 61 | 62 | // NFSClientRPCStats retrieves NFS client RPC statistics. 63 | func (fs FS) NFSClientRPCStats() (*nfs.ClientRPCStats, error) { 64 | f, err := os.Open(fs.Path("net/rpc/nfs")) 65 | if err != nil { 66 | return nil, err 67 | } 68 | defer f.Close() 69 | 70 | return nfs.ParseClientRPCStats(f) 71 | } 72 | 73 | // NFSdServerRPCStats retrieves NFS daemon RPC statistics. 74 | func (fs FS) NFSdServerRPCStats() (*nfs.ServerRPCStats, error) { 75 | f, err := os.Open(fs.Path("net/rpc/nfsd")) 76 | if err != nil { 77 | return nil, err 78 | } 79 | defer f.Close() 80 | 81 | return nfs.ParseServerRPCStats(f) 82 | } 83 | -------------------------------------------------------------------------------- /win32/string_utils.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "syscall" 7 | "unicode/utf16" 8 | "unsafe" 9 | ) 10 | 11 | type Text string 12 | 13 | func (t Text) String() string { 14 | return string(t) 15 | } 16 | 17 | func (t Text) Chars() *uint8 { 18 | if t == "" { 19 | return nil 20 | } 21 | return StringToCharPtr(string(t)) 22 | } 23 | 24 | func (t Text) WChars() *uint16 { 25 | if t == "" { 26 | return nil 27 | } 28 | bs, _ := syscall.UTF16FromString(string(t)) 29 | return &bs[0] 30 | } 31 | 32 | // CharPtrToString converts a null-terminated string 33 | // to a Go string. The C-String should be an ASCII-encoded string. 34 | // This method does not support Wide-Characters. 35 | // For Wide-characters, use UTF16PtrToString 36 | func CharPtrToString(cstr *uint8) string { 37 | if cstr == nil { 38 | return "" 39 | } 40 | var chars []byte 41 | for p := uintptr(unsafe.Pointer(cstr)); ; p++ { 42 | //nolint 43 | ch := *(*uint8)(unsafe.Pointer(p)) 44 | if ch == 0 { 45 | return string(chars) 46 | } 47 | chars = append(chars, ch) 48 | } 49 | } 50 | 51 | // StringToCharPtr converts a go string into a null-terminated string 52 | // The string should be an ASCII-encoded, not UTF-8. 53 | func StringToCharPtr(str string) *uint8 { 54 | if str == "" { 55 | n := []uint8{0} 56 | return &n[0] 57 | } 58 | chars := append([]byte(str), 0) // null terminated 59 | return &chars[0] 60 | } 61 | 62 | // UTF16PtrToString converts a null-terimanted UTF-16 encoded C-String 63 | // into a Go string. This method supports only wide-character 64 | // strings in UTF-16; not UTF-8. 65 | // For ASCII strings, use CharPtrToString. 66 | func UTF16PtrToString(wstr *uint16) string { 67 | if wstr != nil { 68 | us := make([]uint16, 0, 256) 69 | for p := uintptr(unsafe.Pointer(wstr)); ; p += 2 { 70 | //nolint 71 | u := *(*uint16)(unsafe.Pointer(p)) 72 | if u == 0 { 73 | return string(utf16.Decode(us)) 74 | } 75 | us = append(us, u) 76 | } 77 | } 78 | return "" 79 | } 80 | 81 | // UTF16PtrToStringN converts a UTF-16 encoded C-String 82 | // into a Go string. The n specifies the length of the string. 83 | // This function supports only wide-character strings in UTF-16; not UTF-8. 84 | func UTF16PtrToStringN(wstr *uint16, n int) string { 85 | if wstr != nil { 86 | us := make([]uint16, 0, n) 87 | i := 0 88 | for p := uintptr(unsafe.Pointer(wstr)); ; p += 2 { 89 | //nolint 90 | u := *(*uint16)(unsafe.Pointer(p)) 91 | us = append(us, u) 92 | i++ 93 | if i > n { 94 | return string(utf16.Decode(us)) 95 | } 96 | } 97 | } 98 | return "" 99 | } 100 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/Makefile: -------------------------------------------------------------------------------- 1 | # Copyright 2018 The Prometheus Authors 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | # Ensure GOBIN is not set during build so that promu is installed to the correct path 15 | unexport GOBIN 16 | 17 | GO ?= go 18 | GOFMT ?= $(GO)fmt 19 | FIRST_GOPATH := $(firstword $(subst :, ,$(shell $(GO) env GOPATH))) 20 | STATICCHECK := $(FIRST_GOPATH)/bin/staticcheck 21 | pkgs = $(shell $(GO) list ./... | grep -v /vendor/) 22 | 23 | PREFIX ?= $(shell pwd) 24 | BIN_DIR ?= $(shell pwd) 25 | 26 | ifdef DEBUG 27 | bindata_flags = -debug 28 | endif 29 | 30 | STATICCHECK_IGNORE = 31 | 32 | all: format staticcheck build test 33 | 34 | style: 35 | @echo ">> checking code style" 36 | @! $(GOFMT) -d $(shell find . -path ./vendor -prune -o -name '*.go' -print) | grep '^' 37 | 38 | check_license: 39 | @echo ">> checking license header" 40 | @./scripts/check_license.sh 41 | 42 | test: fixtures/.unpacked sysfs/fixtures/.unpacked 43 | @echo ">> running all tests" 44 | @$(GO) test -race $(shell $(GO) list ./... | grep -v /vendor/ | grep -v examples) 45 | 46 | format: 47 | @echo ">> formatting code" 48 | @$(GO) fmt $(pkgs) 49 | 50 | vet: 51 | @echo ">> vetting code" 52 | @$(GO) vet $(pkgs) 53 | 54 | staticcheck: $(STATICCHECK) 55 | @echo ">> running staticcheck" 56 | @$(STATICCHECK) -ignore "$(STATICCHECK_IGNORE)" $(pkgs) 57 | 58 | %/.unpacked: %.ttar 59 | ./ttar -C $(dir $*) -x -f $*.ttar 60 | touch $@ 61 | 62 | update_fixtures: fixtures.ttar sysfs/fixtures.ttar 63 | 64 | %fixtures.ttar: %/fixtures 65 | rm -v $(dir $*)fixtures/.unpacked 66 | ./ttar -C $(dir $*) -c -f $*fixtures.ttar fixtures/ 67 | 68 | $(FIRST_GOPATH)/bin/staticcheck: 69 | @GOOS= GOARCH= $(GO) get -u honnef.co/go/tools/cmd/staticcheck 70 | 71 | .PHONY: all style check_license format test vet staticcheck 72 | 73 | # Declaring the binaries at their default locations as PHONY targets is a hack 74 | # to ensure the latest version is downloaded on every make execution. 75 | # If this is not desired, copy/symlink these binaries to a different path and 76 | # set the respective environment variables. 77 | .PHONY: $(GOPATH)/bin/staticcheck 78 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/syscall.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // Package windows contains an interface to the low-level operating system 8 | // primitives. OS details vary depending on the underlying system, and 9 | // by default, godoc will display the OS-specific documentation for the current 10 | // system. If you want godoc to display syscall documentation for another 11 | // system, set $GOOS and $GOARCH to the desired system. For example, if 12 | // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS 13 | // to freebsd and $GOARCH to arm. 14 | // 15 | // The primary use of this package is inside other packages that provide a more 16 | // portable interface to the system, such as "os", "time" and "net". Use 17 | // those packages rather than this one if you can. 18 | // 19 | // For details of the functions and data types in this package consult 20 | // the manuals for the appropriate operating system. 21 | // 22 | // These calls return err == nil to indicate success; otherwise 23 | // err represents an operating system error describing the failure and 24 | // holds a value of type syscall.Errno. 25 | package windows // import "golang.org/x/sys/windows" 26 | 27 | import ( 28 | "syscall" 29 | ) 30 | 31 | // ByteSliceFromString returns a NUL-terminated slice of bytes 32 | // containing the text of s. If s contains a NUL byte at any 33 | // location, it returns (nil, syscall.EINVAL). 34 | func ByteSliceFromString(s string) ([]byte, error) { 35 | for i := 0; i < len(s); i++ { 36 | if s[i] == 0 { 37 | return nil, syscall.EINVAL 38 | } 39 | } 40 | a := make([]byte, len(s)+1) 41 | copy(a, s) 42 | return a, nil 43 | } 44 | 45 | // BytePtrFromString returns a pointer to a NUL-terminated array of 46 | // bytes containing the text of s. If s contains a NUL byte at any 47 | // location, it returns (nil, syscall.EINVAL). 48 | func BytePtrFromString(s string) (*byte, error) { 49 | a, err := ByteSliceFromString(s) 50 | if err != nil { 51 | return nil, err 52 | } 53 | return &a[0], nil 54 | } 55 | 56 | // Single-word zero for use when we need a valid pointer to 0 bytes. 57 | // See mksyscall.pl. 58 | var _zero uintptr 59 | 60 | func (ts *Timespec) Unix() (sec int64, nsec int64) { 61 | return int64(ts.Sec), int64(ts.Nsec) 62 | } 63 | 64 | func (tv *Timeval) Unix() (sec int64, nsec int64) { 65 | return int64(tv.Sec), int64(tv.Usec) * 1000 66 | } 67 | 68 | func (ts *Timespec) Nano() int64 { 69 | return int64(ts.Sec)*1e9 + int64(ts.Nsec) 70 | } 71 | 72 | func (tv *Timeval) Nano() int64 { 73 | return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 74 | } 75 | -------------------------------------------------------------------------------- /log/log.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path/filepath" 7 | 8 | "github.com/natefinch/lumberjack" 9 | "github.com/pkg/errors" 10 | "github.com/rs/zerolog" 11 | ) 12 | 13 | const DefaultLogName = "damon.log" 14 | const DefaultDamonNomadLogSuffix = ".damon.log" 15 | 16 | type LogConfig struct { 17 | MaxLogFiles int 18 | MaxSizeMB int 19 | LogDir string 20 | LogName string 21 | NomadAllocDir string 22 | NomadTaskName string 23 | NomadLogSuffix string 24 | } 25 | 26 | func (c LogConfig) Dir() (string, error) { 27 | if c.LogDir != "" { 28 | return c.LogDir, nil 29 | } 30 | if c.NomadAllocDir != "" { 31 | return filepath.Join(c.NomadAllocDir, "logs"), nil 32 | } 33 | return os.Getwd() 34 | } 35 | 36 | func (c LogConfig) Name() string { 37 | if c.LogName != "" { 38 | return c.LogName 39 | } 40 | if c.NomadTaskName != "" { 41 | if c.NomadLogSuffix != "" { 42 | return fmt.Sprintf("%s%s", c.NomadTaskName, c.NomadLogSuffix) 43 | } 44 | return fmt.Sprintf("%s%s", c.NomadTaskName, DefaultDamonNomadLogSuffix) 45 | } 46 | return DefaultLogName 47 | } 48 | 49 | func (c LogConfig) Path() (string, error) { 50 | dir, err := c.Dir() 51 | if err != nil { 52 | return "", err 53 | } 54 | return filepath.Join(dir, c.Name()), nil 55 | } 56 | 57 | type Logger struct { 58 | zl zerolog.Logger 59 | } 60 | 61 | func (l Logger) WithFields(fs map[string]interface{}) Logger { 62 | return Logger{ 63 | zl: l.zl.With().Fields(fs).Logger(), 64 | } 65 | } 66 | 67 | func (l Logger) Logln(v ...interface{}) { 68 | l.zl.Info().Msg(fmt.Sprint(v...)) 69 | } 70 | 71 | func (l Logger) Logf(format string, v ...interface{}) { 72 | l.zl.Info().Msgf(format, v...) 73 | } 74 | 75 | func (l Logger) Error(err error, msg string) { 76 | if err == nil { 77 | return 78 | } 79 | type stackTracer interface { 80 | StackTrace() errors.StackTrace 81 | } 82 | if v, ok := err.(stackTracer); ok { 83 | var stacktrace []string 84 | for _, frame := range v.StackTrace() { 85 | stacktrace = append(stacktrace, fmt.Sprintf("%+v", frame)) 86 | } 87 | logger := l.zl.With().Fields(map[string]interface{}{ 88 | "stacktrace": stacktrace, 89 | }).Logger() 90 | logger.Error().Err(err).Msg(msg) 91 | } else { 92 | l.zl.Error().Err(err).Msg(msg) 93 | } 94 | } 95 | 96 | func NewLogger(cfg LogConfig) (Logger, error) { 97 | filename, err := cfg.Path() 98 | if err != nil { 99 | return Logger{}, errors.Wrapf(err, "unable to get log directory") 100 | } 101 | logOut := &lumberjack.Logger{ 102 | Filename: filename, 103 | MaxSize: cfg.MaxSizeMB, 104 | MaxBackups: cfg.MaxLogFiles, 105 | } 106 | logger := zerolog.New(logOut).With().Timestamp().Logger() 107 | return Logger{ 108 | zl: logger, 109 | }, nil 110 | } 111 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/buddyinfo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package procfs 15 | 16 | import ( 17 | "bufio" 18 | "fmt" 19 | "io" 20 | "os" 21 | "strconv" 22 | "strings" 23 | ) 24 | 25 | // A BuddyInfo is the details parsed from /proc/buddyinfo. 26 | // The data is comprised of an array of free fragments of each size. 27 | // The sizes are 2^n*PAGE_SIZE, where n is the array index. 28 | type BuddyInfo struct { 29 | Node string 30 | Zone string 31 | Sizes []float64 32 | } 33 | 34 | // NewBuddyInfo reads the buddyinfo statistics. 35 | func NewBuddyInfo() ([]BuddyInfo, error) { 36 | fs, err := NewFS(DefaultMountPoint) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | return fs.NewBuddyInfo() 42 | } 43 | 44 | // NewBuddyInfo reads the buddyinfo statistics from the specified `proc` filesystem. 45 | func (fs FS) NewBuddyInfo() ([]BuddyInfo, error) { 46 | file, err := os.Open(fs.Path("buddyinfo")) 47 | if err != nil { 48 | return nil, err 49 | } 50 | defer file.Close() 51 | 52 | return parseBuddyInfo(file) 53 | } 54 | 55 | func parseBuddyInfo(r io.Reader) ([]BuddyInfo, error) { 56 | var ( 57 | buddyInfo = []BuddyInfo{} 58 | scanner = bufio.NewScanner(r) 59 | bucketCount = -1 60 | ) 61 | 62 | for scanner.Scan() { 63 | var err error 64 | line := scanner.Text() 65 | parts := strings.Fields(line) 66 | 67 | if len(parts) < 4 { 68 | return nil, fmt.Errorf("invalid number of fields when parsing buddyinfo") 69 | } 70 | 71 | node := strings.TrimRight(parts[1], ",") 72 | zone := strings.TrimRight(parts[3], ",") 73 | arraySize := len(parts[4:]) 74 | 75 | if bucketCount == -1 { 76 | bucketCount = arraySize 77 | } else { 78 | if bucketCount != arraySize { 79 | return nil, fmt.Errorf("mismatch in number of buddyinfo buckets, previous count %d, new count %d", bucketCount, arraySize) 80 | } 81 | } 82 | 83 | sizes := make([]float64, arraySize) 84 | for i := 0; i < arraySize; i++ { 85 | sizes[i], err = strconv.ParseFloat(parts[i+4], 64) 86 | if err != nil { 87 | return nil, fmt.Errorf("invalid value in buddyinfo: %s", err) 88 | } 89 | } 90 | 91 | buddyInfo = append(buddyInfo, BuddyInfo{node, zone, sizes}) 92 | } 93 | 94 | return buddyInfo, scanner.Err() 95 | } 96 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/nfs/parse_nfsd.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package nfs 15 | 16 | import ( 17 | "bufio" 18 | "fmt" 19 | "io" 20 | "strings" 21 | 22 | "github.com/prometheus/procfs/internal/util" 23 | ) 24 | 25 | // ParseServerRPCStats returns stats read from /proc/net/rpc/nfsd 26 | func ParseServerRPCStats(r io.Reader) (*ServerRPCStats, error) { 27 | stats := &ServerRPCStats{} 28 | 29 | scanner := bufio.NewScanner(r) 30 | for scanner.Scan() { 31 | line := scanner.Text() 32 | parts := strings.Fields(scanner.Text()) 33 | // require at least 34 | if len(parts) < 2 { 35 | return nil, fmt.Errorf("invalid NFSd metric line %q", line) 36 | } 37 | label := parts[0] 38 | 39 | var values []uint64 40 | var err error 41 | if label == "th" { 42 | if len(parts) < 3 { 43 | return nil, fmt.Errorf("invalid NFSd th metric line %q", line) 44 | } 45 | values, err = util.ParseUint64s(parts[1:3]) 46 | } else { 47 | values, err = util.ParseUint64s(parts[1:]) 48 | } 49 | if err != nil { 50 | return nil, fmt.Errorf("error parsing NFSd metric line: %s", err) 51 | } 52 | 53 | switch metricLine := parts[0]; metricLine { 54 | case "rc": 55 | stats.ReplyCache, err = parseReplyCache(values) 56 | case "fh": 57 | stats.FileHandles, err = parseFileHandles(values) 58 | case "io": 59 | stats.InputOutput, err = parseInputOutput(values) 60 | case "th": 61 | stats.Threads, err = parseThreads(values) 62 | case "ra": 63 | stats.ReadAheadCache, err = parseReadAheadCache(values) 64 | case "net": 65 | stats.Network, err = parseNetwork(values) 66 | case "rpc": 67 | stats.ServerRPC, err = parseServerRPC(values) 68 | case "proc2": 69 | stats.V2Stats, err = parseV2Stats(values) 70 | case "proc3": 71 | stats.V3Stats, err = parseV3Stats(values) 72 | case "proc4": 73 | stats.ServerV4Stats, err = parseServerV4Stats(values) 74 | case "proc4ops": 75 | stats.V4Ops, err = parseV4Ops(values) 76 | default: 77 | return nil, fmt.Errorf("unknown NFSd metric line %q", metricLine) 78 | } 79 | if err != nil { 80 | return nil, fmt.Errorf("errors parsing NFSd metric line: %s", err) 81 | } 82 | } 83 | 84 | if err := scanner.Err(); err != nil { 85 | return nil, fmt.Errorf("error scanning NFSd file: %s", err) 86 | } 87 | 88 | return stats, nil 89 | } 90 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/expfmt/encode.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package expfmt 15 | 16 | import ( 17 | "fmt" 18 | "io" 19 | "net/http" 20 | 21 | "github.com/golang/protobuf/proto" 22 | "github.com/matttproud/golang_protobuf_extensions/pbutil" 23 | "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg" 24 | 25 | dto "github.com/prometheus/client_model/go" 26 | ) 27 | 28 | // Encoder types encode metric families into an underlying wire protocol. 29 | type Encoder interface { 30 | Encode(*dto.MetricFamily) error 31 | } 32 | 33 | type encoder func(*dto.MetricFamily) error 34 | 35 | func (e encoder) Encode(v *dto.MetricFamily) error { 36 | return e(v) 37 | } 38 | 39 | // Negotiate returns the Content-Type based on the given Accept header. 40 | // If no appropriate accepted type is found, FmtText is returned. 41 | func Negotiate(h http.Header) Format { 42 | for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) { 43 | // Check for protocol buffer 44 | if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol { 45 | switch ac.Params["encoding"] { 46 | case "delimited": 47 | return FmtProtoDelim 48 | case "text": 49 | return FmtProtoText 50 | case "compact-text": 51 | return FmtProtoCompact 52 | } 53 | } 54 | // Check for text format. 55 | ver := ac.Params["version"] 56 | if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { 57 | return FmtText 58 | } 59 | } 60 | return FmtText 61 | } 62 | 63 | // NewEncoder returns a new encoder based on content type negotiation. 64 | func NewEncoder(w io.Writer, format Format) Encoder { 65 | switch format { 66 | case FmtProtoDelim: 67 | return encoder(func(v *dto.MetricFamily) error { 68 | _, err := pbutil.WriteDelimited(w, v) 69 | return err 70 | }) 71 | case FmtProtoCompact: 72 | return encoder(func(v *dto.MetricFamily) error { 73 | _, err := fmt.Fprintln(w, v.String()) 74 | return err 75 | }) 76 | case FmtProtoText: 77 | return encoder(func(v *dto.MetricFamily) error { 78 | _, err := fmt.Fprintln(w, proto.MarshalTextString(v)) 79 | return err 80 | }) 81 | case FmtText: 82 | return encoder(func(v *dto.MetricFamily) error { 83 | _, err := MetricFamilyToText(w, v) 84 | return err 85 | }) 86 | } 87 | panic("expfmt.NewEncoder: unknown format") 88 | } 89 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/cbor/time.go: -------------------------------------------------------------------------------- 1 | package cbor 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | func appendIntegerTimestamp(dst []byte, t time.Time) []byte { 8 | major := majorTypeTags 9 | minor := additionalTypeTimestamp 10 | dst = append(dst, byte(major|minor)) 11 | secs := t.Unix() 12 | var val uint64 13 | if secs < 0 { 14 | major = majorTypeNegativeInt 15 | val = uint64(-secs - 1) 16 | } else { 17 | major = majorTypeUnsignedInt 18 | val = uint64(secs) 19 | } 20 | dst = appendCborTypePrefix(dst, major, uint64(val)) 21 | return dst 22 | } 23 | 24 | func (e Encoder) appendFloatTimestamp(dst []byte, t time.Time) []byte { 25 | major := majorTypeTags 26 | minor := additionalTypeTimestamp 27 | dst = append(dst, byte(major|minor)) 28 | secs := t.Unix() 29 | nanos := t.Nanosecond() 30 | var val float64 31 | val = float64(secs)*1.0 + float64(nanos)*1E-9 32 | return e.AppendFloat64(dst, val) 33 | } 34 | 35 | // AppendTime encodes and adds a timestamp to the dst byte array. 36 | func (e Encoder) AppendTime(dst []byte, t time.Time, unused string) []byte { 37 | utc := t.UTC() 38 | if utc.Nanosecond() == 0 { 39 | return appendIntegerTimestamp(dst, utc) 40 | } 41 | return e.appendFloatTimestamp(dst, utc) 42 | } 43 | 44 | // AppendTimes encodes and adds an array of timestamps to the dst byte array. 45 | func (e Encoder) AppendTimes(dst []byte, vals []time.Time, unused string) []byte { 46 | major := majorTypeArray 47 | l := len(vals) 48 | if l == 0 { 49 | return e.AppendArrayEnd(e.AppendArrayStart(dst)) 50 | } 51 | if l <= additionalMax { 52 | lb := byte(l) 53 | dst = append(dst, byte(major|lb)) 54 | } else { 55 | dst = appendCborTypePrefix(dst, major, uint64(l)) 56 | } 57 | 58 | for _, t := range vals { 59 | dst = e.AppendTime(dst, t, unused) 60 | } 61 | return dst 62 | } 63 | 64 | // AppendDuration encodes and adds a duration to the dst byte array. 65 | // useInt field indicates whether to store the duration as seconds (integer) or 66 | // as seconds+nanoseconds (float). 67 | func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte { 68 | if useInt { 69 | return e.AppendInt64(dst, int64(d/unit)) 70 | } 71 | return e.AppendFloat64(dst, float64(d)/float64(unit)) 72 | } 73 | 74 | // AppendDurations encodes and adds an array of durations to the dst byte array. 75 | // useInt field indicates whether to store the duration as seconds (integer) or 76 | // as seconds+nanoseconds (float). 77 | func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte { 78 | major := majorTypeArray 79 | l := len(vals) 80 | if l == 0 { 81 | return e.AppendArrayEnd(e.AppendArrayStart(dst)) 82 | } 83 | if l <= additionalMax { 84 | lb := byte(l) 85 | dst = append(dst, byte(major|lb)) 86 | } else { 87 | dst = appendCborTypePrefix(dst, major, uint64(l)) 88 | } 89 | for _, d := range vals { 90 | dst = e.AppendDuration(dst, d, unit, useInt) 91 | } 92 | return dst 93 | } 94 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/writer.go: -------------------------------------------------------------------------------- 1 | package zerolog 2 | 3 | import ( 4 | "io" 5 | "sync" 6 | ) 7 | 8 | // LevelWriter defines as interface a writer may implement in order 9 | // to receive level information with payload. 10 | type LevelWriter interface { 11 | io.Writer 12 | WriteLevel(level Level, p []byte) (n int, err error) 13 | } 14 | 15 | type levelWriterAdapter struct { 16 | io.Writer 17 | } 18 | 19 | func (lw levelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error) { 20 | return lw.Write(p) 21 | } 22 | 23 | type syncWriter struct { 24 | mu sync.Mutex 25 | lw LevelWriter 26 | } 27 | 28 | // SyncWriter wraps w so that each call to Write is synchronized with a mutex. 29 | // This syncer can be the call to writer's Write method is not thread safe. 30 | // Note that os.File Write operation is using write() syscall which is supposed 31 | // to be thread-safe on POSIX systems. So there is no need to use this with 32 | // os.File on such systems as zerolog guaranties to issue a single Write call 33 | // per log event. 34 | func SyncWriter(w io.Writer) io.Writer { 35 | if lw, ok := w.(LevelWriter); ok { 36 | return &syncWriter{lw: lw} 37 | } 38 | return &syncWriter{lw: levelWriterAdapter{w}} 39 | } 40 | 41 | // Write implements the io.Writer interface. 42 | func (s *syncWriter) Write(p []byte) (n int, err error) { 43 | s.mu.Lock() 44 | defer s.mu.Unlock() 45 | return s.lw.Write(p) 46 | } 47 | 48 | // WriteLevel implements the LevelWriter interface. 49 | func (s *syncWriter) WriteLevel(l Level, p []byte) (n int, err error) { 50 | s.mu.Lock() 51 | defer s.mu.Unlock() 52 | return s.lw.WriteLevel(l, p) 53 | } 54 | 55 | type multiLevelWriter struct { 56 | writers []LevelWriter 57 | } 58 | 59 | func (t multiLevelWriter) Write(p []byte) (n int, err error) { 60 | for _, w := range t.writers { 61 | n, err = w.Write(p) 62 | if err != nil { 63 | return 64 | } 65 | if n != len(p) { 66 | err = io.ErrShortWrite 67 | return 68 | } 69 | } 70 | return len(p), nil 71 | } 72 | 73 | func (t multiLevelWriter) WriteLevel(l Level, p []byte) (n int, err error) { 74 | for _, w := range t.writers { 75 | n, err = w.WriteLevel(l, p) 76 | if err != nil { 77 | return 78 | } 79 | if n != len(p) { 80 | err = io.ErrShortWrite 81 | return 82 | } 83 | } 84 | return len(p), nil 85 | } 86 | 87 | // MultiLevelWriter creates a writer that duplicates its writes to all the 88 | // provided writers, similar to the Unix tee(1) command. If some writers 89 | // implement LevelWriter, their WriteLevel method will be used instead of Write. 90 | func MultiLevelWriter(writers ...io.Writer) LevelWriter { 91 | lwriters := make([]LevelWriter, 0, len(writers)) 92 | for _, w := range writers { 93 | if lw, ok := w.(LevelWriter); ok { 94 | lwriters = append(lwriters, lw) 95 | } else { 96 | lwriters = append(lwriters, levelWriterAdapter{w}) 97 | } 98 | } 99 | return multiLevelWriter{lwriters} 100 | } 101 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/model/fingerprinting.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package model 15 | 16 | import ( 17 | "fmt" 18 | "strconv" 19 | ) 20 | 21 | // Fingerprint provides a hash-capable representation of a Metric. 22 | // For our purposes, FNV-1A 64-bit is used. 23 | type Fingerprint uint64 24 | 25 | // FingerprintFromString transforms a string representation into a Fingerprint. 26 | func FingerprintFromString(s string) (Fingerprint, error) { 27 | num, err := strconv.ParseUint(s, 16, 64) 28 | return Fingerprint(num), err 29 | } 30 | 31 | // ParseFingerprint parses the input string into a fingerprint. 32 | func ParseFingerprint(s string) (Fingerprint, error) { 33 | num, err := strconv.ParseUint(s, 16, 64) 34 | if err != nil { 35 | return 0, err 36 | } 37 | return Fingerprint(num), nil 38 | } 39 | 40 | func (f Fingerprint) String() string { 41 | return fmt.Sprintf("%016x", uint64(f)) 42 | } 43 | 44 | // Fingerprints represents a collection of Fingerprint subject to a given 45 | // natural sorting scheme. It implements sort.Interface. 46 | type Fingerprints []Fingerprint 47 | 48 | // Len implements sort.Interface. 49 | func (f Fingerprints) Len() int { 50 | return len(f) 51 | } 52 | 53 | // Less implements sort.Interface. 54 | func (f Fingerprints) Less(i, j int) bool { 55 | return f[i] < f[j] 56 | } 57 | 58 | // Swap implements sort.Interface. 59 | func (f Fingerprints) Swap(i, j int) { 60 | f[i], f[j] = f[j], f[i] 61 | } 62 | 63 | // FingerprintSet is a set of Fingerprints. 64 | type FingerprintSet map[Fingerprint]struct{} 65 | 66 | // Equal returns true if both sets contain the same elements (and not more). 67 | func (s FingerprintSet) Equal(o FingerprintSet) bool { 68 | if len(s) != len(o) { 69 | return false 70 | } 71 | 72 | for k := range s { 73 | if _, ok := o[k]; !ok { 74 | return false 75 | } 76 | } 77 | 78 | return true 79 | } 80 | 81 | // Intersection returns the elements contained in both sets. 82 | func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSet { 83 | myLength, otherLength := len(s), len(o) 84 | if myLength == 0 || otherLength == 0 { 85 | return FingerprintSet{} 86 | } 87 | 88 | subSet := s 89 | superSet := o 90 | 91 | if otherLength < myLength { 92 | subSet = o 93 | superSet = s 94 | } 95 | 96 | out := FingerprintSet{} 97 | 98 | for k := range subSet { 99 | if _, ok := superSet[k]; ok { 100 | out[k] = struct{}{} 101 | } 102 | } 103 | 104 | return out 105 | } 106 | -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Matt T. Proud 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package pbutil 16 | 17 | import ( 18 | "encoding/binary" 19 | "errors" 20 | "io" 21 | 22 | "github.com/golang/protobuf/proto" 23 | ) 24 | 25 | var errInvalidVarint = errors.New("invalid varint32 encountered") 26 | 27 | // ReadDelimited decodes a message from the provided length-delimited stream, 28 | // where the length is encoded as 32-bit varint prefix to the message body. 29 | // It returns the total number of bytes read and any applicable error. This is 30 | // roughly equivalent to the companion Java API's 31 | // MessageLite#parseDelimitedFrom. As per the reader contract, this function 32 | // calls r.Read repeatedly as required until exactly one message including its 33 | // prefix is read and decoded (or an error has occurred). The function never 34 | // reads more bytes from the stream than required. The function never returns 35 | // an error if a message has been read and decoded correctly, even if the end 36 | // of the stream has been reached in doing so. In that case, any subsequent 37 | // calls return (0, io.EOF). 38 | func ReadDelimited(r io.Reader, m proto.Message) (n int, err error) { 39 | // Per AbstractParser#parsePartialDelimitedFrom with 40 | // CodedInputStream#readRawVarint32. 41 | var headerBuf [binary.MaxVarintLen32]byte 42 | var bytesRead, varIntBytes int 43 | var messageLength uint64 44 | for varIntBytes == 0 { // i.e. no varint has been decoded yet. 45 | if bytesRead >= len(headerBuf) { 46 | return bytesRead, errInvalidVarint 47 | } 48 | // We have to read byte by byte here to avoid reading more bytes 49 | // than required. Each read byte is appended to what we have 50 | // read before. 51 | newBytesRead, err := r.Read(headerBuf[bytesRead : bytesRead+1]) 52 | if newBytesRead == 0 { 53 | if err != nil { 54 | return bytesRead, err 55 | } 56 | // A Reader should not return (0, nil), but if it does, 57 | // it should be treated as no-op (according to the 58 | // Reader contract). So let's go on... 59 | continue 60 | } 61 | bytesRead += newBytesRead 62 | // Now present everything read so far to the varint decoder and 63 | // see if a varint can be decoded already. 64 | messageLength, varIntBytes = proto.DecodeVarint(headerBuf[:bytesRead]) 65 | } 66 | 67 | messageBuf := make([]byte, messageLength) 68 | newBytesRead, err := io.ReadFull(r, messageBuf) 69 | bytesRead += newBytesRead 70 | if err != nil { 71 | return bytesRead, err 72 | } 73 | 74 | return bytesRead, proto.Unmarshal(messageBuf, m) 75 | } 76 | -------------------------------------------------------------------------------- /make.ps1: -------------------------------------------------------------------------------- 1 | #!powershell 2 | [CmdletBinding()] 3 | Param( 4 | [Parameter(ParameterSetName='Test')] 5 | [switch]$Test, 6 | 7 | [Parameter(ParameterSetName='Test')] 8 | [switch]$VerboseOutput, 9 | 10 | [Parameter(ParameterSetName='Test')] 11 | [string]$CoverProfile = "cover.out", 12 | 13 | [Parameter(ParameterSetName='Lint')] 14 | [switch]$Lint, 15 | 16 | [Parameter(ParameterSetName='Build')] 17 | [switch]$Build, 18 | 19 | [Parameter(ParameterSetName='Build')] 20 | [string]$OutFile = "damon.exe" 21 | ) 22 | 23 | $GOLANG_LINT_VERSION="1.10.2" 24 | 25 | ## Setup 26 | $env:GOOS="windows" 27 | $env:GOARCH="amd64" 28 | $env:GO111MODULE="on" 29 | $env:GOFLAGS="-mod=vendor" 30 | 31 | ## Lint Code 32 | if ($Lint) { 33 | ## Install Linter 34 | if( -not (Test-Path -Path $env:GOPATH\bin\golangci-lint.exe)) { 35 | Mkdir -Path $env:GOPATH\bin | Out-Null 36 | Invoke-WebRequest -OutFile $env:GOPATH\bin\golangci-lint.zip -Uri "https://github.com/golangci/golangci-lint/releases/download/v${GOLANG_LINT_VERSION}/golangci-lint-${GOLANG_LINT_VERSION}-windows-amd64.zip" 37 | Expand-Archive $env:GOPATH\bin\golangci-lint.zip -DestinationPath $env:GOPATH\bin 38 | Move-Item -Path $env:GOPATH\bin\golangci-lint-${GOLANG_LINT_VERSION}-windows-amd64\*.exe -Destination $env:GOPATH\bin 39 | } 40 | ## Run Linter 41 | golangci-lint.exe run --exclude-use-default 42 | exit $LASTEXITCODE 43 | } 44 | 45 | ## Run Test + Coverage 46 | if($Test) { 47 | Write-Host "=== Test ===" 48 | $env:TEST_EXE_PATH = "$env:ALLUSERSPROFILE\test-damon.exe" 49 | Write-Host "Compiling ${env:TEST_EXE_PATH}" 50 | go.exe build -o $env:TEST_EXE_PATH ./testcmd/ 51 | if($env:APPVEYOR -eq "True") { 52 | $env:TEST_WIN32_USER_NAME="testuser" 53 | $env:TEST_WIN32_USER_PASSWORD="test123!" 54 | $user = Get-LocalUser -Name testuser -ErrorAction SilentlyContinue 55 | if(-not $user) { 56 | Write-Host "Create user $env:TEST_WIN32_USER_NAME" 57 | $password = ConvertTo-SecureString -AsPlainText -String $env:TEST_WIN32_USER_PASSWORD -Force 58 | New-LocalUser -Name $env:TEST_WIN32_USER_NAME -Password $password | Out-Null 59 | Write-Host "Assign 'Logon as Batch' rights" 60 | Start-Process -FilePath $env:TEST_EXE_PATH -ArgumentList "batch_login",$env:TEST_WIN32_USER_NAME | Wait-Process 61 | } 62 | } 63 | $v = if($VerboseOutput) { "-v" } else { "" } 64 | go.exe test $v -coverprofile $CoverProfile ./... 65 | exit $LASTEXITCODE 66 | } 67 | 68 | ## Run Build 69 | if($Build) { 70 | $gitRevision = $(git rev-parse HEAD) 71 | $gitDescribe = $(git describe 2> $null) 72 | $buildTimestamp = $(Get-Date -UFormat "%Y-%m-%dT%T%Z") 73 | 74 | $ldflags = "" 75 | $ldflags = "$ldflags -X github.com/jet/damon/version.GitCommit=${gitRevision}" 76 | $ldflags = "$ldflags -X github.com/jet/damon/version.GitDescribe=${gitDescribe}" 77 | $ldflags = "$ldflags -X github.com/jet/damon/version.BuildTime=${buildTimestamp}" 78 | 79 | Write-Host $gcflags 80 | go.exe build -o $OutFile -ldflags="$ldflags" . 81 | exit $LASTEXITCODE 82 | } 83 | 84 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v0.3.0 h1:e1/Ivsx3Z0FVTV0NSOv/aVgbUWyQuzj7DDnFblkRvsY= 2 | github.com/BurntSushi/toml v0.3.0/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 3 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0= 4 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 5 | github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= 6 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 7 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= 8 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 9 | github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM= 10 | github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk= 11 | github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= 12 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 13 | github.com/prometheus/client_golang v0.8.0 h1:1921Yw9Gc3iSc4VQh3PIoOqgPCZS7G/4xQNVUp8Mda8= 14 | github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 15 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 h1:idejC8f05m9MGOsuEi1ATq9shN03HrxNkD/luQvxCv8= 16 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 17 | github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e h1:n/3MEhJQjQxrOUCzh1Y3Re6aJUUWRp2M9+Oc3eVn/54= 18 | github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= 19 | github.com/prometheus/procfs v0.0.0-20180920065004-418d78d0b9a7 h1:NgR6WN8nQ4SmFC1sSUHY8SriLuWCZ6cCIQtH4vDZN3c= 20 | github.com/prometheus/procfs v0.0.0-20180920065004-418d78d0b9a7/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 21 | github.com/rs/zerolog v1.9.1 h1:AjV/SFRF0+gEa6rSjkh0Eji/DnkrJKVpPho6SW5g4mU= 22 | github.com/rs/zerolog v1.9.1/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= 23 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY= 24 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 25 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs= 26 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 27 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 28 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 29 | gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= 30 | gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= 31 | gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= 32 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 33 | -------------------------------------------------------------------------------- /win32/process_test.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "bytes" 7 | "context" 8 | "os" 9 | "os/exec" 10 | "strings" 11 | "testing" 12 | "time" 13 | ) 14 | 15 | func SkipIfDocker(t *testing.T) { 16 | t.Helper() 17 | if d := os.Getenv("DOCKER"); d != "" && d != "no" { 18 | t.Skip("SkipIfDocker") 19 | } 20 | } 21 | 22 | func TestRunProcess(t *testing.T) { 23 | buf := &bytes.Buffer{} 24 | cmd := exec.Command(SetupTestExe(t)) 25 | token, err := CurrentProcessToken() 26 | if err != nil { 27 | t.Fatal("CurrentProcessToken", err) 28 | } 29 | cmd.Stdout = buf 30 | defer token.Close() 31 | proc, err := CreateProcessWithToken(cmd, token) 32 | if err != nil { 33 | t.Fatal("CreateProcessWithToken", err) 34 | } 35 | if err = proc.Start(); err != nil { 36 | t.Fatal("proc.Start()", err) 37 | } 38 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 39 | defer cancel() 40 | res, err := proc.Wait(ctx.Done()) 41 | if err != nil { 42 | t.Fatal("proc.Wait()", err) 43 | } 44 | if rc := res.ExitStatus; rc != 0 { 45 | t.Fatalf("res.ExitStatus != 0: %d", rc) 46 | } 47 | t.Log("out", buf.String()) 48 | } 49 | 50 | func TestRunProcessWaitSignal(t *testing.T) { 51 | SkipIfDocker(t) 52 | buf := &bytes.Buffer{} 53 | cmd := exec.Command(SetupTestExe(t), "wait") 54 | token, err := CurrentProcessToken() 55 | if err != nil { 56 | t.Fatal("CurrentProcessToken", err) 57 | } 58 | cmd.Stdout = buf 59 | defer token.Close() 60 | proc, err := CreateProcessWithToken(cmd, token) 61 | if err != nil { 62 | t.Fatal("CreateProcessWithToken", err) 63 | } 64 | if err = proc.Start(); err != nil { 65 | t.Fatal("proc.Start()", err) 66 | } 67 | ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) 68 | defer cancel() 69 | res, err := proc.Wait(ctx.Done()) 70 | if err != nil { 71 | t.Fatal("proc.Wait()", err) 72 | } 73 | if rc := res.ExitStatus; rc != 1 { 74 | t.Fatalf("res.ExitStatus != 1: %d", rc) 75 | } 76 | out := strings.TrimSpace(buf.String()) 77 | exp := "rc 1" 78 | t.Log("out", out) 79 | if out != exp { 80 | t.Fatalf("out: expected '%s', actual '%s'", exp, out) 81 | } 82 | } 83 | 84 | func TestRunProcessWaitNoSignal(t *testing.T) { 85 | SkipIfDocker(t) 86 | buf := &bytes.Buffer{} 87 | cmd := exec.Command(SetupTestExe(t), "wait_nosig") 88 | token, err := CurrentProcessToken() 89 | if err != nil { 90 | t.Fatal("CurrentProcessToken", err) 91 | } 92 | cmd.Stdout = buf 93 | defer token.Close() 94 | proc, err := CreateProcessWithToken(cmd, token) 95 | if err != nil { 96 | t.Fatal("CreateProcessWithToken", err) 97 | } 98 | if err = proc.Start(); err != nil { 99 | t.Fatal("proc.Start()", err) 100 | } 101 | ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) 102 | defer cancel() 103 | res, err := proc.Wait(ctx.Done()) 104 | if err != nil { 105 | t.Fatal("proc.Wait()", err) 106 | } 107 | if rc := res.ExitStatus; rc != 0 { 108 | t.Fatalf("res.ExitStatus != 0: %d", rc) 109 | } 110 | out := strings.TrimSpace(buf.String()) 111 | exp := "rc 0" 112 | t.Log("out", out) 113 | if out != exp { 114 | t.Fatalf("out: expected '%s', actual '%s'", exp, out) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /win32/resources_win32.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "syscall" 7 | "unsafe" 8 | ) 9 | 10 | var ( 11 | procGetSystemInfo = kernel32DLL.NewProc("GetSystemInfo") 12 | procGlobalMemoryStatusEx = kernel32DLL.NewProc("GlobalMemoryStatusEx") 13 | ) 14 | 15 | // typedef struct _SYSTEM_INFO { 16 | // union { 17 | // DWORD dwOemId; 18 | // struct { 19 | // WORD wProcessorArchitecture; 20 | // WORD wReserved; 21 | // }; 22 | // }; 23 | // DWORD dwPageSize; 24 | // LPVOID lpMinimumApplicationAddress; 25 | // LPVOID lpMaximumApplicationAddress; 26 | // DWORD_PTR dwActiveProcessorMask; 27 | // DWORD dwNumberOfProcessors; 28 | // DWORD dwProcessorType; 29 | // DWORD dwAllocationGranularity; 30 | // WORD wProcessorLevel; 31 | // WORD wProcessorRevision; 32 | // } SYSTEM_INFO; 33 | // https://msdn.microsoft.com/en-us/library/ms724958(v=vs.85).aspx 34 | type _SYSTEM_INFO struct { 35 | dwOemId DWORD 36 | dwPageSize DWORD 37 | lpMinimumApplicationAddress uintptr 38 | lpMaximumApplicationAddress uintptr 39 | dwActiveProcessorMask uintptr 40 | dwNumberOfProcessors DWORD 41 | dwProcessorType DWORD 42 | dwAllocationGranularity DWORD 43 | wProcessorLevel WORD 44 | wProcessorRevision WORD 45 | } 46 | 47 | // void WINAPI GetSystemInfo( 48 | // _Out_ LPSYSTEM_INFO lpSystemInfo 49 | // ); 50 | // https://msdn.microsoft.com/en-us/library/ms724381(VS.85).aspx 51 | func getSystemInfo() (_SYSTEM_INFO, error) { 52 | var si _SYSTEM_INFO 53 | _, _, err := procGetSystemInfo.Call( 54 | uintptr(unsafe.Pointer(&si)), 55 | ) 56 | if err != syscall.Errno(0) { 57 | return si, err 58 | } 59 | return si, nil 60 | } 61 | 62 | // typedef struct _MEMORYSTATUSEX { 63 | // DWORD dwLength; 64 | // DWORD dwMemoryLoad; 65 | // DWORDLONG ullTotalPhys; 66 | // DWORDLONG ullAvailPhys; 67 | // DWORDLONG ullTotalPageFile; 68 | // DWORDLONG ullAvailPageFile; 69 | // DWORDLONG ullTotalVirtual; 70 | // DWORDLONG ullAvailVirtual; 71 | // DWORDLONG ullAvailExtendedVirtual; 72 | // } MEMORYSTATUSEX, *LPMEMORYSTATUSEX; 73 | // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx 74 | type _MEMORYSTATUSEX struct { 75 | dwLength uint32 76 | dwMemoryLoad uint32 77 | ullTotalPhys uint64 78 | ullAvailPhys uint64 79 | ullTotalPageFile uint64 80 | ullAvailPageFile uint64 81 | ullTotalVirtual uint64 82 | ullAvailVirtual uint64 83 | ullAvailExtendedVirtual uint64 84 | } 85 | 86 | // BOOL WINAPI GlobalMemoryStatusEx( 87 | // _Inout_ LPMEMORYSTATUSEX lpBuffer 88 | // ); 89 | // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx 90 | func globalMemoryStatusEx() (*_MEMORYSTATUSEX, error) { 91 | var Buffer _MEMORYSTATUSEX 92 | Buffer.dwLength = uint32(unsafe.Sizeof(Buffer)) 93 | ret, _, errno := procGlobalMemoryStatusEx.Call( 94 | uintptr(unsafe.Pointer(&Buffer)), 95 | ) 96 | if err := testReturnCodeNonZero(ret, errno); err != nil { 97 | return nil, err 98 | } 99 | return &Buffer, nil 100 | } 101 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/model/silence.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package model 15 | 16 | import ( 17 | "encoding/json" 18 | "fmt" 19 | "regexp" 20 | "time" 21 | ) 22 | 23 | // Matcher describes a matches the value of a given label. 24 | type Matcher struct { 25 | Name LabelName `json:"name"` 26 | Value string `json:"value"` 27 | IsRegex bool `json:"isRegex"` 28 | } 29 | 30 | func (m *Matcher) UnmarshalJSON(b []byte) error { 31 | type plain Matcher 32 | if err := json.Unmarshal(b, (*plain)(m)); err != nil { 33 | return err 34 | } 35 | 36 | if len(m.Name) == 0 { 37 | return fmt.Errorf("label name in matcher must not be empty") 38 | } 39 | if m.IsRegex { 40 | if _, err := regexp.Compile(m.Value); err != nil { 41 | return err 42 | } 43 | } 44 | return nil 45 | } 46 | 47 | // Validate returns true iff all fields of the matcher have valid values. 48 | func (m *Matcher) Validate() error { 49 | if !m.Name.IsValid() { 50 | return fmt.Errorf("invalid name %q", m.Name) 51 | } 52 | if m.IsRegex { 53 | if _, err := regexp.Compile(m.Value); err != nil { 54 | return fmt.Errorf("invalid regular expression %q", m.Value) 55 | } 56 | } else if !LabelValue(m.Value).IsValid() || len(m.Value) == 0 { 57 | return fmt.Errorf("invalid value %q", m.Value) 58 | } 59 | return nil 60 | } 61 | 62 | // Silence defines the representation of a silence definition in the Prometheus 63 | // eco-system. 64 | type Silence struct { 65 | ID uint64 `json:"id,omitempty"` 66 | 67 | Matchers []*Matcher `json:"matchers"` 68 | 69 | StartsAt time.Time `json:"startsAt"` 70 | EndsAt time.Time `json:"endsAt"` 71 | 72 | CreatedAt time.Time `json:"createdAt,omitempty"` 73 | CreatedBy string `json:"createdBy"` 74 | Comment string `json:"comment,omitempty"` 75 | } 76 | 77 | // Validate returns true iff all fields of the silence have valid values. 78 | func (s *Silence) Validate() error { 79 | if len(s.Matchers) == 0 { 80 | return fmt.Errorf("at least one matcher required") 81 | } 82 | for _, m := range s.Matchers { 83 | if err := m.Validate(); err != nil { 84 | return fmt.Errorf("invalid matcher: %s", err) 85 | } 86 | } 87 | if s.StartsAt.IsZero() { 88 | return fmt.Errorf("start time missing") 89 | } 90 | if s.EndsAt.IsZero() { 91 | return fmt.Errorf("end time missing") 92 | } 93 | if s.EndsAt.Before(s.StartsAt) { 94 | return fmt.Errorf("start time must be before end time") 95 | } 96 | if s.CreatedBy == "" { 97 | return fmt.Errorf("creator information missing") 98 | } 99 | if s.Comment == "" { 100 | return fmt.Errorf("comment missing") 101 | } 102 | if s.CreatedAt.IsZero() { 103 | return fmt.Errorf("creation timestamp missing") 104 | } 105 | return nil 106 | } 107 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/cbor/cbor.go: -------------------------------------------------------------------------------- 1 | // Package cbor provides primitives for storing different data 2 | // in the CBOR (binary) format. CBOR is defined in RFC7049. 3 | package cbor 4 | 5 | import "time" 6 | 7 | const ( 8 | majorOffset = 5 9 | additionalMax = 23 10 | 11 | // Non Values. 12 | additionalTypeBoolFalse byte = 20 13 | additionalTypeBoolTrue byte = 21 14 | additionalTypeNull byte = 22 15 | 16 | // Integer (+ve and -ve) Sub-types. 17 | additionalTypeIntUint8 byte = 24 18 | additionalTypeIntUint16 byte = 25 19 | additionalTypeIntUint32 byte = 26 20 | additionalTypeIntUint64 byte = 27 21 | 22 | // Float Sub-types. 23 | additionalTypeFloat16 byte = 25 24 | additionalTypeFloat32 byte = 26 25 | additionalTypeFloat64 byte = 27 26 | additionalTypeBreak byte = 31 27 | 28 | // Tag Sub-types. 29 | additionalTypeTimestamp byte = 01 30 | 31 | // Extended Tags - from https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml 32 | additionalTypeTagNetworkAddr uint16 = 260 33 | additionalTypeTagNetworkPrefix uint16 = 261 34 | additionalTypeEmbeddedJSON uint16 = 262 35 | additionalTypeTagHexString uint16 = 263 36 | 37 | // Unspecified number of elements. 38 | additionalTypeInfiniteCount byte = 31 39 | ) 40 | const ( 41 | majorTypeUnsignedInt byte = iota << majorOffset // Major type 0 42 | majorTypeNegativeInt // Major type 1 43 | majorTypeByteString // Major type 2 44 | majorTypeUtf8String // Major type 3 45 | majorTypeArray // Major type 4 46 | majorTypeMap // Major type 5 47 | majorTypeTags // Major type 6 48 | majorTypeSimpleAndFloat // Major type 7 49 | ) 50 | 51 | const ( 52 | maskOutAdditionalType byte = (7 << majorOffset) 53 | maskOutMajorType byte = 31 54 | ) 55 | 56 | const ( 57 | float32Nan = "\xfa\x7f\xc0\x00\x00" 58 | float32PosInfinity = "\xfa\x7f\x80\x00\x00" 59 | float32NegInfinity = "\xfa\xff\x80\x00\x00" 60 | float64Nan = "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00" 61 | float64PosInfinity = "\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00" 62 | float64NegInfinity = "\xfb\xff\xf0\x00\x00\x00\x00\x00\x00" 63 | ) 64 | 65 | // IntegerTimeFieldFormat indicates the format of timestamp decoded 66 | // from an integer (time in seconds). 67 | var IntegerTimeFieldFormat = time.RFC3339 68 | 69 | // NanoTimeFieldFormat indicates the format of timestamp decoded 70 | // from a float value (time in seconds and nano seconds). 71 | var NanoTimeFieldFormat = time.RFC3339Nano 72 | 73 | func appendCborTypePrefix(dst []byte, major byte, number uint64) []byte { 74 | byteCount := 8 75 | var minor byte 76 | switch { 77 | case number < 256: 78 | byteCount = 1 79 | minor = additionalTypeIntUint8 80 | 81 | case number < 65536: 82 | byteCount = 2 83 | minor = additionalTypeIntUint16 84 | 85 | case number < 4294967296: 86 | byteCount = 4 87 | minor = additionalTypeIntUint32 88 | 89 | default: 90 | byteCount = 8 91 | minor = additionalTypeIntUint64 92 | 93 | } 94 | dst = append(dst, byte(major|minor)) 95 | byteCount-- 96 | for ; byteCount >= 0; byteCount-- { 97 | dst = append(dst, byte(number>>(uint(byteCount)*8))) 98 | } 99 | return dst 100 | } 101 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/model/metric.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package model 15 | 16 | import ( 17 | "fmt" 18 | "regexp" 19 | "sort" 20 | "strings" 21 | ) 22 | 23 | var ( 24 | separator = []byte{0} 25 | // MetricNameRE is a regular expression matching valid metric 26 | // names. Note that the IsValidMetricName function performs the same 27 | // check but faster than a match with this regular expression. 28 | MetricNameRE = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`) 29 | ) 30 | 31 | // A Metric is similar to a LabelSet, but the key difference is that a Metric is 32 | // a singleton and refers to one and only one stream of samples. 33 | type Metric LabelSet 34 | 35 | // Equal compares the metrics. 36 | func (m Metric) Equal(o Metric) bool { 37 | return LabelSet(m).Equal(LabelSet(o)) 38 | } 39 | 40 | // Before compares the metrics' underlying label sets. 41 | func (m Metric) Before(o Metric) bool { 42 | return LabelSet(m).Before(LabelSet(o)) 43 | } 44 | 45 | // Clone returns a copy of the Metric. 46 | func (m Metric) Clone() Metric { 47 | clone := make(Metric, len(m)) 48 | for k, v := range m { 49 | clone[k] = v 50 | } 51 | return clone 52 | } 53 | 54 | func (m Metric) String() string { 55 | metricName, hasName := m[MetricNameLabel] 56 | numLabels := len(m) - 1 57 | if !hasName { 58 | numLabels = len(m) 59 | } 60 | labelStrings := make([]string, 0, numLabels) 61 | for label, value := range m { 62 | if label != MetricNameLabel { 63 | labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value)) 64 | } 65 | } 66 | 67 | switch numLabels { 68 | case 0: 69 | if hasName { 70 | return string(metricName) 71 | } 72 | return "{}" 73 | default: 74 | sort.Strings(labelStrings) 75 | return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", ")) 76 | } 77 | } 78 | 79 | // Fingerprint returns a Metric's Fingerprint. 80 | func (m Metric) Fingerprint() Fingerprint { 81 | return LabelSet(m).Fingerprint() 82 | } 83 | 84 | // FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing 85 | // algorithm, which is, however, more susceptible to hash collisions. 86 | func (m Metric) FastFingerprint() Fingerprint { 87 | return LabelSet(m).FastFingerprint() 88 | } 89 | 90 | // IsValidMetricName returns true iff name matches the pattern of MetricNameRE. 91 | // This function, however, does not use MetricNameRE for the check but a much 92 | // faster hardcoded implementation. 93 | func IsValidMetricName(n LabelValue) bool { 94 | if len(n) == 0 { 95 | return false 96 | } 97 | for i, b := range n { 98 | if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == ':' || (b >= '0' && b <= '9' && i > 0)) { 99 | return false 100 | } 101 | } 102 | return true 103 | } 104 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | "os/exec" 8 | "os/signal" 9 | "runtime" 10 | 11 | "github.com/jet/damon/container" 12 | "github.com/jet/damon/log" 13 | "github.com/jet/damon/metrics" 14 | "github.com/jet/damon/version" 15 | "github.com/jet/damon/win32" 16 | ) 17 | 18 | func main() { 19 | // Limit Damon to 1 CPU 20 | runtime.GOMAXPROCS(1) 21 | vinfo := version.GetInfo() 22 | 23 | if len(os.Args) < 2 { 24 | // print version and exit - no args 25 | fmt.Println(vinfo.FullString(true)) 26 | os.Exit(0) 27 | } 28 | 29 | var cmd *exec.Cmd 30 | if len(os.Args) > 2 { 31 | cmd = exec.Command(os.Args[1], os.Args[2:]...) 32 | } else { 33 | cmd = exec.Command(os.Args[1]) 34 | } 35 | 36 | lcfg := LogConfigFromEnvironment() 37 | fields := NomadLogFields() 38 | logger, err := log.NewLogger(lcfg) 39 | if err != nil { 40 | fmt.Println(err) 41 | os.Exit(1) 42 | } 43 | logger = logger.WithFields(fields) 44 | logger.WithFields(map[string]interface{}{ 45 | "version": vinfo, 46 | "revision": version.GitCommit, 47 | "cmdline": os.Args, 48 | }).Logln("damon starting") 49 | clogger := logger.WithFields(map[string]interface{}{ 50 | "version": vinfo.String(), 51 | "revision": version.GitCommit, 52 | "cmdline": os.Args, 53 | }) 54 | ccfg, err := LoadContainerConfigFromEnvironment() 55 | if err != nil { 56 | logger.Error(err, "unable to load container configuration from environment variables") 57 | } 58 | win32.SetLogger(logger) 59 | resources := win32.GetSystemResources() 60 | labels := make(map[string]string) 61 | for k, v := range fields { 62 | labels[k] = fmt.Sprintf("%v", v) 63 | } 64 | m := metrics.Metrics{ 65 | Cores: resources.CPUNumCores, 66 | MHzPerCore: resources.CPUMhzPercore, 67 | CPULimitHz: float64(ccfg.CPUMHzLimit * 1000000), 68 | MemoryLimitBytes: float64(ccfg.MemoryMBLimit * 1024 * 1024), 69 | Namespace: "damon", 70 | Labels: labels, 71 | } 72 | m.Init() 73 | c := container.Container{ 74 | Command: cmd, 75 | Config: ccfg, 76 | Logger: clogger, 77 | OnStats: func(s container.ProcessStats) { 78 | m.OnStats(s) 79 | }, 80 | OnViolation: func(v container.LimitViolation) { 81 | m.OnViolation(v) 82 | }, 83 | } 84 | if err := c.Start(); err != nil { 85 | logger.Error(err, "damon startup error") 86 | os.Exit(1) 87 | } 88 | exitCh := make(chan struct{}) 89 | sigCh := make(chan os.Signal) 90 | signal.Notify(sigCh) 91 | go func() { 92 | <-sigCh 93 | close(exitCh) 94 | }() 95 | if addr := ListenAddress(); addr != "" { 96 | go func() { 97 | endpoint := MetricsEndpoint() 98 | mux := http.NewServeMux() 99 | mux.Handle(endpoint, m.Handler()) 100 | srv := &http.Server{ 101 | Addr: addr, 102 | Handler: mux, 103 | } 104 | logger.Logf("metrics on http://%s/%s", addr, endpoint) 105 | logger.Error(srv.ListenAndServe(), "error closing http server") 106 | }() 107 | } 108 | pr, err := c.Wait(exitCh) 109 | if err != nil { 110 | logger.WithFields(map[string]interface{}{ 111 | "version": vinfo, 112 | "revision": version.GitCommit, 113 | "cmdline": os.Args, 114 | }).Error(err, "process exited with an error") 115 | } 116 | 117 | logger.WithFields(map[string]interface{}{ 118 | "version": vinfo, 119 | "revision": version.GitCommit, 120 | "cmdline": os.Args, 121 | "start": pr.Start, 122 | "end": pr.End, 123 | "run_time": pr.End.Sub(pr.Start), 124 | "exit_status": pr.ExitCode, 125 | }).Logln("damon exiting") 126 | os.Exit(pr.ExitCode) 127 | } 128 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/sampler.go: -------------------------------------------------------------------------------- 1 | package zerolog 2 | 3 | import ( 4 | "math/rand" 5 | "sync/atomic" 6 | "time" 7 | ) 8 | 9 | var ( 10 | // Often samples log every ~ 10 events. 11 | Often = RandomSampler(10) 12 | // Sometimes samples log every ~ 100 events. 13 | Sometimes = RandomSampler(100) 14 | // Rarely samples log every ~ 1000 events. 15 | Rarely = RandomSampler(1000) 16 | ) 17 | 18 | // Sampler defines an interface to a log sampler. 19 | type Sampler interface { 20 | // Sample returns true if the event should be part of the sample, false if 21 | // the event should be dropped. 22 | Sample(lvl Level) bool 23 | } 24 | 25 | // RandomSampler use a PRNG to randomly sample an event out of N events, 26 | // regardless of their level. 27 | type RandomSampler uint32 28 | 29 | // Sample implements the Sampler interface. 30 | func (s RandomSampler) Sample(lvl Level) bool { 31 | if s <= 0 { 32 | return false 33 | } 34 | if rand.Intn(int(s)) != 0 { 35 | return false 36 | } 37 | return true 38 | } 39 | 40 | // BasicSampler is a sampler that will send every Nth events, regardless of 41 | // there level. 42 | type BasicSampler struct { 43 | N uint32 44 | counter uint32 45 | } 46 | 47 | // Sample implements the Sampler interface. 48 | func (s *BasicSampler) Sample(lvl Level) bool { 49 | c := atomic.AddUint32(&s.counter, 1) 50 | return c%s.N == s.N-1 51 | } 52 | 53 | // BurstSampler lets Burst events pass per Period then pass the decision to 54 | // NextSampler. If Sampler is not set, all subsequent events are rejected. 55 | type BurstSampler struct { 56 | // Burst is the maximum number of event per period allowed before calling 57 | // NextSampler. 58 | Burst uint32 59 | // Period defines the burst period. If 0, NextSampler is always called. 60 | Period time.Duration 61 | // NextSampler is the sampler used after the burst is reached. If nil, 62 | // events are always rejected after the burst. 63 | NextSampler Sampler 64 | 65 | counter uint32 66 | resetAt int64 67 | } 68 | 69 | // Sample implements the Sampler interface. 70 | func (s *BurstSampler) Sample(lvl Level) bool { 71 | if s.Burst > 0 && s.Period > 0 { 72 | if s.inc() <= s.Burst { 73 | return true 74 | } 75 | } 76 | if s.NextSampler == nil { 77 | return false 78 | } 79 | return s.NextSampler.Sample(lvl) 80 | } 81 | 82 | func (s *BurstSampler) inc() uint32 { 83 | now := time.Now().UnixNano() 84 | resetAt := atomic.LoadInt64(&s.resetAt) 85 | var c uint32 86 | if now > resetAt { 87 | c = 1 88 | atomic.StoreUint32(&s.counter, c) 89 | newResetAt := now + s.Period.Nanoseconds() 90 | reset := atomic.CompareAndSwapInt64(&s.resetAt, resetAt, newResetAt) 91 | if !reset { 92 | // Lost the race with another goroutine trying to reset. 93 | c = atomic.AddUint32(&s.counter, 1) 94 | } 95 | } else { 96 | c = atomic.AddUint32(&s.counter, 1) 97 | } 98 | return c 99 | } 100 | 101 | // LevelSampler applies a different sampler for each level. 102 | type LevelSampler struct { 103 | DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler 104 | } 105 | 106 | func (s LevelSampler) Sample(lvl Level) bool { 107 | switch lvl { 108 | case DebugLevel: 109 | if s.DebugSampler != nil { 110 | return s.DebugSampler.Sample(lvl) 111 | } 112 | case InfoLevel: 113 | if s.InfoSampler != nil { 114 | return s.InfoSampler.Sample(lvl) 115 | } 116 | case WarnLevel: 117 | if s.WarnSampler != nil { 118 | return s.WarnSampler.Sample(lvl) 119 | } 120 | case ErrorLevel: 121 | if s.ErrorSampler != nil { 122 | return s.ErrorSampler.Sample(lvl) 123 | } 124 | } 125 | return true 126 | } 127 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/cbor/README.md: -------------------------------------------------------------------------------- 1 | ## Reference: 2 | CBOR Encoding is described in [RFC7049](https://tools.ietf.org/html/rfc7049) 3 | 4 | ## Comparison of JSON vs CBOR 5 | 6 | Two main areas of reduction are: 7 | 8 | 1. CPU usage to write a log msg 9 | 2. Size (in bytes) of log messages. 10 | 11 | 12 | CPU Usage savings are below: 13 | ``` 14 | name JSON time/op CBOR time/op delta 15 | Info-32 15.3ns ± 1% 11.7ns ± 3% -23.78% (p=0.000 n=9+10) 16 | ContextFields-32 16.2ns ± 2% 12.3ns ± 3% -23.97% (p=0.000 n=9+9) 17 | ContextAppend-32 6.70ns ± 0% 6.20ns ± 0% -7.44% (p=0.000 n=9+9) 18 | LogFields-32 66.4ns ± 0% 24.6ns ± 2% -62.89% (p=0.000 n=10+9) 19 | LogArrayObject-32 911ns ±11% 768ns ± 6% -15.64% (p=0.000 n=10+10) 20 | LogFieldType/Floats-32 70.3ns ± 2% 29.5ns ± 1% -57.98% (p=0.000 n=10+10) 21 | LogFieldType/Err-32 14.0ns ± 3% 12.1ns ± 8% -13.20% (p=0.000 n=8+10) 22 | LogFieldType/Dur-32 17.2ns ± 2% 13.1ns ± 1% -24.27% (p=0.000 n=10+9) 23 | LogFieldType/Object-32 54.3ns ±11% 52.3ns ± 7% ~ (p=0.239 n=10+10) 24 | LogFieldType/Ints-32 20.3ns ± 2% 15.1ns ± 2% -25.50% (p=0.000 n=9+10) 25 | LogFieldType/Interfaces-32 642ns ±11% 621ns ± 9% ~ (p=0.118 n=10+10) 26 | LogFieldType/Interface(Objects)-32 635ns ±13% 632ns ± 9% ~ (p=0.592 n=10+10) 27 | LogFieldType/Times-32 294ns ± 0% 27ns ± 1% -90.71% (p=0.000 n=10+9) 28 | LogFieldType/Durs-32 121ns ± 0% 33ns ± 2% -72.44% (p=0.000 n=9+9) 29 | LogFieldType/Interface(Object)-32 56.6ns ± 8% 52.3ns ± 8% -7.54% (p=0.007 n=10+10) 30 | LogFieldType/Errs-32 17.8ns ± 3% 16.1ns ± 2% -9.71% (p=0.000 n=10+9) 31 | LogFieldType/Time-32 40.5ns ± 1% 12.7ns ± 6% -68.66% (p=0.000 n=8+9) 32 | LogFieldType/Bool-32 12.0ns ± 5% 10.2ns ± 2% -15.18% (p=0.000 n=10+8) 33 | LogFieldType/Bools-32 17.2ns ± 2% 12.6ns ± 4% -26.63% (p=0.000 n=10+10) 34 | LogFieldType/Int-32 12.3ns ± 2% 11.2ns ± 4% -9.27% (p=0.000 n=9+10) 35 | LogFieldType/Float-32 16.7ns ± 1% 12.6ns ± 2% -24.42% (p=0.000 n=7+9) 36 | LogFieldType/Str-32 12.7ns ± 7% 11.3ns ± 7% -10.88% (p=0.000 n=10+9) 37 | LogFieldType/Strs-32 20.3ns ± 3% 18.2ns ± 3% -10.25% (p=0.000 n=9+10) 38 | LogFieldType/Interface-32 183ns ±12% 175ns ± 9% ~ (p=0.078 n=10+10) 39 | ``` 40 | 41 | Log message size savings is greatly dependent on the number and type of fields in the log message. 42 | Assuming this log message (with an Integer, timestamp and string, in addition to level). 43 | 44 | `{"level":"error","Fault":41650,"time":"2018-04-01T15:18:19-07:00","message":"Some Message"}` 45 | 46 | Two measurements were done for the log file sizes - one without any compression, second 47 | using [compress/zlib](https://golang.org/pkg/compress/zlib/). 48 | 49 | Results for 10,000 log messages: 50 | 51 | | Log Format | Plain File Size (in KB) | Compressed File Size (in KB) | 52 | | :--- | :---: | :---: | 53 | | JSON | 920 | 28 | 54 | | CBOR | 550 | 28 | 55 | 56 | The example used to calculate the above data is available in [Examples](examples). 57 | -------------------------------------------------------------------------------- /log/log_test.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path/filepath" 7 | "testing" 8 | ) 9 | 10 | func TestLogConfig(t *testing.T) { 11 | workingDir, err := os.Getwd() 12 | if err != nil { 13 | t.Fatalf("Getwd error: %v", err) 14 | } 15 | suffix := ".log" 16 | logName := "damon-static.log" 17 | taskName := "damon-task" 18 | damonDir := `c:\damon\logs` 19 | allocDir := `c:\nomad\alloc\c6f9c416-6d1b-4e76-94dc-724d1cd5134a\alloc` 20 | allocLogsDir := `c:\nomad\alloc\c6f9c416-6d1b-4e76-94dc-724d1cd5134a\alloc\logs` 21 | tests := []struct { 22 | cfg LogConfig 23 | expectedDir string 24 | expectedFile string 25 | }{ 26 | { 27 | cfg: LogConfig{}, 28 | expectedDir: workingDir, 29 | expectedFile: filepath.Join(workingDir, DefaultLogName), 30 | }, 31 | { 32 | cfg: LogConfig{LogDir: damonDir}, 33 | expectedDir: damonDir, 34 | expectedFile: filepath.Join(damonDir, DefaultLogName), 35 | }, 36 | { 37 | cfg: LogConfig{LogDir: damonDir, NomadAllocDir: allocDir}, 38 | expectedDir: damonDir, 39 | expectedFile: filepath.Join(damonDir, DefaultLogName), 40 | }, 41 | { 42 | cfg: LogConfig{NomadAllocDir: allocDir}, 43 | expectedDir: allocLogsDir, 44 | expectedFile: filepath.Join(allocLogsDir, DefaultLogName), 45 | }, 46 | { 47 | cfg: LogConfig{NomadAllocDir: allocDir, NomadTaskName: taskName}, 48 | expectedDir: allocLogsDir, 49 | expectedFile: filepath.Join(allocLogsDir, fmt.Sprintf("%s%s", taskName, DefaultDamonNomadLogSuffix)), 50 | }, 51 | { 52 | cfg: LogConfig{NomadAllocDir: allocDir, NomadTaskName: taskName, NomadLogSuffix: suffix}, 53 | expectedDir: allocLogsDir, 54 | expectedFile: filepath.Join(allocLogsDir, fmt.Sprintf("%s%s", taskName, suffix)), 55 | }, 56 | { 57 | cfg: LogConfig{LogName: logName}, 58 | expectedDir: workingDir, 59 | expectedFile: filepath.Join(workingDir, logName), 60 | }, 61 | { 62 | cfg: LogConfig{LogName: logName, LogDir: damonDir}, 63 | expectedDir: damonDir, 64 | expectedFile: filepath.Join(damonDir, logName), 65 | }, 66 | { 67 | cfg: LogConfig{LogName: logName, LogDir: damonDir, NomadAllocDir: allocDir}, 68 | expectedDir: damonDir, 69 | expectedFile: filepath.Join(damonDir, logName), 70 | }, 71 | { 72 | cfg: LogConfig{LogName: logName, NomadAllocDir: allocDir}, 73 | expectedDir: allocLogsDir, 74 | expectedFile: filepath.Join(allocLogsDir, logName), 75 | }, 76 | { 77 | cfg: LogConfig{LogName: logName, NomadAllocDir: allocDir, NomadTaskName: taskName}, 78 | expectedDir: allocLogsDir, 79 | expectedFile: filepath.Join(allocLogsDir, logName), 80 | }, 81 | { 82 | cfg: LogConfig{LogName: logName, NomadAllocDir: allocDir, NomadTaskName: taskName}, 83 | expectedDir: allocLogsDir, 84 | expectedFile: filepath.Join(allocLogsDir, logName), 85 | }, 86 | { 87 | cfg: LogConfig{LogName: logName, NomadAllocDir: allocDir, NomadTaskName: taskName, NomadLogSuffix: suffix}, 88 | expectedDir: allocLogsDir, 89 | expectedFile: filepath.Join(allocLogsDir, logName), 90 | }, 91 | } 92 | for i, test := range tests { 93 | t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { 94 | t.Logf("%#v", test.cfg) 95 | dir, err := test.cfg.Dir() 96 | if err != nil { 97 | t.Fatal(err) 98 | } 99 | path, err := test.cfg.Path() 100 | if err != nil { 101 | t.Fatal(err) 102 | } 103 | if dir != test.expectedDir { 104 | t.Errorf("directory: expected %s but got %s", test.expectedDir, dir) 105 | } 106 | if path != test.expectedFile { 107 | t.Errorf("path: expected %s but got %s", test.expectedFile, path) 108 | } 109 | }) 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/collector.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package prometheus 15 | 16 | // Collector is the interface implemented by anything that can be used by 17 | // Prometheus to collect metrics. A Collector has to be registered for 18 | // collection. See Registerer.Register. 19 | // 20 | // The stock metrics provided by this package (Gauge, Counter, Summary, 21 | // Histogram, Untyped) are also Collectors (which only ever collect one metric, 22 | // namely itself). An implementer of Collector may, however, collect multiple 23 | // metrics in a coordinated fashion and/or create metrics on the fly. Examples 24 | // for collectors already implemented in this library are the metric vectors 25 | // (i.e. collection of multiple instances of the same Metric but with different 26 | // label values) like GaugeVec or SummaryVec, and the ExpvarCollector. 27 | type Collector interface { 28 | // Describe sends the super-set of all possible descriptors of metrics 29 | // collected by this Collector to the provided channel and returns once 30 | // the last descriptor has been sent. The sent descriptors fulfill the 31 | // consistency and uniqueness requirements described in the Desc 32 | // documentation. (It is valid if one and the same Collector sends 33 | // duplicate descriptors. Those duplicates are simply ignored. However, 34 | // two different Collectors must not send duplicate descriptors.) This 35 | // method idempotently sends the same descriptors throughout the 36 | // lifetime of the Collector. If a Collector encounters an error while 37 | // executing this method, it must send an invalid descriptor (created 38 | // with NewInvalidDesc) to signal the error to the registry. 39 | Describe(chan<- *Desc) 40 | // Collect is called by the Prometheus registry when collecting 41 | // metrics. The implementation sends each collected metric via the 42 | // provided channel and returns once the last metric has been sent. The 43 | // descriptor of each sent metric is one of those returned by 44 | // Describe. Returned metrics that share the same descriptor must differ 45 | // in their variable label values. This method may be called 46 | // concurrently and must therefore be implemented in a concurrency safe 47 | // way. Blocking occurs at the expense of total performance of rendering 48 | // all registered metrics. Ideally, Collector implementations support 49 | // concurrent readers. 50 | Collect(chan<- Metric) 51 | } 52 | 53 | // selfCollector implements Collector for a single Metric so that the Metric 54 | // collects itself. Add it as an anonymous field to a struct that implements 55 | // Metric, and call init with the Metric itself as an argument. 56 | type selfCollector struct { 57 | self Metric 58 | } 59 | 60 | // init provides the selfCollector with a reference to the metric it is supposed 61 | // to collect. It is usually called within the factory function to create a 62 | // metric. See example. 63 | func (c *selfCollector) init(self Metric) { 64 | c.self = self 65 | } 66 | 67 | // Describe implements Collector. 68 | func (c *selfCollector) Describe(ch chan<- *Desc) { 69 | ch <- c.self.Desc() 70 | } 71 | 72 | // Collect implements Collector. 73 | func (c *selfCollector) Collect(ch chan<- Metric) { 74 | ch <- c.self 75 | } 76 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/console.go: -------------------------------------------------------------------------------- 1 | package zerolog 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "sort" 9 | "strconv" 10 | "strings" 11 | "sync" 12 | "time" 13 | ) 14 | 15 | const ( 16 | cReset = 0 17 | cBold = 1 18 | cRed = 31 19 | cGreen = 32 20 | cYellow = 33 21 | cBlue = 34 22 | cMagenta = 35 23 | cCyan = 36 24 | cGray = 37 25 | cDarkGray = 90 26 | ) 27 | 28 | var consoleBufPool = sync.Pool{ 29 | New: func() interface{} { 30 | return bytes.NewBuffer(make([]byte, 0, 100)) 31 | }, 32 | } 33 | 34 | // LevelWidth defines the desired character width of the log level column. 35 | // Default 0 does not trim or pad (variable width based level text, e.g. "INFO" or "ERROR") 36 | var LevelWidth = 0 37 | 38 | // ConsoleWriter reads a JSON object per write operation and output an 39 | // optionally colored human readable version on the Out writer. 40 | type ConsoleWriter struct { 41 | Out io.Writer 42 | NoColor bool 43 | } 44 | 45 | func (w ConsoleWriter) Write(p []byte) (n int, err error) { 46 | var event map[string]interface{} 47 | p = decodeIfBinaryToBytes(p) 48 | d := json.NewDecoder(bytes.NewReader(p)) 49 | d.UseNumber() 50 | err = d.Decode(&event) 51 | if err != nil { 52 | return 53 | } 54 | buf := consoleBufPool.Get().(*bytes.Buffer) 55 | defer consoleBufPool.Put(buf) 56 | lvlColor := cReset 57 | level := "????" 58 | if l, ok := event[LevelFieldName].(string); ok { 59 | if !w.NoColor { 60 | lvlColor = levelColor(l) 61 | } 62 | level = strings.ToUpper(l) 63 | if LevelWidth > 0 { 64 | if padding := LevelWidth - len(level); padding > 0 { 65 | level += strings.Repeat(" ", padding) 66 | } else { 67 | level = level[0:LevelWidth] 68 | } 69 | } 70 | } 71 | fmt.Fprintf(buf, "%s |%s| %s", 72 | colorize(formatTime(event[TimestampFieldName]), cDarkGray, !w.NoColor), 73 | colorize(level, lvlColor, !w.NoColor), 74 | colorize(event[MessageFieldName], cReset, !w.NoColor)) 75 | fields := make([]string, 0, len(event)) 76 | for field := range event { 77 | switch field { 78 | case LevelFieldName, TimestampFieldName, MessageFieldName: 79 | continue 80 | } 81 | fields = append(fields, field) 82 | } 83 | sort.Strings(fields) 84 | for _, field := range fields { 85 | fmt.Fprintf(buf, " %s=", colorize(field, cCyan, !w.NoColor)) 86 | switch value := event[field].(type) { 87 | case string: 88 | if needsQuote(value) { 89 | buf.WriteString(strconv.Quote(value)) 90 | } else { 91 | buf.WriteString(value) 92 | } 93 | case json.Number: 94 | fmt.Fprint(buf, value) 95 | default: 96 | b, err := json.Marshal(value) 97 | if err != nil { 98 | fmt.Fprintf(buf, "[error: %v]", err) 99 | } else { 100 | fmt.Fprint(buf, string(b)) 101 | } 102 | } 103 | } 104 | buf.WriteByte('\n') 105 | buf.WriteTo(w.Out) 106 | n = len(p) 107 | return 108 | } 109 | 110 | func formatTime(t interface{}) string { 111 | switch t := t.(type) { 112 | case string: 113 | return t 114 | case json.Number: 115 | u, _ := t.Int64() 116 | return time.Unix(u, 0).Format(time.RFC3339) 117 | } 118 | return "" 119 | } 120 | 121 | func colorize(s interface{}, color int, enabled bool) string { 122 | if !enabled { 123 | return fmt.Sprintf("%v", s) 124 | } 125 | return fmt.Sprintf("\x1b[%dm%v\x1b[0m", color, s) 126 | } 127 | 128 | func levelColor(level string) int { 129 | switch level { 130 | case "debug": 131 | return cMagenta 132 | case "info": 133 | return cGreen 134 | case "warn": 135 | return cYellow 136 | case "error", "fatal", "panic": 137 | return cRed 138 | default: 139 | return cReset 140 | } 141 | } 142 | 143 | func needsQuote(s string) bool { 144 | for i := range s { 145 | if s[i] < 0x20 || s[i] > 0x7e || s[i] == ' ' || s[i] == '\\' || s[i] == '"' { 146 | return true 147 | } 148 | } 149 | return false 150 | } 151 | -------------------------------------------------------------------------------- /vendor/github.com/rs/zerolog/internal/json/string.go: -------------------------------------------------------------------------------- 1 | package json 2 | 3 | import "unicode/utf8" 4 | 5 | const hex = "0123456789abcdef" 6 | 7 | var noEscapeTable = [256]bool{} 8 | 9 | func init() { 10 | for i := 0; i <= 0x7e; i++ { 11 | noEscapeTable[i] = i >= 0x20 && i != '\\' && i != '"' 12 | } 13 | } 14 | 15 | // AppendStrings encodes the input strings to json and 16 | // appends the encoded string list to the input byte slice. 17 | func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { 18 | if len(vals) == 0 { 19 | return append(dst, '[', ']') 20 | } 21 | dst = append(dst, '[') 22 | dst = e.AppendString(dst, vals[0]) 23 | if len(vals) > 1 { 24 | for _, val := range vals[1:] { 25 | dst = e.AppendString(append(dst, ','), val) 26 | } 27 | } 28 | dst = append(dst, ']') 29 | return dst 30 | } 31 | 32 | // AppendString encodes the input string to json and appends 33 | // the encoded string to the input byte slice. 34 | // 35 | // The operation loops though each byte in the string looking 36 | // for characters that need json or utf8 encoding. If the string 37 | // does not need encoding, then the string is appended in it's 38 | // entirety to the byte slice. 39 | // If we encounter a byte that does need encoding, switch up 40 | // the operation and perform a byte-by-byte read-encode-append. 41 | func (Encoder) AppendString(dst []byte, s string) []byte { 42 | // Start with a double quote. 43 | dst = append(dst, '"') 44 | // Loop through each character in the string. 45 | for i := 0; i < len(s); i++ { 46 | // Check if the character needs encoding. Control characters, slashes, 47 | // and the double quote need json encoding. Bytes above the ascii 48 | // boundary needs utf8 encoding. 49 | if !noEscapeTable[s[i]] { 50 | // We encountered a character that needs to be encoded. Switch 51 | // to complex version of the algorithm. 52 | dst = appendStringComplex(dst, s, i) 53 | return append(dst, '"') 54 | } 55 | } 56 | // The string has no need for encoding an therefore is directly 57 | // appended to the byte slice. 58 | dst = append(dst, s...) 59 | // End with a double quote 60 | return append(dst, '"') 61 | } 62 | 63 | // appendStringComplex is used by appendString to take over an in 64 | // progress JSON string encoding that encountered a character that needs 65 | // to be encoded. 66 | func appendStringComplex(dst []byte, s string, i int) []byte { 67 | start := 0 68 | for i < len(s) { 69 | b := s[i] 70 | if b >= utf8.RuneSelf { 71 | r, size := utf8.DecodeRuneInString(s[i:]) 72 | if r == utf8.RuneError && size == 1 { 73 | // In case of error, first append previous simple characters to 74 | // the byte slice if any and append a remplacement character code 75 | // in place of the invalid sequence. 76 | if start < i { 77 | dst = append(dst, s[start:i]...) 78 | } 79 | dst = append(dst, `\ufffd`...) 80 | i += size 81 | start = i 82 | continue 83 | } 84 | i += size 85 | continue 86 | } 87 | if noEscapeTable[b] { 88 | i++ 89 | continue 90 | } 91 | // We encountered a character that needs to be encoded. 92 | // Let's append the previous simple characters to the byte slice 93 | // and switch our operation to read and encode the remainder 94 | // characters byte-by-byte. 95 | if start < i { 96 | dst = append(dst, s[start:i]...) 97 | } 98 | switch b { 99 | case '"', '\\': 100 | dst = append(dst, '\\', b) 101 | case '\b': 102 | dst = append(dst, '\\', 'b') 103 | case '\f': 104 | dst = append(dst, '\\', 'f') 105 | case '\n': 106 | dst = append(dst, '\\', 'n') 107 | case '\r': 108 | dst = append(dst, '\\', 'r') 109 | case '\t': 110 | dst = append(dst, '\\', 't') 111 | default: 112 | dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) 113 | } 114 | i++ 115 | start = i 116 | } 117 | if start < len(s) { 118 | dst = append(dst, s[start:]...) 119 | } 120 | return dst 121 | } 122 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/common/model/alert.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package model 15 | 16 | import ( 17 | "fmt" 18 | "time" 19 | ) 20 | 21 | type AlertStatus string 22 | 23 | const ( 24 | AlertFiring AlertStatus = "firing" 25 | AlertResolved AlertStatus = "resolved" 26 | ) 27 | 28 | // Alert is a generic representation of an alert in the Prometheus eco-system. 29 | type Alert struct { 30 | // Label value pairs for purpose of aggregation, matching, and disposition 31 | // dispatching. This must minimally include an "alertname" label. 32 | Labels LabelSet `json:"labels"` 33 | 34 | // Extra key/value information which does not define alert identity. 35 | Annotations LabelSet `json:"annotations"` 36 | 37 | // The known time range for this alert. Both ends are optional. 38 | StartsAt time.Time `json:"startsAt,omitempty"` 39 | EndsAt time.Time `json:"endsAt,omitempty"` 40 | GeneratorURL string `json:"generatorURL"` 41 | } 42 | 43 | // Name returns the name of the alert. It is equivalent to the "alertname" label. 44 | func (a *Alert) Name() string { 45 | return string(a.Labels[AlertNameLabel]) 46 | } 47 | 48 | // Fingerprint returns a unique hash for the alert. It is equivalent to 49 | // the fingerprint of the alert's label set. 50 | func (a *Alert) Fingerprint() Fingerprint { 51 | return a.Labels.Fingerprint() 52 | } 53 | 54 | func (a *Alert) String() string { 55 | s := fmt.Sprintf("%s[%s]", a.Name(), a.Fingerprint().String()[:7]) 56 | if a.Resolved() { 57 | return s + "[resolved]" 58 | } 59 | return s + "[active]" 60 | } 61 | 62 | // Resolved returns true iff the activity interval ended in the past. 63 | func (a *Alert) Resolved() bool { 64 | return a.ResolvedAt(time.Now()) 65 | } 66 | 67 | // ResolvedAt returns true off the activity interval ended before 68 | // the given timestamp. 69 | func (a *Alert) ResolvedAt(ts time.Time) bool { 70 | if a.EndsAt.IsZero() { 71 | return false 72 | } 73 | return !a.EndsAt.After(ts) 74 | } 75 | 76 | // Status returns the status of the alert. 77 | func (a *Alert) Status() AlertStatus { 78 | if a.Resolved() { 79 | return AlertResolved 80 | } 81 | return AlertFiring 82 | } 83 | 84 | // Validate checks whether the alert data is inconsistent. 85 | func (a *Alert) Validate() error { 86 | if a.StartsAt.IsZero() { 87 | return fmt.Errorf("start time missing") 88 | } 89 | if !a.EndsAt.IsZero() && a.EndsAt.Before(a.StartsAt) { 90 | return fmt.Errorf("start time must be before end time") 91 | } 92 | if err := a.Labels.Validate(); err != nil { 93 | return fmt.Errorf("invalid label set: %s", err) 94 | } 95 | if len(a.Labels) == 0 { 96 | return fmt.Errorf("at least one label pair required") 97 | } 98 | if err := a.Annotations.Validate(); err != nil { 99 | return fmt.Errorf("invalid annotations: %s", err) 100 | } 101 | return nil 102 | } 103 | 104 | // Alert is a list of alerts that can be sorted in chronological order. 105 | type Alerts []*Alert 106 | 107 | func (as Alerts) Len() int { return len(as) } 108 | func (as Alerts) Swap(i, j int) { as[i], as[j] = as[j], as[i] } 109 | 110 | func (as Alerts) Less(i, j int) bool { 111 | if as[i].StartsAt.Before(as[j].StartsAt) { 112 | return true 113 | } 114 | if as[i].EndsAt.Before(as[j].EndsAt) { 115 | return true 116 | } 117 | return as[i].Fingerprint() < as[j].Fingerprint() 118 | } 119 | 120 | // HasFiring returns true iff one of the alerts is not resolved. 121 | func (as Alerts) HasFiring() bool { 122 | for _, a := range as { 123 | if !a.Resolved() { 124 | return true 125 | } 126 | } 127 | return false 128 | } 129 | 130 | // Status returns StatusFiring iff at least one of the alerts is firing. 131 | func (as Alerts) Status() AlertStatus { 132 | if as.HasFiring() { 133 | return AlertFiring 134 | } 135 | return AlertResolved 136 | } 137 | -------------------------------------------------------------------------------- /win32/base_types_win32.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package win32 4 | 5 | import ( 6 | "io" 7 | "syscall" 8 | 9 | "golang.org/x/sys/windows" 10 | ) 11 | 12 | var ( 13 | kernel32DLL = windows.NewLazySystemDLL("kernel32.dll") 14 | advapi32DLL = windows.NewLazySystemDLL("advapi32.dll") 15 | userenvDLL = windows.NewLazySystemDLL("userenv.dll") 16 | psapiDLL = windows.NewLazySystemDLL("psapi.dll") 17 | iphlpapiDLL = windows.NewLazySystemDLL("iphlpapi.dll") 18 | ) 19 | 20 | // Types Reference: https://docs.microsoft.com/en-us/windows/desktop/WinProg/windows-data-types 21 | type ( 22 | BOOL uint32 23 | BOOLEAN byte 24 | BYTE byte 25 | DWORD uint32 26 | DWORD64 uint64 27 | HANDLE uintptr 28 | HLOCAL uintptr 29 | LARGE_INTEGER int64 30 | LONG int32 31 | LPVOID uintptr 32 | SIZE_T uintptr 33 | UINT uint32 34 | ULONG_PTR uintptr 35 | ULONGLONG uint64 36 | WORD uint16 37 | ) 38 | 39 | const ( 40 | NULL uintptr = 0 41 | 42 | ANY_SIZE int = 1 43 | 44 | // Error Codes 45 | NO_ERROR uintptr = 0 46 | ERROR_SUCCESS uintptr = 0 47 | ERROR_MORE_DATA uintptr = 0xea // 234 48 | ERROR_MR_MID_NOT_FOUND uintptr = 317 49 | 50 | // Booleans 51 | FALSE BOOL = 0 52 | TRUE BOOL = 1 53 | 54 | // Constants 55 | DWORD_MAX = DWORD(0xFFFFFFFF) 56 | ) 57 | 58 | // https://docs.microsoft.com/en-us/windows/desktop/SecAuthZ/access-mask-format 59 | const ( 60 | // Generic Access Rights 61 | // https://docs.microsoft.com/en-us/windows/desktop/SecAuthZ/generic-access-rights 62 | 63 | _GENERIC_READ uint32 = 0x80000000 64 | _GENERIC_WRITE uint32 = 0x40000000 65 | _GENERIC_EXECUTE uint32 = 0x20000000 66 | _GENERIC_ALL uint32 = 0x10000000 67 | 68 | _ACCESS_SYSTEM_SECURITY uint32 = 0x01000000 69 | _MAXIMUM_ALLOWED uint32 = 0x02000000 70 | 71 | // Standard Access Rights 72 | // https://docs.microsoft.com/en-us/windows/desktop/SecAuthZ/standard-access-rights 73 | 74 | _DELETE uint32 = 0x00010000 75 | _READ_CONTROL uint32 = 0x00020000 76 | _WRITE_DAC uint32 = 0x00040000 77 | _WRITE_OWNER uint32 = 0x00080000 78 | _SYNCHRONIZE uint32 = 0x00100000 79 | _STANDARD_RIGHTS_REQUIRED = _DELETE | _READ_CONTROL | _WRITE_DAC | _WRITE_OWNER 80 | _STANDARD_RIGHTS_EXECUTE = _READ_CONTROL 81 | _STANDARD_RIGHTS_READ = _READ_CONTROL 82 | _STANDARD_RIGHTS_WRITE = _READ_CONTROL 83 | _STANDARD_RIGHTS_ALL = _DELETE | _READ_CONTROL | _WRITE_DAC | _WRITE_OWNER | _SYNCHRONIZE 84 | 85 | // Object-specific Access Rights mask 86 | 87 | _SPECIFIC_RIGHTS_ALL uint32 = 0x0000ffff 88 | ) 89 | 90 | func toBOOL(b bool) BOOL { 91 | if b { 92 | return TRUE 93 | } 94 | return FALSE 95 | } 96 | 97 | func (b BOOL) boolean() bool { 98 | if b == TRUE { 99 | return true 100 | } 101 | return false 102 | } 103 | 104 | // testReturnCodeNonZero is a syscall helper function for testing the return code 105 | // for functions that return a handle + error where a zero value is failure 106 | // 107 | // Example: 108 | // 109 | // r1, _, errno := procVar.Call(uintptr(x),uintptr(y)) 110 | // if err := testReturnCodeNonZero(r1, errno); err != nil { 111 | // return nil, err 112 | // } 113 | // // r1 is valid here 114 | func testReturnCodeNonZero(r1 uintptr, err error) error { 115 | if r1 == 0 { 116 | return errnoToError(err) 117 | } 118 | return nil 119 | } 120 | 121 | // testReturnCodeTrue is a syscall helper function for testing the return code 122 | // for functions that return a handle + error where the return code is a BOOL 123 | // where TRUE is success 124 | // 125 | // Example: 126 | // 127 | // r1, _, errno := procVar.Call(uintptr(x),uintptr(y)) 128 | // if err := testReturnCodeTrue(r1, errno); err != nil { 129 | // return nil, err 130 | // } 131 | // // r1 is valid here 132 | func testReturnCodeTrue(r1 uintptr, err error) error { 133 | if !BOOL(r1).boolean() { 134 | return errnoToError(err) 135 | } 136 | return nil 137 | } 138 | 139 | func errnoToError(err error) error { 140 | if errno, ok := err.(syscall.Errno); ok { 141 | if errno != 0 { 142 | return errno 143 | } 144 | return syscall.EINVAL 145 | } 146 | return err 147 | } 148 | 149 | func CloseLogErr(c io.Closer, errMsg string) { 150 | LogError(c.Close(), errMsg) 151 | } 152 | 153 | func CloseHandleLogErr(h syscall.Handle, errMsg string) { 154 | LogError(syscall.CloseHandle(h), errMsg) 155 | } 156 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package prometheus 15 | 16 | import ( 17 | "encoding/json" 18 | "expvar" 19 | ) 20 | 21 | type expvarCollector struct { 22 | exports map[string]*Desc 23 | } 24 | 25 | // NewExpvarCollector returns a newly allocated expvar Collector that still has 26 | // to be registered with a Prometheus registry. 27 | // 28 | // An expvar Collector collects metrics from the expvar interface. It provides a 29 | // quick way to expose numeric values that are already exported via expvar as 30 | // Prometheus metrics. Note that the data models of expvar and Prometheus are 31 | // fundamentally different, and that the expvar Collector is inherently slower 32 | // than native Prometheus metrics. Thus, the expvar Collector is probably great 33 | // for experiments and prototying, but you should seriously consider a more 34 | // direct implementation of Prometheus metrics for monitoring production 35 | // systems. 36 | // 37 | // The exports map has the following meaning: 38 | // 39 | // The keys in the map correspond to expvar keys, i.e. for every expvar key you 40 | // want to export as Prometheus metric, you need an entry in the exports 41 | // map. The descriptor mapped to each key describes how to export the expvar 42 | // value. It defines the name and the help string of the Prometheus metric 43 | // proxying the expvar value. The type will always be Untyped. 44 | // 45 | // For descriptors without variable labels, the expvar value must be a number or 46 | // a bool. The number is then directly exported as the Prometheus sample 47 | // value. (For a bool, 'false' translates to 0 and 'true' to 1). Expvar values 48 | // that are not numbers or bools are silently ignored. 49 | // 50 | // If the descriptor has one variable label, the expvar value must be an expvar 51 | // map. The keys in the expvar map become the various values of the one 52 | // Prometheus label. The values in the expvar map must be numbers or bools again 53 | // as above. 54 | // 55 | // For descriptors with more than one variable label, the expvar must be a 56 | // nested expvar map, i.e. where the values of the topmost map are maps again 57 | // etc. until a depth is reached that corresponds to the number of labels. The 58 | // leaves of that structure must be numbers or bools as above to serve as the 59 | // sample values. 60 | // 61 | // Anything that does not fit into the scheme above is silently ignored. 62 | func NewExpvarCollector(exports map[string]*Desc) Collector { 63 | return &expvarCollector{ 64 | exports: exports, 65 | } 66 | } 67 | 68 | // Describe implements Collector. 69 | func (e *expvarCollector) Describe(ch chan<- *Desc) { 70 | for _, desc := range e.exports { 71 | ch <- desc 72 | } 73 | } 74 | 75 | // Collect implements Collector. 76 | func (e *expvarCollector) Collect(ch chan<- Metric) { 77 | for name, desc := range e.exports { 78 | var m Metric 79 | expVar := expvar.Get(name) 80 | if expVar == nil { 81 | continue 82 | } 83 | var v interface{} 84 | labels := make([]string, len(desc.variableLabels)) 85 | if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil { 86 | ch <- NewInvalidMetric(desc, err) 87 | continue 88 | } 89 | var processValue func(v interface{}, i int) 90 | processValue = func(v interface{}, i int) { 91 | if i >= len(labels) { 92 | copiedLabels := append(make([]string, 0, len(labels)), labels...) 93 | switch v := v.(type) { 94 | case float64: 95 | m = MustNewConstMetric(desc, UntypedValue, v, copiedLabels...) 96 | case bool: 97 | if v { 98 | m = MustNewConstMetric(desc, UntypedValue, 1, copiedLabels...) 99 | } else { 100 | m = MustNewConstMetric(desc, UntypedValue, 0, copiedLabels...) 101 | } 102 | default: 103 | return 104 | } 105 | ch <- m 106 | return 107 | } 108 | vm, ok := v.(map[string]interface{}) 109 | if !ok { 110 | return 111 | } 112 | for lv, val := range vm { 113 | labels[i] = lv 114 | processValue(val, i+1) 115 | } 116 | } 117 | processValue(v, 0) 118 | } 119 | } 120 | --------------------------------------------------------------------------------