├── .gitignore ├── .promu.yml ├── .travis.yml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── VERSION ├── azure-example.yml ├── azure.go ├── config └── config.go ├── go.mod ├── go.sum ├── main.go ├── utils.go ├── utils_test.go └── vendor ├── github.com ├── alecthomas │ ├── template │ │ ├── LICENSE │ │ ├── README.md │ │ ├── doc.go │ │ ├── exec.go │ │ ├── funcs.go │ │ ├── go.mod │ │ ├── helper.go │ │ ├── parse │ │ │ ├── lex.go │ │ │ ├── node.go │ │ │ └── parse.go │ │ └── template.go │ └── units │ │ ├── COPYING │ │ ├── README.md │ │ ├── bytes.go │ │ ├── doc.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── si.go │ │ └── util.go ├── beorn7 │ └── perks │ │ ├── LICENSE │ │ └── quantile │ │ ├── exampledata.txt │ │ └── stream.go ├── golang │ └── protobuf │ │ ├── AUTHORS │ │ ├── CONTRIBUTORS │ │ ├── LICENSE │ │ └── proto │ │ ├── clone.go │ │ ├── decode.go │ │ ├── deprecated.go │ │ ├── discard.go │ │ ├── encode.go │ │ ├── equal.go │ │ ├── extensions.go │ │ ├── lib.go │ │ ├── message_set.go │ │ ├── pointer_reflect.go │ │ ├── pointer_unsafe.go │ │ ├── properties.go │ │ ├── table_marshal.go │ │ ├── table_merge.go │ │ ├── table_unmarshal.go │ │ ├── text.go │ │ └── text_parser.go ├── matttproud │ └── golang_protobuf_extensions │ │ ├── LICENSE │ │ ├── NOTICE │ │ └── pbutil │ │ ├── .gitignore │ │ ├── Makefile │ │ ├── decode.go │ │ ├── doc.go │ │ └── encode.go └── prometheus │ ├── client_golang │ ├── LICENSE │ ├── NOTICE │ └── prometheus │ │ ├── .gitignore │ │ ├── README.md │ │ ├── build_info.go │ │ ├── build_info_pre_1.12.go │ │ ├── collector.go │ │ ├── counter.go │ │ ├── desc.go │ │ ├── doc.go │ │ ├── expvar_collector.go │ │ ├── fnv.go │ │ ├── gauge.go │ │ ├── go_collector.go │ │ ├── histogram.go │ │ ├── internal │ │ └── metric.go │ │ ├── labels.go │ │ ├── metric.go │ │ ├── observer.go │ │ ├── process_collector.go │ │ ├── process_collector_other.go │ │ ├── process_collector_windows.go │ │ ├── promhttp │ │ ├── delegator.go │ │ ├── http.go │ │ ├── instrument_client.go │ │ └── instrument_server.go │ │ ├── registry.go │ │ ├── summary.go │ │ ├── timer.go │ │ ├── untyped.go │ │ ├── value.go │ │ ├── vec.go │ │ └── wrap.go │ ├── client_model │ ├── LICENSE │ ├── NOTICE │ └── go │ │ └── metrics.pb.go │ ├── common │ ├── LICENSE │ ├── NOTICE │ ├── expfmt │ │ ├── decode.go │ │ ├── encode.go │ │ ├── expfmt.go │ │ ├── fuzz.go │ │ ├── text_create.go │ │ └── text_parse.go │ ├── internal │ │ └── bitbucket.org │ │ │ └── ww │ │ │ └── goautoneg │ │ │ ├── README.txt │ │ │ └── autoneg.go │ ├── model │ │ ├── alert.go │ │ ├── fingerprinting.go │ │ ├── fnv.go │ │ ├── labels.go │ │ ├── labelset.go │ │ ├── metric.go │ │ ├── model.go │ │ ├── signature.go │ │ ├── silence.go │ │ ├── time.go │ │ └── value.go │ └── version │ │ └── info.go │ └── procfs │ ├── .gitignore │ ├── .golangci.yml │ ├── CONTRIBUTING.md │ ├── LICENSE │ ├── MAINTAINERS.md │ ├── Makefile │ ├── Makefile.common │ ├── NOTICE │ ├── README.md │ ├── arp.go │ ├── buddyinfo.go │ ├── cpuinfo.go │ ├── crypto.go │ ├── doc.go │ ├── fixtures.ttar │ ├── fs.go │ ├── go.mod │ ├── go.sum │ ├── internal │ ├── fs │ │ └── fs.go │ └── util │ │ ├── parse.go │ │ ├── sysreadfile.go │ │ ├── sysreadfile_compat.go │ │ └── valueparser.go │ ├── ipvs.go │ ├── mdstat.go │ ├── mountinfo.go │ ├── mountstats.go │ ├── net_dev.go │ ├── net_softnet.go │ ├── net_unix.go │ ├── proc.go │ ├── proc_environ.go │ ├── proc_fdinfo.go │ ├── proc_io.go │ ├── proc_limits.go │ ├── proc_ns.go │ ├── proc_psi.go │ ├── proc_stat.go │ ├── proc_status.go │ ├── schedstat.go │ ├── stat.go │ ├── ttar │ ├── vm.go │ ├── xfrm.go │ └── zoneinfo.go ├── golang.org └── x │ └── sys │ ├── AUTHORS │ ├── CONTRIBUTORS │ ├── LICENSE │ ├── PATENTS │ └── windows │ ├── aliases.go │ ├── asm_windows_386.s │ ├── asm_windows_amd64.s │ ├── asm_windows_arm.s │ ├── dll_windows.go │ ├── env_windows.go │ ├── eventlog.go │ ├── exec_windows.go │ ├── memory_windows.go │ ├── mkerrors.bash │ ├── mkknownfolderids.bash │ ├── mksyscall.go │ ├── race.go │ ├── race0.go │ ├── security_windows.go │ ├── service.go │ ├── str.go │ ├── syscall.go │ ├── syscall_windows.go │ ├── types_windows.go │ ├── types_windows_386.go │ ├── types_windows_amd64.go │ ├── types_windows_arm.go │ ├── zerrors_windows.go │ ├── zknownfolderids_windows.go │ └── zsyscall_windows.go ├── gopkg.in ├── alecthomas │ └── kingpin.v2 │ │ ├── .travis.yml │ │ ├── COPYING │ │ ├── README.md │ │ ├── actions.go │ │ ├── app.go │ │ ├── args.go │ │ ├── cmd.go │ │ ├── completions.go │ │ ├── doc.go │ │ ├── envar.go │ │ ├── flags.go │ │ ├── global.go │ │ ├── guesswidth.go │ │ ├── guesswidth_unix.go │ │ ├── model.go │ │ ├── parser.go │ │ ├── parsers.go │ │ ├── templates.go │ │ ├── usage.go │ │ ├── values.go │ │ ├── values.json │ │ └── values_generated.go └── yaml.v2 │ ├── .travis.yml │ ├── LICENSE │ ├── LICENSE.libyaml │ ├── NOTICE │ ├── README.md │ ├── apic.go │ ├── decode.go │ ├── emitterc.go │ ├── encode.go │ ├── go.mod │ ├── parserc.go │ ├── readerc.go │ ├── resolve.go │ ├── scannerc.go │ ├── sorter.go │ ├── writerc.go │ ├── yaml.go │ ├── yamlh.go │ └── yamlprivateh.go └── modules.txt /.gitignore: -------------------------------------------------------------------------------- 1 | /bin 2 | *.DS_Store 3 | azure_metrics_exporter 4 | azure.yml 5 | notes.txt 6 | -------------------------------------------------------------------------------- /.promu.yml: -------------------------------------------------------------------------------- 1 | go: 2 | cgo: false 3 | repository: 4 | path: github.com/RobustPerception/azure_metrics_exporter 5 | build: 6 | binaries: 7 | - name: azure_metrics_exporter 8 | flags: -a -tags netgo 9 | ldflags: | 10 | -X {{repoPath}}/vendor/github.com/prometheus/common/version.Version={{.Version}} 11 | -X {{repoPath}}/vendor/github.com/prometheus/common/version.Revision={{.Revision}} 12 | -X {{repoPath}}/vendor/github.com/prometheus/common/version.Branch={{.Branch}} 13 | -X {{repoPath}}/vendor/github.com/prometheus/common/version.BuildUser={{user}}@{{host}} 14 | -X {{repoPath}}/vendor/github.com/prometheus/common/version.BuildDate={{date "20060102-15:04:05"}} 15 | tarball: 16 | files: 17 | - README.md 18 | crossbuild: 19 | platforms: 20 | - linux/amd64 21 | - linux/386 22 | - linux/arm 23 | - linux/arm64 24 | - darwin/amd64 25 | - darwin/386 26 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: go 3 | go_import_path: github.com/RobustPerception/azure_metrics_exporter 4 | 5 | install: true 6 | 7 | script: 8 | - make 9 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.11 as builder 2 | WORKDIR /go/src/github.com/RobustPerception/azure_metrics_exporter 3 | COPY . . 4 | RUN make build 5 | 6 | FROM quay.io/prometheus/busybox:latest AS app 7 | 8 | COPY --from=builder /go/src/github.com/RobustPerception/azure_metrics_exporter/azure_metrics_exporter /bin/azure_metrics_exporter 9 | 10 | EXPOSE 9276 11 | ENTRYPOINT ["/bin/azure_metrics_exporter"] 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 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 | GO := GO15VENDOREXPERIMENT=1 go 15 | PROMU := $(GOPATH)/bin/promu 16 | pkgs = $(shell $(GO) list ./... | grep -v /vendor/) 17 | 18 | PREFIX ?= $(shell pwd) 19 | BIN_DIR ?= $(shell pwd) 20 | DOCKER_REPO ?= robustperception 21 | DOCKER_IMAGE_NAME ?= azure_metrics_exporter 22 | DOCKER_IMAGE_TAG ?= $(subst /,-,$(shell git rev-parse --abbrev-ref HEAD)) 23 | 24 | all: format build test 25 | 26 | test: build 27 | @echo ">> running tests" 28 | @$(GO) test -short $(pkgs) 29 | 30 | style: 31 | @echo ">> checking code style" 32 | @! gofmt -d $(shell find . -path ./vendor -prune -o -name '*.go' -print) | grep '^' 33 | 34 | format: 35 | @echo ">> formatting code" 36 | @$(GO) fmt $(pkgs) 37 | 38 | vet: 39 | @echo ">> vetting code" 40 | @$(GO) vet $(pkgs) 41 | 42 | build: promu 43 | @echo ">> building binaries" 44 | @$(PROMU) build --prefix $(PREFIX) 45 | 46 | tarball: promu 47 | @echo ">> building release tarball" 48 | @$(PROMU) tarball --prefix $(PREFIX) $(BIN_DIR) 49 | 50 | docker: 51 | @echo ">> building docker image" 52 | @docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):$(DOCKER_IMAGE_TAG)" . 53 | 54 | promu: 55 | @GOOS=$(shell uname -s | tr A-Z a-z) \ 56 | GOARCH=$(subst x86_64,amd64,$(patsubst i%86,386,$(shell uname -m))) \ 57 | $(GO) get -u github.com/prometheus/promu 58 | 59 | .PHONY: all style format build test vet tarball docker promu -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.1.0-pre0 2 | -------------------------------------------------------------------------------- /azure-example.yml: -------------------------------------------------------------------------------- 1 | --- 2 | active_directory_authority_url: "https://login.microsoftonline.com/" 3 | resource_manager_url: "https://management.azure.com/" 4 | credentials: 5 | subscription_id: 6 | client_id: 7 | client_secret: 8 | tenant_id: 9 | 10 | targets: 11 | - resource: "/resourceGroups/blog-group/providers/Microsoft.Web/sites/blog" 12 | metrics: 13 | - name: "BytesReceived" 14 | - name: "BytesSent" 15 | - resource: "/resourceGroups/app-group/providers/Microsoft.Web/sites/app" 16 | metrics: 17 | - name: "Http2xx" 18 | - name: "Http5xx" 19 | - resource: "/resourceGroups/vm-group/providers/Microsoft.Compute/virtualMachines/vm" 20 | metric_namespace: "Azure.VM.Windows.GuestMetrics" 21 | metrics: 22 | - name: 'Process\Thread Count' 23 | 24 | resource_groups: 25 | - resource_group: "webapps" 26 | resource_types: 27 | - "Microsoft.Compute/virtualMachines" 28 | resource_name_include_re: 29 | - "testvm.*" 30 | resource_name_exclude_re: 31 | - "testvm12" 32 | metrics: 33 | - name: "CPU Credits Consumed" 34 | 35 | resource_tags: 36 | - resource_tag_name: "monitoring" 37 | resource_tag_value: "enabled" 38 | resource_types: 39 | - "Microsoft.Compute/virtualMachines" 40 | metrics: 41 | - name: "CPU Credits consumed" 42 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/RobustPerception/azure_metrics_exporter 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/alecthomas/units v0.0.0-20190910110746-680d30ca3117 // indirect 7 | github.com/golang/protobuf v1.3.3-0.20190827175835-822fe56949f5 // indirect 8 | github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect 9 | github.com/prometheus/client_golang v1.1.1-0.20190913103102-20428fa0bffc 10 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 // indirect 11 | github.com/prometheus/common v0.7.0 12 | github.com/prometheus/procfs v0.0.6-0.20190917143953-de25ac347ef9 // indirect 13 | golang.org/x/sys v0.0.0-20190919044723-0c1ff786ef13 // indirect 14 | gopkg.in/alecthomas/kingpin.v2 v2.2.6 15 | gopkg.in/yaml.v2 v2.2.2 16 | ) 17 | -------------------------------------------------------------------------------- /utils.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "log" 7 | "reflect" 8 | "regexp" 9 | "strings" 10 | "time" 11 | ) 12 | 13 | var ( 14 | // resource component positions in a ResourceURL 15 | resourceGroupPosition = 4 16 | resourceNamePosition = 8 17 | subResourceNamePosition = 10 18 | resourceTypeSuffixPosition = 9 19 | resourceTypePosition = 7 20 | resourceTypePrefixPosition = 6 21 | invalidLabelChars = regexp.MustCompile(`[^a-zA-Z0-9_]+`) 22 | ) 23 | 24 | // PrintPrettyJSON - Prints structs nicely for debugging. 25 | func PrintPrettyJSON(input map[string]interface{}) { 26 | out, err := json.MarshalIndent(input, "", "\t") 27 | if err != nil { 28 | log.Fatalf("Error indenting JSON: %v", err) 29 | } 30 | fmt.Println(string(out)) 31 | } 32 | 33 | // GetTimes - Returns the endTime and startTime used for querying Azure Metrics API 34 | func GetTimes() (string, string) { 35 | // Make sure we are using UTC 36 | now := time.Now().UTC() 37 | 38 | // Use query delay of 3 minutes when querying for latest metric data 39 | endTime := now.Add(time.Minute * time.Duration(-3)).Format(time.RFC3339) 40 | startTime := now.Add(time.Minute * time.Duration(-4)).Format(time.RFC3339) 41 | return endTime, startTime 42 | } 43 | 44 | // CreateResourceLabels - Returns resource labels for a given resource URL. 45 | func CreateResourceLabels(resourceURL string) map[string]string { 46 | labels := make(map[string]string) 47 | resource := strings.Split(resourceURL, "/") 48 | 49 | labels["resource_group"] = resource[resourceGroupPosition] 50 | labels["resource_name"] = resource[resourceNamePosition] 51 | if len(resource) > 13 { 52 | labels["sub_resource_name"] = resource[subResourceNamePosition] 53 | } 54 | return labels 55 | } 56 | 57 | // GetResourceType returns the resource type with the namespace 58 | func GetResourceType(resourceURL string) string { 59 | resource := strings.Split(resourceURL, "/") 60 | var str strings.Builder 61 | str.WriteString(resource[resourceTypePrefixPosition]) 62 | str.WriteString("/") 63 | str.WriteString(resource[resourceTypePosition]) 64 | if len(resource) > 13 { 65 | str.WriteString("/") 66 | str.WriteString(resource[resourceTypeSuffixPosition]) 67 | } 68 | return str.String() 69 | } 70 | 71 | func CreateAllResourceLabelsFrom(rm resourceMeta) map[string]string { 72 | formatTag := "pretty" 73 | labels := make(map[string]string) 74 | 75 | for k, v := range rm.resource.Tags { 76 | k = strings.ToLower(k) 77 | k = "tag_" + k 78 | k = invalidLabelChars.ReplaceAllString(k, "_") 79 | labels[k] = v 80 | } 81 | 82 | // create a label for each field of the resource 83 | val := reflect.ValueOf(rm.resource) 84 | for i := 0; i < val.NumField(); i++ { 85 | field := val.Field(i) 86 | tag := reflect.TypeOf(rm.resource).Field(i).Tag.Get(formatTag) 87 | if field.Kind() == reflect.String { 88 | labels[tag] = field.String() 89 | } 90 | } 91 | 92 | // Most labels are handled by iterating over the fields of resourceMeta.AzureResource. 93 | // Their tag values are used as label keys. 94 | // To keep coherence with the metric labels, we create "resource_group", "resource_name" 95 | // and "sub_resource_name" by invoking CreateResourceLabels. 96 | resourceLabels := CreateResourceLabels(rm.resourceURL) 97 | for k, v := range resourceLabels { 98 | labels[k] = v 99 | } 100 | return labels 101 | } 102 | 103 | func hasAggregation(aggregations []string, aggregation string) bool { 104 | if len(aggregations) == 0 { 105 | return true 106 | } 107 | 108 | for _, aggr := range aggregations { 109 | if aggr == aggregation { 110 | return true 111 | } 112 | } 113 | return false 114 | } 115 | 116 | func filterAggregations(aggregations []string) []string { 117 | base := []string{"Total", "Average", "Minimum", "Maximum"} 118 | if len(aggregations) > 0 { 119 | return aggregations 120 | } 121 | return base 122 | } 123 | -------------------------------------------------------------------------------- /utils_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestCreateResourceLabels(t *testing.T) { 9 | var cases = []struct { 10 | url string 11 | want map[string]string 12 | }{ 13 | { 14 | "/subscriptions/abc123d4-e5f6-g7h8-i9j10-a1b2c3d4e5f6/resourceGroups/prod-rg-001/providers/Microsoft.Compute/virtualMachines/prod-vm-01/providers/microsoft.insights/metrics", 15 | map[string]string{"resource_group": "prod-rg-001", "resource_name": "prod-vm-01"}, 16 | }, 17 | { 18 | "/subscriptions/abc123d4-e5f6-g7h8-i9j10-a1b2c3d4e5f6/resourceGroups/prod-rg-002/providers/Microsoft.Sql/servers/sqlprod/databases/prod-db-01/providers/microsoft.insights/metrics", 19 | map[string]string{"resource_group": "prod-rg-002", "resource_name": "sqlprod", "sub_resource_name": "prod-db-01"}, 20 | }, 21 | } 22 | 23 | for _, c := range cases { 24 | got := CreateResourceLabels(c.url) 25 | 26 | if !reflect.DeepEqual(got, c.want) { 27 | t.Errorf("doesn't create expected resource labels\ngot: %v\nwant: %v", got, c.want) 28 | } 29 | } 30 | } 31 | 32 | func TestCreateAllResourceLabelsFrom(t *testing.T) { 33 | var cases = []struct { 34 | rm resourceMeta 35 | want map[string]string 36 | }{ 37 | { 38 | resourceMeta{ 39 | resourceURL: "/subscriptions/abc123d4-e5f6-g7h8-i9j10-a1b2c3d4e5f6/resourceGroups/prod-rg-001/providers/Microsoft.Compute/virtualMachines/prod-vm-01/providers/microsoft.insights/metrics", 40 | resource: AzureResource{ 41 | ID: "/resourceGroups/prod-rg-001/providers/Microsoft.Compute/virtualMachines/prod-vm-01", 42 | Name: "fxpromdev01", 43 | Location: "canadaeast", 44 | Type: "Microsoft.Compute/virtualMachines", 45 | Tags: map[string]string{"monitoring": "enabled", "department": "secret"}, 46 | Subscription: "abc123d4-e5f6-g7h8-i9j10-a1b2c3d4e5f6", 47 | }, 48 | }, 49 | map[string]string{ 50 | "azure_location": "canadaeast", 51 | "azure_subscription": "abc123d4-e5f6-g7h8-i9j10-a1b2c3d4e5f6", 52 | "id": "/resourceGroups/prod-rg-001/providers/Microsoft.Compute/virtualMachines/prod-vm-01", 53 | "managed_by": "", 54 | "resource_group": "prod-rg-001", 55 | "resource_name": "prod-vm-01", 56 | "resource_type": "Microsoft.Compute/virtualMachines", 57 | "tag_department": "secret", 58 | "tag_monitoring": "enabled", 59 | }, 60 | }, 61 | } 62 | 63 | for _, c := range cases { 64 | got := CreateAllResourceLabelsFrom(c.rm) 65 | 66 | if !reflect.DeepEqual(got, c.want) { 67 | t.Errorf("doesn't create expected resource labels\ngot: %v\nwant: %v", got, c.want) 68 | } 69 | } 70 | } 71 | 72 | func TestCetResourceType(t *testing.T) { 73 | var cases = []struct { 74 | url string 75 | want string 76 | }{ 77 | { 78 | "/subscriptions/abc123d4-e5f6-g7h8-i9j10-a1b2c3d4e5f6/resourceGroups/prod-rg-001/providers/Microsoft.Compute/virtualMachines/prod-vm-01/providers/microsoft.insights/metrics", 79 | "Microsoft.Compute/virtualMachines", 80 | }, 81 | { 82 | "/subscriptions/abc123d4-e5f6-g7h8-i9j10-a1b2c3d4e5f6/resourceGroups/prod-rg-002/providers/Microsoft.Sql/servers/sqlprod/databases/prod-db-01/providers/microsoft.insights/metrics", 83 | "Microsoft.Sql/servers/databases", 84 | }, 85 | } 86 | 87 | for _, c := range cases { 88 | got := GetResourceType(c.url) 89 | 90 | if !reflect.DeepEqual(got, c.want) { 91 | t.Errorf("doesn't create expected resource type\ngot: %v\nwant: %v", got, c.want) 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/template/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 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/alecthomas/template/README.md: -------------------------------------------------------------------------------- 1 | # Go's `text/template` package with newline elision 2 | 3 | This is a fork of Go 1.4's [text/template](http://golang.org/pkg/text/template/) package with one addition: a backslash immediately after a closing delimiter will delete all subsequent newlines until a non-newline. 4 | 5 | eg. 6 | 7 | ``` 8 | {{if true}}\ 9 | hello 10 | {{end}}\ 11 | ``` 12 | 13 | Will result in: 14 | 15 | ``` 16 | hello\n 17 | ``` 18 | 19 | Rather than: 20 | 21 | ``` 22 | \n 23 | hello\n 24 | \n 25 | ``` 26 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/template/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/alecthomas/template 2 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/template/helper.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 | // Helper functions to make constructing templates easier. 6 | 7 | package template 8 | 9 | import ( 10 | "fmt" 11 | "io/ioutil" 12 | "path/filepath" 13 | ) 14 | 15 | // Functions and methods to parse templates. 16 | 17 | // Must is a helper that wraps a call to a function returning (*Template, error) 18 | // and panics if the error is non-nil. It is intended for use in variable 19 | // initializations such as 20 | // var t = template.Must(template.New("name").Parse("text")) 21 | func Must(t *Template, err error) *Template { 22 | if err != nil { 23 | panic(err) 24 | } 25 | return t 26 | } 27 | 28 | // ParseFiles creates a new Template and parses the template definitions from 29 | // the named files. The returned template's name will have the (base) name and 30 | // (parsed) contents of the first file. There must be at least one file. 31 | // If an error occurs, parsing stops and the returned *Template is nil. 32 | func ParseFiles(filenames ...string) (*Template, error) { 33 | return parseFiles(nil, filenames...) 34 | } 35 | 36 | // ParseFiles parses the named files and associates the resulting templates with 37 | // t. If an error occurs, parsing stops and the returned template is nil; 38 | // otherwise it is t. There must be at least one file. 39 | func (t *Template) ParseFiles(filenames ...string) (*Template, error) { 40 | return parseFiles(t, filenames...) 41 | } 42 | 43 | // parseFiles is the helper for the method and function. If the argument 44 | // template is nil, it is created from the first file. 45 | func parseFiles(t *Template, filenames ...string) (*Template, error) { 46 | if len(filenames) == 0 { 47 | // Not really a problem, but be consistent. 48 | return nil, fmt.Errorf("template: no files named in call to ParseFiles") 49 | } 50 | for _, filename := range filenames { 51 | b, err := ioutil.ReadFile(filename) 52 | if err != nil { 53 | return nil, err 54 | } 55 | s := string(b) 56 | name := filepath.Base(filename) 57 | // First template becomes return value if not already defined, 58 | // and we use that one for subsequent New calls to associate 59 | // all the templates together. Also, if this file has the same name 60 | // as t, this file becomes the contents of t, so 61 | // t, err := New(name).Funcs(xxx).ParseFiles(name) 62 | // works. Otherwise we create a new template associated with t. 63 | var tmpl *Template 64 | if t == nil { 65 | t = New(name) 66 | } 67 | if name == t.Name() { 68 | tmpl = t 69 | } else { 70 | tmpl = t.New(name) 71 | } 72 | _, err = tmpl.Parse(s) 73 | if err != nil { 74 | return nil, err 75 | } 76 | } 77 | return t, nil 78 | } 79 | 80 | // ParseGlob creates a new Template and parses the template definitions from the 81 | // files identified by the pattern, which must match at least one file. The 82 | // returned template will have the (base) name and (parsed) contents of the 83 | // first file matched by the pattern. ParseGlob is equivalent to calling 84 | // ParseFiles with the list of files matched by the pattern. 85 | func ParseGlob(pattern string) (*Template, error) { 86 | return parseGlob(nil, pattern) 87 | } 88 | 89 | // ParseGlob parses the template definitions in the files identified by the 90 | // pattern and associates the resulting templates with t. The pattern is 91 | // processed by filepath.Glob and must match at least one file. ParseGlob is 92 | // equivalent to calling t.ParseFiles with the list of files matched by the 93 | // pattern. 94 | func (t *Template) ParseGlob(pattern string) (*Template, error) { 95 | return parseGlob(t, pattern) 96 | } 97 | 98 | // parseGlob is the implementation of the function and method ParseGlob. 99 | func parseGlob(t *Template, pattern string) (*Template, error) { 100 | filenames, err := filepath.Glob(pattern) 101 | if err != nil { 102 | return nil, err 103 | } 104 | if len(filenames) == 0 { 105 | return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern) 106 | } 107 | return parseFiles(t, filenames...) 108 | } 109 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (C) 2014 Alec Thomas 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/README.md: -------------------------------------------------------------------------------- 1 | # Units - Helpful unit multipliers and functions for Go 2 | 3 | The goal of this package is to have functionality similar to the [time](http://golang.org/pkg/time/) package. 4 | 5 | It allows for code like this: 6 | 7 | ```go 8 | n, err := ParseBase2Bytes("1KB") 9 | // n == 1024 10 | n = units.Mebibyte * 512 11 | ``` 12 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/bytes.go: -------------------------------------------------------------------------------- 1 | package units 2 | 3 | // Base2Bytes is the old non-SI power-of-2 byte scale (1024 bytes in a kilobyte, 4 | // etc.). 5 | type Base2Bytes int64 6 | 7 | // Base-2 byte units. 8 | const ( 9 | Kibibyte Base2Bytes = 1024 10 | KiB = Kibibyte 11 | Mebibyte = Kibibyte * 1024 12 | MiB = Mebibyte 13 | Gibibyte = Mebibyte * 1024 14 | GiB = Gibibyte 15 | Tebibyte = Gibibyte * 1024 16 | TiB = Tebibyte 17 | Pebibyte = Tebibyte * 1024 18 | PiB = Pebibyte 19 | Exbibyte = Pebibyte * 1024 20 | EiB = Exbibyte 21 | ) 22 | 23 | var ( 24 | bytesUnitMap = MakeUnitMap("iB", "B", 1024) 25 | oldBytesUnitMap = MakeUnitMap("B", "B", 1024) 26 | ) 27 | 28 | // ParseBase2Bytes supports both iB and B in base-2 multipliers. That is, KB 29 | // and KiB are both 1024. 30 | func ParseBase2Bytes(s string) (Base2Bytes, error) { 31 | n, err := ParseUnit(s, bytesUnitMap) 32 | if err != nil { 33 | n, err = ParseUnit(s, oldBytesUnitMap) 34 | } 35 | return Base2Bytes(n), err 36 | } 37 | 38 | func (b Base2Bytes) String() string { 39 | return ToString(int64(b), 1024, "iB", "B") 40 | } 41 | 42 | var ( 43 | metricBytesUnitMap = MakeUnitMap("B", "B", 1000) 44 | ) 45 | 46 | // MetricBytes are SI byte units (1000 bytes in a kilobyte). 47 | type MetricBytes SI 48 | 49 | // SI base-10 byte units. 50 | const ( 51 | Kilobyte MetricBytes = 1000 52 | KB = Kilobyte 53 | Megabyte = Kilobyte * 1000 54 | MB = Megabyte 55 | Gigabyte = Megabyte * 1000 56 | GB = Gigabyte 57 | Terabyte = Gigabyte * 1000 58 | TB = Terabyte 59 | Petabyte = Terabyte * 1000 60 | PB = Petabyte 61 | Exabyte = Petabyte * 1000 62 | EB = Exabyte 63 | ) 64 | 65 | // ParseMetricBytes parses base-10 metric byte units. That is, KB is 1000 bytes. 66 | func ParseMetricBytes(s string) (MetricBytes, error) { 67 | n, err := ParseUnit(s, metricBytesUnitMap) 68 | return MetricBytes(n), err 69 | } 70 | 71 | func (m MetricBytes) String() string { 72 | return ToString(int64(m), 1000, "B", "B") 73 | } 74 | 75 | // ParseStrictBytes supports both iB and B suffixes for base 2 and metric, 76 | // respectively. That is, KiB represents 1024 and KB represents 1000. 77 | func ParseStrictBytes(s string) (int64, error) { 78 | n, err := ParseUnit(s, bytesUnitMap) 79 | if err != nil { 80 | n, err = ParseUnit(s, metricBytesUnitMap) 81 | } 82 | return int64(n), err 83 | } 84 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/doc.go: -------------------------------------------------------------------------------- 1 | // Package units provides helpful unit multipliers and functions for Go. 2 | // 3 | // The goal of this package is to have functionality similar to the time [1] package. 4 | // 5 | // 6 | // [1] http://golang.org/pkg/time/ 7 | // 8 | // It allows for code like this: 9 | // 10 | // n, err := ParseBase2Bytes("1KB") 11 | // // n == 1024 12 | // n = units.Mebibyte * 512 13 | package units 14 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/alecthomas/units 2 | 3 | require github.com/stretchr/testify v1.4.0 4 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 6 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 7 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 9 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 10 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 11 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 12 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/si.go: -------------------------------------------------------------------------------- 1 | package units 2 | 3 | // SI units. 4 | type SI int64 5 | 6 | // SI unit multiples. 7 | const ( 8 | Kilo SI = 1000 9 | Mega = Kilo * 1000 10 | Giga = Mega * 1000 11 | Tera = Giga * 1000 12 | Peta = Tera * 1000 13 | Exa = Peta * 1000 14 | ) 15 | 16 | func MakeUnitMap(suffix, shortSuffix string, scale int64) map[string]float64 { 17 | return map[string]float64{ 18 | shortSuffix: 1, 19 | "K" + suffix: float64(scale), 20 | "M" + suffix: float64(scale * scale), 21 | "G" + suffix: float64(scale * scale * scale), 22 | "T" + suffix: float64(scale * scale * scale * scale), 23 | "P" + suffix: float64(scale * scale * scale * scale * scale), 24 | "E" + suffix: float64(scale * scale * scale * scale * scale * scale), 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/util.go: -------------------------------------------------------------------------------- 1 | package units 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | var ( 10 | siUnits = []string{"", "K", "M", "G", "T", "P", "E"} 11 | ) 12 | 13 | func ToString(n int64, scale int64, suffix, baseSuffix string) string { 14 | mn := len(siUnits) 15 | out := make([]string, mn) 16 | for i, m := range siUnits { 17 | if n%scale != 0 || i == 0 && n == 0 { 18 | s := suffix 19 | if i == 0 { 20 | s = baseSuffix 21 | } 22 | out[mn-1-i] = fmt.Sprintf("%d%s%s", n%scale, m, s) 23 | } 24 | n /= scale 25 | if n == 0 { 26 | break 27 | } 28 | } 29 | return strings.Join(out, "") 30 | } 31 | 32 | // Below code ripped straight from http://golang.org/src/pkg/time/format.go?s=33392:33438#L1123 33 | var errLeadingInt = errors.New("units: bad [0-9]*") // never printed 34 | 35 | // leadingInt consumes the leading [0-9]* from s. 36 | func leadingInt(s string) (x int64, rem string, err error) { 37 | i := 0 38 | for ; i < len(s); i++ { 39 | c := s[i] 40 | if c < '0' || c > '9' { 41 | break 42 | } 43 | if x >= (1<<63-10)/10 { 44 | // overflow 45 | return 0, "", errLeadingInt 46 | } 47 | x = x*10 + int64(c) - '0' 48 | } 49 | return x, s[i:], nil 50 | } 51 | 52 | func ParseUnit(s string, unitMap map[string]float64) (int64, error) { 53 | // [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+ 54 | orig := s 55 | f := float64(0) 56 | neg := false 57 | 58 | // Consume [-+]? 59 | if s != "" { 60 | c := s[0] 61 | if c == '-' || c == '+' { 62 | neg = c == '-' 63 | s = s[1:] 64 | } 65 | } 66 | // Special case: if all that is left is "0", this is zero. 67 | if s == "0" { 68 | return 0, nil 69 | } 70 | if s == "" { 71 | return 0, errors.New("units: invalid " + orig) 72 | } 73 | for s != "" { 74 | g := float64(0) // this element of the sequence 75 | 76 | var x int64 77 | var err error 78 | 79 | // The next character must be [0-9.] 80 | if !(s[0] == '.' || ('0' <= s[0] && s[0] <= '9')) { 81 | return 0, errors.New("units: invalid " + orig) 82 | } 83 | // Consume [0-9]* 84 | pl := len(s) 85 | x, s, err = leadingInt(s) 86 | if err != nil { 87 | return 0, errors.New("units: invalid " + orig) 88 | } 89 | g = float64(x) 90 | pre := pl != len(s) // whether we consumed anything before a period 91 | 92 | // Consume (\.[0-9]*)? 93 | post := false 94 | if s != "" && s[0] == '.' { 95 | s = s[1:] 96 | pl := len(s) 97 | x, s, err = leadingInt(s) 98 | if err != nil { 99 | return 0, errors.New("units: invalid " + orig) 100 | } 101 | scale := 1.0 102 | for n := pl - len(s); n > 0; n-- { 103 | scale *= 10 104 | } 105 | g += float64(x) / scale 106 | post = pl != len(s) 107 | } 108 | if !pre && !post { 109 | // no digits (e.g. ".s" or "-.s") 110 | return 0, errors.New("units: invalid " + orig) 111 | } 112 | 113 | // Consume unit. 114 | i := 0 115 | for ; i < len(s); i++ { 116 | c := s[i] 117 | if c == '.' || ('0' <= c && c <= '9') { 118 | break 119 | } 120 | } 121 | u := s[:i] 122 | s = s[i:] 123 | unit, ok := unitMap[u] 124 | if !ok { 125 | return 0, errors.New("units: unknown unit " + u + " in " + orig) 126 | } 127 | 128 | f += g * unit 129 | } 130 | 131 | if neg { 132 | f = -f 133 | } 134 | if f < float64(-1<<63) || f > float64(1<<63-1) { 135 | return 0, errors.New("units: overflow parsing unit") 136 | } 137 | return int64(f), nil 138 | } 139 | -------------------------------------------------------------------------------- /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/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/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/golang/protobuf/proto/deprecated.go: -------------------------------------------------------------------------------- 1 | // Go support for Protocol Buffers - Google's data interchange format 2 | // 3 | // Copyright 2018 The Go Authors. All rights reserved. 4 | // https://github.com/golang/protobuf 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // * Redistributions of source code must retain the above copyright 11 | // notice, this list of conditions and the following disclaimer. 12 | // * Redistributions in binary form must reproduce the above 13 | // copyright notice, this list of conditions and the following disclaimer 14 | // in the documentation and/or other materials provided with the 15 | // distribution. 16 | // * Neither the name of Google Inc. nor the names of its 17 | // contributors may be used to endorse or promote products derived from 18 | // this software without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | package proto 33 | 34 | import "errors" 35 | 36 | // Deprecated: do not use. 37 | type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } 38 | 39 | // Deprecated: do not use. 40 | func GetStats() Stats { return Stats{} } 41 | 42 | // Deprecated: do not use. 43 | func MarshalMessageSet(interface{}) ([]byte, error) { 44 | return nil, errors.New("proto: not implemented") 45 | } 46 | 47 | // Deprecated: do not use. 48 | func UnmarshalMessageSet([]byte, interface{}) error { 49 | return errors.New("proto: not implemented") 50 | } 51 | 52 | // Deprecated: do not use. 53 | func MarshalMessageSetJSON(interface{}) ([]byte, error) { 54 | return nil, errors.New("proto: not implemented") 55 | } 56 | 57 | // Deprecated: do not use. 58 | func UnmarshalMessageSetJSON([]byte, interface{}) error { 59 | return errors.New("proto: not implemented") 60 | } 61 | 62 | // Deprecated: do not use. 63 | func RegisterMessageSetType(Message, int32, string) {} 64 | -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2012 Matt T. Proud (matt.proud@gmail.com) 2 | -------------------------------------------------------------------------------- /vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/.gitignore: -------------------------------------------------------------------------------- 1 | cover.dat 2 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/client_golang/prometheus/.gitignore: -------------------------------------------------------------------------------- 1 | command-line-arguments.test 2 | -------------------------------------------------------------------------------- /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/prometheus/client_golang/prometheus/build_info.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 go1.12 15 | 16 | package prometheus 17 | 18 | import "runtime/debug" 19 | 20 | // readBuildInfo is a wrapper around debug.ReadBuildInfo for Go 1.12+. 21 | func readBuildInfo() (path, version, sum string) { 22 | path, version, sum = "unknown", "unknown", "unknown" 23 | if bi, ok := debug.ReadBuildInfo(); ok { 24 | path = bi.Main.Path 25 | version = bi.Main.Version 26 | sum = bi.Main.Sum 27 | } 28 | return 29 | } 30 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/build_info_pre_1.12.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 !go1.12 15 | 16 | package prometheus 17 | 18 | // readBuildInfo is a wrapper around debug.ReadBuildInfo for Go versions before 19 | // 1.12. Remove this whole file once the minimum supported Go version is 1.12. 20 | func readBuildInfo() (path, version, sum string) { 21 | return "unknown", "unknown", "unknown" 22 | } 23 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/fnv.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 prometheus 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/github.com/prometheus/client_golang/prometheus/internal/metric.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 internal 15 | 16 | import ( 17 | "sort" 18 | 19 | dto "github.com/prometheus/client_model/go" 20 | ) 21 | 22 | // metricSorter is a sortable slice of *dto.Metric. 23 | type metricSorter []*dto.Metric 24 | 25 | func (s metricSorter) Len() int { 26 | return len(s) 27 | } 28 | 29 | func (s metricSorter) Swap(i, j int) { 30 | s[i], s[j] = s[j], s[i] 31 | } 32 | 33 | func (s metricSorter) Less(i, j int) bool { 34 | if len(s[i].Label) != len(s[j].Label) { 35 | // This should not happen. The metrics are 36 | // inconsistent. However, we have to deal with the fact, as 37 | // people might use custom collectors or metric family injection 38 | // to create inconsistent metrics. So let's simply compare the 39 | // number of labels in this case. That will still yield 40 | // reproducible sorting. 41 | return len(s[i].Label) < len(s[j].Label) 42 | } 43 | for n, lp := range s[i].Label { 44 | vi := lp.GetValue() 45 | vj := s[j].Label[n].GetValue() 46 | if vi != vj { 47 | return vi < vj 48 | } 49 | } 50 | 51 | // We should never arrive here. Multiple metrics with the same 52 | // label set in the same scrape will lead to undefined ingestion 53 | // behavior. However, as above, we have to provide stable sorting 54 | // here, even for inconsistent metrics. So sort equal metrics 55 | // by their timestamp, with missing timestamps (implying "now") 56 | // coming last. 57 | if s[i].TimestampMs == nil { 58 | return false 59 | } 60 | if s[j].TimestampMs == nil { 61 | return true 62 | } 63 | return s[i].GetTimestampMs() < s[j].GetTimestampMs() 64 | } 65 | 66 | // NormalizeMetricFamilies returns a MetricFamily slice with empty 67 | // MetricFamilies pruned and the remaining MetricFamilies sorted by name within 68 | // the slice, with the contained Metrics sorted within each MetricFamily. 69 | func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily { 70 | for _, mf := range metricFamiliesByName { 71 | sort.Sort(metricSorter(mf.Metric)) 72 | } 73 | names := make([]string, 0, len(metricFamiliesByName)) 74 | for name, mf := range metricFamiliesByName { 75 | if len(mf.Metric) > 0 { 76 | names = append(names, name) 77 | } 78 | } 79 | sort.Strings(names) 80 | result := make([]*dto.MetricFamily, 0, len(names)) 81 | for _, name := range names { 82 | result = append(result, metricFamiliesByName[name]) 83 | } 84 | return result 85 | } 86 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/labels.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 prometheus 15 | 16 | import ( 17 | "errors" 18 | "fmt" 19 | "strings" 20 | "unicode/utf8" 21 | 22 | "github.com/prometheus/common/model" 23 | ) 24 | 25 | // Labels represents a collection of label name -> value mappings. This type is 26 | // commonly used with the With(Labels) and GetMetricWith(Labels) methods of 27 | // metric vector Collectors, e.g.: 28 | // myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) 29 | // 30 | // The other use-case is the specification of constant label pairs in Opts or to 31 | // create a Desc. 32 | type Labels map[string]string 33 | 34 | // reservedLabelPrefix is a prefix which is not legal in user-supplied 35 | // label names. 36 | const reservedLabelPrefix = "__" 37 | 38 | var errInconsistentCardinality = errors.New("inconsistent label cardinality") 39 | 40 | func makeInconsistentCardinalityError(fqName string, labels, labelValues []string) error { 41 | return fmt.Errorf( 42 | "%s: %q has %d variable labels named %q but %d values %q were provided", 43 | errInconsistentCardinality, fqName, 44 | len(labels), labels, 45 | len(labelValues), labelValues, 46 | ) 47 | } 48 | 49 | func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error { 50 | if len(labels) != expectedNumberOfValues { 51 | return fmt.Errorf( 52 | "%s: expected %d label values but got %d in %#v", 53 | errInconsistentCardinality, expectedNumberOfValues, 54 | len(labels), labels, 55 | ) 56 | } 57 | 58 | for name, val := range labels { 59 | if !utf8.ValidString(val) { 60 | return fmt.Errorf("label %s: value %q is not valid UTF-8", name, val) 61 | } 62 | } 63 | 64 | return nil 65 | } 66 | 67 | func validateLabelValues(vals []string, expectedNumberOfValues int) error { 68 | if len(vals) != expectedNumberOfValues { 69 | return fmt.Errorf( 70 | "%s: expected %d label values but got %d in %#v", 71 | errInconsistentCardinality, expectedNumberOfValues, 72 | len(vals), vals, 73 | ) 74 | } 75 | 76 | for _, val := range vals { 77 | if !utf8.ValidString(val) { 78 | return fmt.Errorf("label value %q is not valid UTF-8", val) 79 | } 80 | } 81 | 82 | return nil 83 | } 84 | 85 | func checkLabelName(l string) bool { 86 | return model.LabelName(l).IsValid() && !strings.HasPrefix(l, reservedLabelPrefix) 87 | } 88 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/observer.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 prometheus 15 | 16 | // Observer is the interface that wraps the Observe method, which is used by 17 | // Histogram and Summary to add observations. 18 | type Observer interface { 19 | Observe(float64) 20 | } 21 | 22 | // The ObserverFunc type is an adapter to allow the use of ordinary 23 | // functions as Observers. If f is a function with the appropriate 24 | // signature, ObserverFunc(f) is an Observer that calls f. 25 | // 26 | // This adapter is usually used in connection with the Timer type, and there are 27 | // two general use cases: 28 | // 29 | // The most common one is to use a Gauge as the Observer for a Timer. 30 | // See the "Gauge" Timer example. 31 | // 32 | // The more advanced use case is to create a function that dynamically decides 33 | // which Observer to use for observing the duration. See the "Complex" Timer 34 | // example. 35 | type ObserverFunc func(float64) 36 | 37 | // Observe calls f(value). It implements Observer. 38 | func (f ObserverFunc) Observe(value float64) { 39 | f(value) 40 | } 41 | 42 | // ObserverVec is an interface implemented by `HistogramVec` and `SummaryVec`. 43 | type ObserverVec interface { 44 | GetMetricWith(Labels) (Observer, error) 45 | GetMetricWithLabelValues(lvs ...string) (Observer, error) 46 | With(Labels) Observer 47 | WithLabelValues(...string) Observer 48 | CurryWith(Labels) (ObserverVec, error) 49 | MustCurryWith(Labels) ObserverVec 50 | 51 | Collector 52 | } 53 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 !windows 15 | 16 | package prometheus 17 | 18 | import ( 19 | "github.com/prometheus/procfs" 20 | ) 21 | 22 | func canCollectProcess() bool { 23 | _, err := procfs.NewDefaultFS() 24 | return err == nil 25 | } 26 | 27 | func (c *processCollector) processCollect(ch chan<- Metric) { 28 | pid, err := c.pidFn() 29 | if err != nil { 30 | c.reportError(ch, nil, err) 31 | return 32 | } 33 | 34 | p, err := procfs.NewProc(pid) 35 | if err != nil { 36 | c.reportError(ch, nil, err) 37 | return 38 | } 39 | 40 | if stat, err := p.Stat(); err == nil { 41 | ch <- MustNewConstMetric(c.cpuTotal, CounterValue, stat.CPUTime()) 42 | ch <- MustNewConstMetric(c.vsize, GaugeValue, float64(stat.VirtualMemory())) 43 | ch <- MustNewConstMetric(c.rss, GaugeValue, float64(stat.ResidentMemory())) 44 | if startTime, err := stat.StartTime(); err == nil { 45 | ch <- MustNewConstMetric(c.startTime, GaugeValue, startTime) 46 | } else { 47 | c.reportError(ch, c.startTime, err) 48 | } 49 | } else { 50 | c.reportError(ch, nil, err) 51 | } 52 | 53 | if fds, err := p.FileDescriptorsLen(); err == nil { 54 | ch <- MustNewConstMetric(c.openFDs, GaugeValue, float64(fds)) 55 | } else { 56 | c.reportError(ch, c.openFDs, err) 57 | } 58 | 59 | if limits, err := p.Limits(); err == nil { 60 | ch <- MustNewConstMetric(c.maxFDs, GaugeValue, float64(limits.OpenFiles)) 61 | ch <- MustNewConstMetric(c.maxVsize, GaugeValue, float64(limits.AddressSpace)) 62 | } else { 63 | c.reportError(ch, nil, err) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | "syscall" 18 | "unsafe" 19 | 20 | "golang.org/x/sys/windows" 21 | ) 22 | 23 | func canCollectProcess() bool { 24 | return true 25 | } 26 | 27 | var ( 28 | modpsapi = syscall.NewLazyDLL("psapi.dll") 29 | modkernel32 = syscall.NewLazyDLL("kernel32.dll") 30 | 31 | procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo") 32 | procGetProcessHandleCount = modkernel32.NewProc("GetProcessHandleCount") 33 | ) 34 | 35 | type processMemoryCounters struct { 36 | // https://docs.microsoft.com/en-us/windows/desktop/api/psapi/ns-psapi-_process_memory_counters_ex 37 | _ uint32 38 | PageFaultCount uint32 39 | PeakWorkingSetSize uint64 40 | WorkingSetSize uint64 41 | QuotaPeakPagedPoolUsage uint64 42 | QuotaPagedPoolUsage uint64 43 | QuotaPeakNonPagedPoolUsage uint64 44 | QuotaNonPagedPoolUsage uint64 45 | PagefileUsage uint64 46 | PeakPagefileUsage uint64 47 | PrivateUsage uint64 48 | } 49 | 50 | func getProcessMemoryInfo(handle windows.Handle) (processMemoryCounters, error) { 51 | mem := processMemoryCounters{} 52 | r1, _, err := procGetProcessMemoryInfo.Call( 53 | uintptr(handle), 54 | uintptr(unsafe.Pointer(&mem)), 55 | uintptr(unsafe.Sizeof(mem)), 56 | ) 57 | if r1 != 1 { 58 | return mem, err 59 | } else { 60 | return mem, nil 61 | } 62 | } 63 | 64 | func getProcessHandleCount(handle windows.Handle) (uint32, error) { 65 | var count uint32 66 | r1, _, err := procGetProcessHandleCount.Call( 67 | uintptr(handle), 68 | uintptr(unsafe.Pointer(&count)), 69 | ) 70 | if r1 != 1 { 71 | return 0, err 72 | } else { 73 | return count, nil 74 | } 75 | } 76 | 77 | func (c *processCollector) processCollect(ch chan<- Metric) { 78 | h, err := windows.GetCurrentProcess() 79 | if err != nil { 80 | c.reportError(ch, nil, err) 81 | return 82 | } 83 | 84 | var startTime, exitTime, kernelTime, userTime windows.Filetime 85 | err = windows.GetProcessTimes(h, &startTime, &exitTime, &kernelTime, &userTime) 86 | if err != nil { 87 | c.reportError(ch, nil, err) 88 | return 89 | } 90 | ch <- MustNewConstMetric(c.startTime, GaugeValue, float64(startTime.Nanoseconds()/1e9)) 91 | ch <- MustNewConstMetric(c.cpuTotal, CounterValue, fileTimeToSeconds(kernelTime)+fileTimeToSeconds(userTime)) 92 | 93 | mem, err := getProcessMemoryInfo(h) 94 | if err != nil { 95 | c.reportError(ch, nil, err) 96 | return 97 | } 98 | ch <- MustNewConstMetric(c.vsize, GaugeValue, float64(mem.PrivateUsage)) 99 | ch <- MustNewConstMetric(c.rss, GaugeValue, float64(mem.WorkingSetSize)) 100 | 101 | handles, err := getProcessHandleCount(h) 102 | if err != nil { 103 | c.reportError(ch, nil, err) 104 | return 105 | } 106 | ch <- MustNewConstMetric(c.openFDs, GaugeValue, float64(handles)) 107 | ch <- MustNewConstMetric(c.maxFDs, GaugeValue, float64(16*1024*1024)) // Windows has a hard-coded max limit, not per-process. 108 | } 109 | 110 | func fileTimeToSeconds(ft windows.Filetime) float64 { 111 | return float64(uint64(ft.HighDateTime)<<32+uint64(ft.LowDateTime)) / 1e7 112 | } 113 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/timer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 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 "time" 17 | 18 | // Timer is a helper type to time functions. Use NewTimer to create new 19 | // instances. 20 | type Timer struct { 21 | begin time.Time 22 | observer Observer 23 | } 24 | 25 | // NewTimer creates a new Timer. The provided Observer is used to observe a 26 | // duration in seconds. Timer is usually used to time a function call in the 27 | // following way: 28 | // func TimeMe() { 29 | // timer := NewTimer(myHistogram) 30 | // defer timer.ObserveDuration() 31 | // // Do actual work. 32 | // } 33 | func NewTimer(o Observer) *Timer { 34 | return &Timer{ 35 | begin: time.Now(), 36 | observer: o, 37 | } 38 | } 39 | 40 | // ObserveDuration records the duration passed since the Timer was created with 41 | // NewTimer. It calls the Observe method of the Observer provided during 42 | // construction with the duration in seconds as an argument. The observed 43 | // duration is also returned. ObserveDuration is usually called with a defer 44 | // statement. 45 | // 46 | // Note that this method is only guaranteed to never observe negative durations 47 | // if used with Go1.9+. 48 | func (t *Timer) ObserveDuration() time.Duration { 49 | d := time.Since(t.begin) 50 | if t.observer != nil { 51 | t.observer.Observe(d.Seconds()) 52 | } 53 | return d 54 | } 55 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/client_golang/prometheus/untyped.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 | // UntypedOpts is an alias for Opts. See there for doc comments. 17 | type UntypedOpts Opts 18 | 19 | // UntypedFunc works like GaugeFunc but the collected metric is of type 20 | // "Untyped". UntypedFunc is useful to mirror an external metric of unknown 21 | // type. 22 | // 23 | // To create UntypedFunc instances, use NewUntypedFunc. 24 | type UntypedFunc interface { 25 | Metric 26 | Collector 27 | } 28 | 29 | // NewUntypedFunc creates a new UntypedFunc based on the provided 30 | // UntypedOpts. The value reported is determined by calling the given function 31 | // from within the Write method. Take into account that metric collection may 32 | // happen concurrently. If that results in concurrent calls to Write, like in 33 | // the case where an UntypedFunc is directly registered with Prometheus, the 34 | // provided function must be concurrency-safe. 35 | func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc { 36 | return newValueFunc(NewDesc( 37 | BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), 38 | opts.Help, 39 | nil, 40 | opts.ConstLabels, 41 | ), UntypedValue, function) 42 | } 43 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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/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/common/internal/bitbucket.org/ww/goautoneg/autoneg.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2011, Open Knowledge Foundation Ltd. 3 | All rights reserved. 4 | 5 | HTTP Content-Type Autonegotiation. 6 | 7 | The functions in this package implement the behaviour specified in 8 | http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions are 12 | met: 13 | 14 | Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | 17 | Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in 19 | the documentation and/or other materials provided with the 20 | distribution. 21 | 22 | Neither the name of the Open Knowledge Foundation Ltd. nor the 23 | names of its contributors may be used to endorse or promote 24 | products derived from this software without specific prior written 25 | permission. 26 | 27 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 28 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 29 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 30 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 31 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 32 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 33 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 34 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 35 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 36 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 37 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 38 | 39 | 40 | */ 41 | package goautoneg 42 | 43 | import ( 44 | "sort" 45 | "strconv" 46 | "strings" 47 | ) 48 | 49 | // Structure to represent a clause in an HTTP Accept Header 50 | type Accept struct { 51 | Type, SubType string 52 | Q float64 53 | Params map[string]string 54 | } 55 | 56 | // For internal use, so that we can use the sort interface 57 | type accept_slice []Accept 58 | 59 | func (accept accept_slice) Len() int { 60 | slice := []Accept(accept) 61 | return len(slice) 62 | } 63 | 64 | func (accept accept_slice) Less(i, j int) bool { 65 | slice := []Accept(accept) 66 | ai, aj := slice[i], slice[j] 67 | if ai.Q > aj.Q { 68 | return true 69 | } 70 | if ai.Type != "*" && aj.Type == "*" { 71 | return true 72 | } 73 | if ai.SubType != "*" && aj.SubType == "*" { 74 | return true 75 | } 76 | return false 77 | } 78 | 79 | func (accept accept_slice) Swap(i, j int) { 80 | slice := []Accept(accept) 81 | slice[i], slice[j] = slice[j], slice[i] 82 | } 83 | 84 | // Parse an Accept Header string returning a sorted list 85 | // of clauses 86 | func ParseAccept(header string) (accept []Accept) { 87 | parts := strings.Split(header, ",") 88 | accept = make([]Accept, 0, len(parts)) 89 | for _, part := range parts { 90 | part := strings.Trim(part, " ") 91 | 92 | a := Accept{} 93 | a.Params = make(map[string]string) 94 | a.Q = 1.0 95 | 96 | mrp := strings.Split(part, ";") 97 | 98 | media_range := mrp[0] 99 | sp := strings.Split(media_range, "/") 100 | a.Type = strings.Trim(sp[0], " ") 101 | 102 | switch { 103 | case len(sp) == 1 && a.Type == "*": 104 | a.SubType = "*" 105 | case len(sp) == 2: 106 | a.SubType = strings.Trim(sp[1], " ") 107 | default: 108 | continue 109 | } 110 | 111 | if len(mrp) == 1 { 112 | accept = append(accept, a) 113 | continue 114 | } 115 | 116 | for _, param := range mrp[1:] { 117 | sp := strings.SplitN(param, "=", 2) 118 | if len(sp) != 2 { 119 | continue 120 | } 121 | token := strings.Trim(sp[0], " ") 122 | if token == "q" { 123 | a.Q, _ = strconv.ParseFloat(sp[1], 32) 124 | } else { 125 | a.Params[token] = strings.Trim(sp[1], " ") 126 | } 127 | } 128 | 129 | accept = append(accept, a) 130 | } 131 | 132 | slice := accept_slice(accept) 133 | sort.Sort(slice) 134 | 135 | return 136 | } 137 | 138 | // Negotiate the most appropriate content_type given the accept header 139 | // and a list of alternatives. 140 | func Negotiate(header string, alternatives []string) (content_type string) { 141 | asp := make([][]string, 0, len(alternatives)) 142 | for _, ctype := range alternatives { 143 | asp = append(asp, strings.SplitN(ctype, "/", 2)) 144 | } 145 | for _, clause := range ParseAccept(header) { 146 | for i, ctsp := range asp { 147 | if clause.Type == ctsp[0] && clause.SubType == ctsp[1] { 148 | content_type = alternatives[i] 149 | return 150 | } 151 | if clause.Type == ctsp[0] && clause.SubType == "*" { 152 | content_type = alternatives[i] 153 | return 154 | } 155 | if clause.Type == "*" && clause.SubType == "*" { 156 | content_type = alternatives[i] 157 | return 158 | } 159 | } 160 | } 161 | return 162 | } 163 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/github.com/prometheus/common/model/labelset.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 | "encoding/json" 18 | "fmt" 19 | "sort" 20 | "strings" 21 | ) 22 | 23 | // A LabelSet is a collection of LabelName and LabelValue pairs. The LabelSet 24 | // may be fully-qualified down to the point where it may resolve to a single 25 | // Metric in the data store or not. All operations that occur within the realm 26 | // of a LabelSet can emit a vector of Metric entities to which the LabelSet may 27 | // match. 28 | type LabelSet map[LabelName]LabelValue 29 | 30 | // Validate checks whether all names and values in the label set 31 | // are valid. 32 | func (ls LabelSet) Validate() error { 33 | for ln, lv := range ls { 34 | if !ln.IsValid() { 35 | return fmt.Errorf("invalid name %q", ln) 36 | } 37 | if !lv.IsValid() { 38 | return fmt.Errorf("invalid value %q", lv) 39 | } 40 | } 41 | return nil 42 | } 43 | 44 | // Equal returns true iff both label sets have exactly the same key/value pairs. 45 | func (ls LabelSet) Equal(o LabelSet) bool { 46 | if len(ls) != len(o) { 47 | return false 48 | } 49 | for ln, lv := range ls { 50 | olv, ok := o[ln] 51 | if !ok { 52 | return false 53 | } 54 | if olv != lv { 55 | return false 56 | } 57 | } 58 | return true 59 | } 60 | 61 | // Before compares the metrics, using the following criteria: 62 | // 63 | // If m has fewer labels than o, it is before o. If it has more, it is not. 64 | // 65 | // If the number of labels is the same, the superset of all label names is 66 | // sorted alphanumerically. The first differing label pair found in that order 67 | // determines the outcome: If the label does not exist at all in m, then m is 68 | // before o, and vice versa. Otherwise the label value is compared 69 | // alphanumerically. 70 | // 71 | // If m and o are equal, the method returns false. 72 | func (ls LabelSet) Before(o LabelSet) bool { 73 | if len(ls) < len(o) { 74 | return true 75 | } 76 | if len(ls) > len(o) { 77 | return false 78 | } 79 | 80 | lns := make(LabelNames, 0, len(ls)+len(o)) 81 | for ln := range ls { 82 | lns = append(lns, ln) 83 | } 84 | for ln := range o { 85 | lns = append(lns, ln) 86 | } 87 | // It's probably not worth it to de-dup lns. 88 | sort.Sort(lns) 89 | for _, ln := range lns { 90 | mlv, ok := ls[ln] 91 | if !ok { 92 | return true 93 | } 94 | olv, ok := o[ln] 95 | if !ok { 96 | return false 97 | } 98 | if mlv < olv { 99 | return true 100 | } 101 | if mlv > olv { 102 | return false 103 | } 104 | } 105 | return false 106 | } 107 | 108 | // Clone returns a copy of the label set. 109 | func (ls LabelSet) Clone() LabelSet { 110 | lsn := make(LabelSet, len(ls)) 111 | for ln, lv := range ls { 112 | lsn[ln] = lv 113 | } 114 | return lsn 115 | } 116 | 117 | // Merge is a helper function to non-destructively merge two label sets. 118 | func (l LabelSet) Merge(other LabelSet) LabelSet { 119 | result := make(LabelSet, len(l)) 120 | 121 | for k, v := range l { 122 | result[k] = v 123 | } 124 | 125 | for k, v := range other { 126 | result[k] = v 127 | } 128 | 129 | return result 130 | } 131 | 132 | func (l LabelSet) String() string { 133 | lstrs := make([]string, 0, len(l)) 134 | for l, v := range l { 135 | lstrs = append(lstrs, fmt.Sprintf("%s=%q", l, v)) 136 | } 137 | 138 | sort.Strings(lstrs) 139 | return fmt.Sprintf("{%s}", strings.Join(lstrs, ", ")) 140 | } 141 | 142 | // Fingerprint returns the LabelSet's fingerprint. 143 | func (ls LabelSet) Fingerprint() Fingerprint { 144 | return labelSetToFingerprint(ls) 145 | } 146 | 147 | // FastFingerprint returns the LabelSet's Fingerprint calculated by a faster hashing 148 | // algorithm, which is, however, more susceptible to hash collisions. 149 | func (ls LabelSet) FastFingerprint() Fingerprint { 150 | return labelSetToFastFingerprint(ls) 151 | } 152 | 153 | // UnmarshalJSON implements the json.Unmarshaler interface. 154 | func (l *LabelSet) UnmarshalJSON(b []byte) error { 155 | var m map[LabelName]LabelValue 156 | if err := json.Unmarshal(b, &m); err != nil { 157 | return err 158 | } 159 | // encoding/json only unmarshals maps of the form map[string]T. It treats 160 | // LabelName as a string and does not call its UnmarshalJSON method. 161 | // Thus, we have to replicate the behavior here. 162 | for ln := range m { 163 | if !ln.IsValid() { 164 | return fmt.Errorf("%q is not a valid label name", ln) 165 | } 166 | } 167 | *l = LabelSet(m) 168 | return nil 169 | } 170 | -------------------------------------------------------------------------------- /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 | // MetricNameRE is a regular expression matching valid metric 25 | // names. Note that the IsValidMetricName function performs the same 26 | // check but faster than a match with this regular expression. 27 | MetricNameRE = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`) 28 | ) 29 | 30 | // A Metric is similar to a LabelSet, but the key difference is that a Metric is 31 | // a singleton and refers to one and only one stream of samples. 32 | type Metric LabelSet 33 | 34 | // Equal compares the metrics. 35 | func (m Metric) Equal(o Metric) bool { 36 | return LabelSet(m).Equal(LabelSet(o)) 37 | } 38 | 39 | // Before compares the metrics' underlying label sets. 40 | func (m Metric) Before(o Metric) bool { 41 | return LabelSet(m).Before(LabelSet(o)) 42 | } 43 | 44 | // Clone returns a copy of the Metric. 45 | func (m Metric) Clone() Metric { 46 | clone := make(Metric, len(m)) 47 | for k, v := range m { 48 | clone[k] = v 49 | } 50 | return clone 51 | } 52 | 53 | func (m Metric) String() string { 54 | metricName, hasName := m[MetricNameLabel] 55 | numLabels := len(m) - 1 56 | if !hasName { 57 | numLabels = len(m) 58 | } 59 | labelStrings := make([]string, 0, numLabels) 60 | for label, value := range m { 61 | if label != MetricNameLabel { 62 | labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value)) 63 | } 64 | } 65 | 66 | switch numLabels { 67 | case 0: 68 | if hasName { 69 | return string(metricName) 70 | } 71 | return "{}" 72 | default: 73 | sort.Strings(labelStrings) 74 | return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", ")) 75 | } 76 | } 77 | 78 | // Fingerprint returns a Metric's Fingerprint. 79 | func (m Metric) Fingerprint() Fingerprint { 80 | return LabelSet(m).Fingerprint() 81 | } 82 | 83 | // FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing 84 | // algorithm, which is, however, more susceptible to hash collisions. 85 | func (m Metric) FastFingerprint() Fingerprint { 86 | return LabelSet(m).FastFingerprint() 87 | } 88 | 89 | // IsValidMetricName returns true iff name matches the pattern of MetricNameRE. 90 | // This function, however, does not use MetricNameRE for the check but a much 91 | // faster hardcoded implementation. 92 | func IsValidMetricName(n LabelValue) bool { 93 | if len(n) == 0 { 94 | return false 95 | } 96 | for i, b := range n { 97 | if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == ':' || (b >= '0' && b <= '9' && i > 0)) { 98 | return false 99 | } 100 | } 101 | return true 102 | } 103 | -------------------------------------------------------------------------------- /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/github.com/prometheus/common/model/signature.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 model 15 | 16 | import ( 17 | "sort" 18 | ) 19 | 20 | // SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is 21 | // used to separate label names, label values, and other strings from each other 22 | // when calculating their combined hash value (aka signature aka fingerprint). 23 | const SeparatorByte byte = 255 24 | 25 | var ( 26 | // cache the signature of an empty label set. 27 | emptyLabelSignature = hashNew() 28 | ) 29 | 30 | // LabelsToSignature returns a quasi-unique signature (i.e., fingerprint) for a 31 | // given label set. (Collisions are possible but unlikely if the number of label 32 | // sets the function is applied to is small.) 33 | func LabelsToSignature(labels map[string]string) uint64 { 34 | if len(labels) == 0 { 35 | return emptyLabelSignature 36 | } 37 | 38 | labelNames := make([]string, 0, len(labels)) 39 | for labelName := range labels { 40 | labelNames = append(labelNames, labelName) 41 | } 42 | sort.Strings(labelNames) 43 | 44 | sum := hashNew() 45 | for _, labelName := range labelNames { 46 | sum = hashAdd(sum, labelName) 47 | sum = hashAddByte(sum, SeparatorByte) 48 | sum = hashAdd(sum, labels[labelName]) 49 | sum = hashAddByte(sum, SeparatorByte) 50 | } 51 | return sum 52 | } 53 | 54 | // labelSetToFingerprint works exactly as LabelsToSignature but takes a LabelSet as 55 | // parameter (rather than a label map) and returns a Fingerprint. 56 | func labelSetToFingerprint(ls LabelSet) Fingerprint { 57 | if len(ls) == 0 { 58 | return Fingerprint(emptyLabelSignature) 59 | } 60 | 61 | labelNames := make(LabelNames, 0, len(ls)) 62 | for labelName := range ls { 63 | labelNames = append(labelNames, labelName) 64 | } 65 | sort.Sort(labelNames) 66 | 67 | sum := hashNew() 68 | for _, labelName := range labelNames { 69 | sum = hashAdd(sum, string(labelName)) 70 | sum = hashAddByte(sum, SeparatorByte) 71 | sum = hashAdd(sum, string(ls[labelName])) 72 | sum = hashAddByte(sum, SeparatorByte) 73 | } 74 | return Fingerprint(sum) 75 | } 76 | 77 | // labelSetToFastFingerprint works similar to labelSetToFingerprint but uses a 78 | // faster and less allocation-heavy hash function, which is more susceptible to 79 | // create hash collisions. Therefore, collision detection should be applied. 80 | func labelSetToFastFingerprint(ls LabelSet) Fingerprint { 81 | if len(ls) == 0 { 82 | return Fingerprint(emptyLabelSignature) 83 | } 84 | 85 | var result uint64 86 | for labelName, labelValue := range ls { 87 | sum := hashNew() 88 | sum = hashAdd(sum, string(labelName)) 89 | sum = hashAddByte(sum, SeparatorByte) 90 | sum = hashAdd(sum, string(labelValue)) 91 | result ^= sum 92 | } 93 | return Fingerprint(result) 94 | } 95 | 96 | // SignatureForLabels works like LabelsToSignature but takes a Metric as 97 | // parameter (rather than a label map) and only includes the labels with the 98 | // specified LabelNames into the signature calculation. The labels passed in 99 | // will be sorted by this function. 100 | func SignatureForLabels(m Metric, labels ...LabelName) uint64 { 101 | if len(labels) == 0 { 102 | return emptyLabelSignature 103 | } 104 | 105 | sort.Sort(LabelNames(labels)) 106 | 107 | sum := hashNew() 108 | for _, label := range labels { 109 | sum = hashAdd(sum, string(label)) 110 | sum = hashAddByte(sum, SeparatorByte) 111 | sum = hashAdd(sum, string(m[label])) 112 | sum = hashAddByte(sum, SeparatorByte) 113 | } 114 | return sum 115 | } 116 | 117 | // SignatureWithoutLabels works like LabelsToSignature but takes a Metric as 118 | // parameter (rather than a label map) and excludes the labels with any of the 119 | // specified LabelNames from the signature calculation. 120 | func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 { 121 | if len(m) == 0 { 122 | return emptyLabelSignature 123 | } 124 | 125 | labelNames := make(LabelNames, 0, len(m)) 126 | for labelName := range m { 127 | if _, exclude := labels[labelName]; !exclude { 128 | labelNames = append(labelNames, labelName) 129 | } 130 | } 131 | if len(labelNames) == 0 { 132 | return emptyLabelSignature 133 | } 134 | sort.Sort(labelNames) 135 | 136 | sum := hashNew() 137 | for _, labelName := range labelNames { 138 | sum = hashAdd(sum, string(labelName)) 139 | sum = hashAddByte(sum, SeparatorByte) 140 | sum = hashAdd(sum, string(m[labelName])) 141 | sum = hashAddByte(sum, SeparatorByte) 142 | } 143 | return sum 144 | } 145 | -------------------------------------------------------------------------------- /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/prometheus/common/version/info.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 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 version 15 | 16 | import ( 17 | "bytes" 18 | "fmt" 19 | "runtime" 20 | "strings" 21 | "text/template" 22 | 23 | "github.com/prometheus/client_golang/prometheus" 24 | ) 25 | 26 | // Build information. Populated at build-time. 27 | var ( 28 | Version string 29 | Revision string 30 | Branch string 31 | BuildUser string 32 | BuildDate string 33 | GoVersion = runtime.Version() 34 | ) 35 | 36 | // NewCollector returns a collector which exports metrics about current version information. 37 | func NewCollector(program string) *prometheus.GaugeVec { 38 | buildInfo := prometheus.NewGaugeVec( 39 | prometheus.GaugeOpts{ 40 | Namespace: program, 41 | Name: "build_info", 42 | Help: fmt.Sprintf( 43 | "A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.", 44 | program, 45 | ), 46 | }, 47 | []string{"version", "revision", "branch", "goversion"}, 48 | ) 49 | buildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1) 50 | return buildInfo 51 | } 52 | 53 | // versionInfoTmpl contains the template used by Info. 54 | var versionInfoTmpl = ` 55 | {{.program}}, version {{.version}} (branch: {{.branch}}, revision: {{.revision}}) 56 | build user: {{.buildUser}} 57 | build date: {{.buildDate}} 58 | go version: {{.goVersion}} 59 | ` 60 | 61 | // Print returns version information. 62 | func Print(program string) string { 63 | m := map[string]string{ 64 | "program": program, 65 | "version": Version, 66 | "revision": Revision, 67 | "branch": Branch, 68 | "buildUser": BuildUser, 69 | "buildDate": BuildDate, 70 | "goVersion": GoVersion, 71 | } 72 | t := template.Must(template.New("version").Parse(versionInfoTmpl)) 73 | 74 | var buf bytes.Buffer 75 | if err := t.ExecuteTemplate(&buf, "version", m); err != nil { 76 | panic(err) 77 | } 78 | return strings.TrimSpace(buf.String()) 79 | } 80 | 81 | // Info returns version, branch and revision information. 82 | func Info() string { 83 | return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, Revision) 84 | } 85 | 86 | // BuildContext returns goVersion, buildUser and buildDate information. 87 | func BuildContext() string { 88 | return fmt.Sprintf("(go=%s, user=%s, date=%s)", GoVersion, BuildUser, BuildDate) 89 | } 90 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/.gitignore: -------------------------------------------------------------------------------- 1 | /fixtures/ 2 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/.golangci.yml: -------------------------------------------------------------------------------- 1 | # Run only staticcheck for now. Additional linters will be enabled one-by-one. 2 | linters: 3 | enable: 4 | - staticcheck 5 | - govet 6 | disable-all: true 7 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/MAINTAINERS.md: -------------------------------------------------------------------------------- 1 | * Johannes 'fish' Ziemke @discordianfish 2 | * Paul Gier @pgier 3 | -------------------------------------------------------------------------------- /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 | include Makefile.common 15 | 16 | %/.unpacked: %.ttar 17 | @echo ">> extracting fixtures" 18 | ./ttar -C $(dir $*) -x -f $*.ttar 19 | touch $@ 20 | 21 | update_fixtures: 22 | rm -vf fixtures/.unpacked 23 | ./ttar -c -f fixtures.ttar fixtures/ 24 | 25 | .PHONY: build 26 | build: 27 | 28 | .PHONY: test 29 | test: fixtures/.unpacked common-test 30 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/README.md: -------------------------------------------------------------------------------- 1 | # procfs 2 | 3 | This package provides functions to retrieve system, kernel, and process 4 | metrics from the pseudo-filesystems /proc and /sys. 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 | 13 | ## Usage 14 | 15 | The procfs library is organized by packages based on whether the gathered data is coming from 16 | /proc, /sys, or both. Each package contains an `FS` type which represents the path to either /proc, 17 | /sys, or both. For example, cpu statistics are gathered from 18 | `/proc/stat` and are available via the root procfs package. First, the proc filesystem mount 19 | point is initialized, and then the stat information is read. 20 | 21 | ```go 22 | fs, err := procfs.NewFS("/proc") 23 | stats, err := fs.Stat() 24 | ``` 25 | 26 | Some sub-packages such as `blockdevice`, require access to both the proc and sys filesystems. 27 | 28 | ```go 29 | fs, err := blockdevice.NewFS("/proc", "/sys") 30 | stats, err := fs.ProcDiskstats() 31 | ``` 32 | 33 | ## Package Organization 34 | 35 | The packages in this project are organized according to (1) whether the data comes from the `/proc` or 36 | `/sys` filesystem and (2) the type of information being retrieved. For example, most process information 37 | can be gathered from the functions in the root `procfs` package. Information about block devices such as disk drives 38 | is available in the `blockdevices` sub-package. 39 | 40 | ## Building and Testing 41 | 42 | The procfs library is intended to be built as part of another application, so there are no distributable binaries. 43 | However, most of the API includes unit tests which can be run with `make test`. 44 | 45 | ### Updating Test Fixtures 46 | 47 | The procfs library includes a set of test fixtures which include many example files from 48 | the `/proc` and `/sys` filesystems. These fixtures are included as a [ttar](https://github.com/ideaship/ttar) file 49 | which is extracted automatically during testing. To add/update the test fixtures, first 50 | ensure the `fixtures` directory is up to date by removing the existing directory and then 51 | extracting the ttar file using `make fixtures/.unpacked` or just `make test`. 52 | 53 | ```bash 54 | rm -rf fixtures 55 | make test 56 | ``` 57 | 58 | Next, make the required changes to the extracted files in the `fixtures` directory. When 59 | the changes are complete, run `make update_fixtures` to create a new `fixtures.ttar` file 60 | based on the updated `fixtures` directory. And finally, verify the changes using 61 | `git diff fixtures.ttar`. 62 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/arp.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | "net" 20 | "strings" 21 | ) 22 | 23 | // ARPEntry contains a single row of the columnar data represented in 24 | // /proc/net/arp. 25 | type ARPEntry struct { 26 | // IP address 27 | IPAddr net.IP 28 | // MAC address 29 | HWAddr net.HardwareAddr 30 | // Name of the device 31 | Device string 32 | } 33 | 34 | // GatherARPEntries retrieves all the ARP entries, parse the relevant columns, 35 | // and then return a slice of ARPEntry's. 36 | func (fs FS) GatherARPEntries() ([]ARPEntry, error) { 37 | data, err := ioutil.ReadFile(fs.proc.Path("net/arp")) 38 | if err != nil { 39 | return nil, fmt.Errorf("error reading arp %s: %s", fs.proc.Path("net/arp"), err) 40 | } 41 | 42 | return parseARPEntries(data) 43 | } 44 | 45 | func parseARPEntries(data []byte) ([]ARPEntry, error) { 46 | lines := strings.Split(string(data), "\n") 47 | entries := make([]ARPEntry, 0) 48 | var err error 49 | const ( 50 | expectedDataWidth = 6 51 | expectedHeaderWidth = 9 52 | ) 53 | for _, line := range lines { 54 | columns := strings.Fields(line) 55 | width := len(columns) 56 | 57 | if width == expectedHeaderWidth || width == 0 { 58 | continue 59 | } else if width == expectedDataWidth { 60 | entry, err := parseARPEntry(columns) 61 | if err != nil { 62 | return []ARPEntry{}, fmt.Errorf("failed to parse ARP entry: %s", err) 63 | } 64 | entries = append(entries, entry) 65 | } else { 66 | return []ARPEntry{}, fmt.Errorf("%d columns were detected, but %d were expected", width, expectedDataWidth) 67 | } 68 | 69 | } 70 | 71 | return entries, err 72 | } 73 | 74 | func parseARPEntry(columns []string) (ARPEntry, error) { 75 | ip := net.ParseIP(columns[0]) 76 | mac := net.HardwareAddr(columns[3]) 77 | 78 | entry := ARPEntry{ 79 | IPAddr: ip, 80 | HWAddr: mac, 81 | Device: columns[5], 82 | } 83 | 84 | return entry, nil 85 | } 86 | -------------------------------------------------------------------------------- /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 | // BuddyInfo reads the buddyinfo statistics from the specified `proc` filesystem. 35 | func (fs FS) BuddyInfo() ([]BuddyInfo, error) { 36 | file, err := os.Open(fs.proc.Path("buddyinfo")) 37 | if err != nil { 38 | return nil, err 39 | } 40 | defer file.Close() 41 | 42 | return parseBuddyInfo(file) 43 | } 44 | 45 | func parseBuddyInfo(r io.Reader) ([]BuddyInfo, error) { 46 | var ( 47 | buddyInfo = []BuddyInfo{} 48 | scanner = bufio.NewScanner(r) 49 | bucketCount = -1 50 | ) 51 | 52 | for scanner.Scan() { 53 | var err error 54 | line := scanner.Text() 55 | parts := strings.Fields(line) 56 | 57 | if len(parts) < 4 { 58 | return nil, fmt.Errorf("invalid number of fields when parsing buddyinfo") 59 | } 60 | 61 | node := strings.TrimRight(parts[1], ",") 62 | zone := strings.TrimRight(parts[3], ",") 63 | arraySize := len(parts[4:]) 64 | 65 | if bucketCount == -1 { 66 | bucketCount = arraySize 67 | } else { 68 | if bucketCount != arraySize { 69 | return nil, fmt.Errorf("mismatch in number of buddyinfo buckets, previous count %d, new count %d", bucketCount, arraySize) 70 | } 71 | } 72 | 73 | sizes := make([]float64, arraySize) 74 | for i := 0; i < arraySize; i++ { 75 | sizes[i], err = strconv.ParseFloat(parts[i+4], 64) 76 | if err != nil { 77 | return nil, fmt.Errorf("invalid value in buddyinfo: %s", err) 78 | } 79 | } 80 | 81 | buddyInfo = append(buddyInfo, BuddyInfo{node, zone, sizes}) 82 | } 83 | 84 | return buddyInfo, scanner.Err() 85 | } 86 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/crypto.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | "bytes" 18 | "fmt" 19 | "io/ioutil" 20 | "strconv" 21 | "strings" 22 | 23 | "github.com/prometheus/procfs/internal/util" 24 | ) 25 | 26 | // Crypto holds info parsed from /proc/crypto. 27 | type Crypto struct { 28 | Alignmask *uint64 29 | Async bool 30 | Blocksize *uint64 31 | Chunksize *uint64 32 | Ctxsize *uint64 33 | Digestsize *uint64 34 | Driver string 35 | Geniv string 36 | Internal string 37 | Ivsize *uint64 38 | Maxauthsize *uint64 39 | MaxKeysize *uint64 40 | MinKeysize *uint64 41 | Module string 42 | Name string 43 | Priority *int64 44 | Refcnt *int64 45 | Seedsize *uint64 46 | Selftest string 47 | Type string 48 | Walksize *uint64 49 | } 50 | 51 | // Crypto parses an crypto-file (/proc/crypto) and returns a slice of 52 | // structs containing the relevant info. More information available here: 53 | // https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html 54 | func (fs FS) Crypto() ([]Crypto, error) { 55 | data, err := ioutil.ReadFile(fs.proc.Path("crypto")) 56 | if err != nil { 57 | return nil, fmt.Errorf("error parsing crypto %s: %s", fs.proc.Path("crypto"), err) 58 | } 59 | crypto, err := parseCrypto(data) 60 | if err != nil { 61 | return nil, fmt.Errorf("error parsing crypto %s: %s", fs.proc.Path("crypto"), err) 62 | } 63 | return crypto, nil 64 | } 65 | 66 | func parseCrypto(cryptoData []byte) ([]Crypto, error) { 67 | crypto := []Crypto{} 68 | 69 | cryptoBlocks := bytes.Split(cryptoData, []byte("\n\n")) 70 | 71 | for _, block := range cryptoBlocks { 72 | var newCryptoElem Crypto 73 | 74 | lines := strings.Split(string(block), "\n") 75 | for _, line := range lines { 76 | if strings.TrimSpace(line) == "" || line[0] == ' ' { 77 | continue 78 | } 79 | fields := strings.Split(line, ":") 80 | key := strings.TrimSpace(fields[0]) 81 | value := strings.TrimSpace(fields[1]) 82 | vp := util.NewValueParser(value) 83 | 84 | switch strings.TrimSpace(key) { 85 | case "async": 86 | b, err := strconv.ParseBool(value) 87 | if err == nil { 88 | newCryptoElem.Async = b 89 | } 90 | case "blocksize": 91 | newCryptoElem.Blocksize = vp.PUInt64() 92 | case "chunksize": 93 | newCryptoElem.Chunksize = vp.PUInt64() 94 | case "digestsize": 95 | newCryptoElem.Digestsize = vp.PUInt64() 96 | case "driver": 97 | newCryptoElem.Driver = value 98 | case "geniv": 99 | newCryptoElem.Geniv = value 100 | case "internal": 101 | newCryptoElem.Internal = value 102 | case "ivsize": 103 | newCryptoElem.Ivsize = vp.PUInt64() 104 | case "maxauthsize": 105 | newCryptoElem.Maxauthsize = vp.PUInt64() 106 | case "max keysize": 107 | newCryptoElem.MaxKeysize = vp.PUInt64() 108 | case "min keysize": 109 | newCryptoElem.MinKeysize = vp.PUInt64() 110 | case "module": 111 | newCryptoElem.Module = value 112 | case "name": 113 | newCryptoElem.Name = value 114 | case "priority": 115 | newCryptoElem.Priority = vp.PInt64() 116 | case "refcnt": 117 | newCryptoElem.Refcnt = vp.PInt64() 118 | case "seedsize": 119 | newCryptoElem.Seedsize = vp.PUInt64() 120 | case "selftest": 121 | newCryptoElem.Selftest = value 122 | case "type": 123 | newCryptoElem.Type = value 124 | case "walksize": 125 | newCryptoElem.Walksize = vp.PUInt64() 126 | } 127 | } 128 | crypto = append(crypto, newCryptoElem) 129 | } 130 | return crypto, nil 131 | } 132 | -------------------------------------------------------------------------------- /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/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 | "github.com/prometheus/procfs/internal/fs" 18 | ) 19 | 20 | // FS represents the pseudo-filesystem sys, which provides an interface to 21 | // kernel data structures. 22 | type FS struct { 23 | proc fs.FS 24 | } 25 | 26 | // DefaultMountPoint is the common mount point of the proc filesystem. 27 | const DefaultMountPoint = fs.DefaultProcMountPoint 28 | 29 | // NewDefaultFS returns a new proc FS mounted under the default proc mountPoint. 30 | // It will error if the mount point directory can't be read or is a file. 31 | func NewDefaultFS() (FS, error) { 32 | return NewFS(DefaultMountPoint) 33 | } 34 | 35 | // NewFS returns a new proc FS mounted under the given proc mountPoint. It will error 36 | // if the mount point directory can't be read or is a file. 37 | func NewFS(mountPoint string) (FS, error) { 38 | fs, err := fs.NewFS(mountPoint) 39 | if err != nil { 40 | return FS{}, err 41 | } 42 | return FS{fs}, nil 43 | } 44 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/prometheus/procfs 2 | 3 | require ( 4 | github.com/google/go-cmp v0.3.0 5 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 6 | ) 7 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= 2 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 3 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= 4 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 5 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/internal/fs/fs.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 fs 15 | 16 | import ( 17 | "fmt" 18 | "os" 19 | "path/filepath" 20 | ) 21 | 22 | const ( 23 | // DefaultProcMountPoint is the common mount point of the proc filesystem. 24 | DefaultProcMountPoint = "/proc" 25 | 26 | // DefaultSysMountPoint is the common mount point of the sys filesystem. 27 | DefaultSysMountPoint = "/sys" 28 | 29 | // DefaultConfigfsMountPoint is the common mount point of the configfs 30 | DefaultConfigfsMountPoint = "/sys/kernel/config" 31 | ) 32 | 33 | // FS represents a pseudo-filesystem, normally /proc or /sys, which provides an 34 | // interface to kernel data structures. 35 | type FS string 36 | 37 | // NewFS returns a new FS mounted under the given mountPoint. It will error 38 | // if the mount point can't be read. 39 | func NewFS(mountPoint string) (FS, error) { 40 | info, err := os.Stat(mountPoint) 41 | if err != nil { 42 | return "", fmt.Errorf("could not read %s: %s", mountPoint, err) 43 | } 44 | if !info.IsDir() { 45 | return "", fmt.Errorf("mount point %s is not a directory", mountPoint) 46 | } 47 | 48 | return FS(mountPoint), nil 49 | } 50 | 51 | // Path appends the given path elements to the filesystem path, adding separators 52 | // as necessary. 53 | func (fs FS) Path(p ...string) string { 54 | return filepath.Join(append([]string{string(fs)}, p...)...) 55 | } 56 | -------------------------------------------------------------------------------- /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 ( 17 | "io/ioutil" 18 | "strconv" 19 | "strings" 20 | ) 21 | 22 | // ParseUint32s parses a slice of strings into a slice of uint32s. 23 | func ParseUint32s(ss []string) ([]uint32, error) { 24 | us := make([]uint32, 0, len(ss)) 25 | for _, s := range ss { 26 | u, err := strconv.ParseUint(s, 10, 32) 27 | if err != nil { 28 | return nil, err 29 | } 30 | 31 | us = append(us, uint32(u)) 32 | } 33 | 34 | return us, nil 35 | } 36 | 37 | // ParseUint64s parses a slice of strings into a slice of uint64s. 38 | func ParseUint64s(ss []string) ([]uint64, error) { 39 | us := make([]uint64, 0, len(ss)) 40 | for _, s := range ss { 41 | u, err := strconv.ParseUint(s, 10, 64) 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | us = append(us, u) 47 | } 48 | 49 | return us, nil 50 | } 51 | 52 | // ParsePInt64s parses a slice of strings into a slice of int64 pointers. 53 | func ParsePInt64s(ss []string) ([]*int64, error) { 54 | us := make([]*int64, 0, len(ss)) 55 | for _, s := range ss { 56 | u, err := strconv.ParseInt(s, 10, 64) 57 | if err != nil { 58 | return nil, err 59 | } 60 | 61 | us = append(us, &u) 62 | } 63 | 64 | return us, nil 65 | } 66 | 67 | // ReadUintFromFile reads a file and attempts to parse a uint64 from it. 68 | func ReadUintFromFile(path string) (uint64, error) { 69 | data, err := ioutil.ReadFile(path) 70 | if err != nil { 71 | return 0, err 72 | } 73 | return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) 74 | } 75 | 76 | // ParseBool parses a string into a boolean pointer. 77 | func ParseBool(b string) *bool { 78 | var truth bool 79 | switch b { 80 | case "enabled": 81 | truth = true 82 | case "disabled": 83 | truth = false 84 | default: 85 | return nil 86 | } 87 | return &truth 88 | } 89 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/internal/util/sysreadfile.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 | // +build linux,!appengine 15 | 16 | package util 17 | 18 | import ( 19 | "bytes" 20 | "os" 21 | "syscall" 22 | ) 23 | 24 | // SysReadFile is a simplified ioutil.ReadFile that invokes syscall.Read directly. 25 | // https://github.com/prometheus/node_exporter/pull/728/files 26 | func SysReadFile(file string) (string, error) { 27 | f, err := os.Open(file) 28 | if err != nil { 29 | return "", err 30 | } 31 | defer f.Close() 32 | 33 | // On some machines, hwmon drivers are broken and return EAGAIN. This causes 34 | // Go's ioutil.ReadFile implementation to poll forever. 35 | // 36 | // Since we either want to read data or bail immediately, do the simplest 37 | // possible read using syscall directly. 38 | b := make([]byte, 128) 39 | n, err := syscall.Read(int(f.Fd()), b) 40 | if err != nil { 41 | return "", err 42 | } 43 | 44 | return string(bytes.TrimSpace(b[:n])), nil 45 | } 46 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 linux,appengine !linux 15 | 16 | package util 17 | 18 | import ( 19 | "fmt" 20 | ) 21 | 22 | // SysReadFile is here implemented as a noop for builds that do not support 23 | // the read syscall. For example Windows, or Linux on Google App Engine. 24 | func SysReadFile(file string) (string, error) { 25 | return "", fmt.Errorf("not supported on this platform") 26 | } 27 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/internal/util/valueparser.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 ( 17 | "strconv" 18 | ) 19 | 20 | // TODO(mdlayher): util packages are an anti-pattern and this should be moved 21 | // somewhere else that is more focused in the future. 22 | 23 | // A ValueParser enables parsing a single string into a variety of data types 24 | // in a concise and safe way. The Err method must be invoked after invoking 25 | // any other methods to ensure a value was successfully parsed. 26 | type ValueParser struct { 27 | v string 28 | err error 29 | } 30 | 31 | // NewValueParser creates a ValueParser using the input string. 32 | func NewValueParser(v string) *ValueParser { 33 | return &ValueParser{v: v} 34 | } 35 | 36 | // PInt64 interprets the underlying value as an int64 and returns a pointer to 37 | // that value. 38 | func (vp *ValueParser) PInt64() *int64 { 39 | if vp.err != nil { 40 | return nil 41 | } 42 | 43 | // A base value of zero makes ParseInt infer the correct base using the 44 | // string's prefix, if any. 45 | const base = 0 46 | v, err := strconv.ParseInt(vp.v, base, 64) 47 | if err != nil { 48 | vp.err = err 49 | return nil 50 | } 51 | 52 | return &v 53 | } 54 | 55 | // PUInt64 interprets the underlying value as an uint64 and returns a pointer to 56 | // that value. 57 | func (vp *ValueParser) PUInt64() *uint64 { 58 | if vp.err != nil { 59 | return nil 60 | } 61 | 62 | // A base value of zero makes ParseInt infer the correct base using the 63 | // string's prefix, if any. 64 | const base = 0 65 | v, err := strconv.ParseUint(vp.v, base, 64) 66 | if err != nil { 67 | vp.err = err 68 | return nil 69 | } 70 | 71 | return &v 72 | } 73 | 74 | // Err returns the last error, if any, encountered by the ValueParser. 75 | func (vp *ValueParser) Err() error { 76 | return vp.err 77 | } 78 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/net_softnet.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | "strconv" 20 | "strings" 21 | ) 22 | 23 | // For the proc file format details, 24 | // see https://elixir.bootlin.com/linux/v4.17/source/net/core/net-procfs.c#L162 25 | // and https://elixir.bootlin.com/linux/v4.17/source/include/linux/netdevice.h#L2810. 26 | 27 | // SoftnetEntry contains a single row of data from /proc/net/softnet_stat 28 | type SoftnetEntry struct { 29 | // Number of processed packets 30 | Processed uint 31 | // Number of dropped packets 32 | Dropped uint 33 | // Number of times processing packets ran out of quota 34 | TimeSqueezed uint 35 | } 36 | 37 | // GatherSoftnetStats reads /proc/net/softnet_stat, parse the relevant columns, 38 | // and then return a slice of SoftnetEntry's. 39 | func (fs FS) GatherSoftnetStats() ([]SoftnetEntry, error) { 40 | data, err := ioutil.ReadFile(fs.proc.Path("net/softnet_stat")) 41 | if err != nil { 42 | return nil, fmt.Errorf("error reading softnet %s: %s", fs.proc.Path("net/softnet_stat"), err) 43 | } 44 | 45 | return parseSoftnetEntries(data) 46 | } 47 | 48 | func parseSoftnetEntries(data []byte) ([]SoftnetEntry, error) { 49 | lines := strings.Split(string(data), "\n") 50 | entries := make([]SoftnetEntry, 0) 51 | var err error 52 | const ( 53 | expectedColumns = 11 54 | ) 55 | for _, line := range lines { 56 | columns := strings.Fields(line) 57 | width := len(columns) 58 | if width == 0 { 59 | continue 60 | } 61 | if width != expectedColumns { 62 | return []SoftnetEntry{}, fmt.Errorf("%d columns were detected, but %d were expected", width, expectedColumns) 63 | } 64 | var entry SoftnetEntry 65 | if entry, err = parseSoftnetEntry(columns); err != nil { 66 | return []SoftnetEntry{}, err 67 | } 68 | entries = append(entries, entry) 69 | } 70 | 71 | return entries, nil 72 | } 73 | 74 | func parseSoftnetEntry(columns []string) (SoftnetEntry, error) { 75 | var err error 76 | var processed, dropped, timeSqueezed uint64 77 | if processed, err = strconv.ParseUint(columns[0], 16, 32); err != nil { 78 | return SoftnetEntry{}, fmt.Errorf("Unable to parse column 0: %s", err) 79 | } 80 | if dropped, err = strconv.ParseUint(columns[1], 16, 32); err != nil { 81 | return SoftnetEntry{}, fmt.Errorf("Unable to parse column 1: %s", err) 82 | } 83 | if timeSqueezed, err = strconv.ParseUint(columns[2], 16, 32); err != nil { 84 | return SoftnetEntry{}, fmt.Errorf("Unable to parse column 2: %s", err) 85 | } 86 | return SoftnetEntry{ 87 | Processed: uint(processed), 88 | Dropped: uint(dropped), 89 | TimeSqueezed: uint(timeSqueezed), 90 | }, nil 91 | } 92 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/proc_environ.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | "io/ioutil" 18 | "os" 19 | "strings" 20 | ) 21 | 22 | // Environ reads process environments from /proc//environ 23 | func (p Proc) Environ() ([]string, error) { 24 | environments := make([]string, 0) 25 | 26 | f, err := os.Open(p.path("environ")) 27 | if err != nil { 28 | return environments, err 29 | } 30 | defer f.Close() 31 | 32 | data, err := ioutil.ReadAll(f) 33 | if err != nil { 34 | return environments, err 35 | } 36 | 37 | environments = strings.Split(string(data), "\000") 38 | if len(environments) > 0 { 39 | environments = environments[:len(environments)-1] 40 | } 41 | 42 | return environments, nil 43 | } 44 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/proc_fdinfo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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/ioutil" 20 | "os" 21 | "regexp" 22 | "strings" 23 | ) 24 | 25 | // Regexp variables 26 | var ( 27 | rPos = regexp.MustCompile(`^pos:\s+(\d+)$`) 28 | rFlags = regexp.MustCompile(`^flags:\s+(\d+)$`) 29 | rMntID = regexp.MustCompile(`^mnt_id:\s+(\d+)$`) 30 | rInotify = regexp.MustCompile(`^inotify`) 31 | ) 32 | 33 | // ProcFDInfo contains represents file descriptor information. 34 | type ProcFDInfo struct { 35 | // File descriptor 36 | FD string 37 | // File offset 38 | Pos string 39 | // File access mode and status flags 40 | Flags string 41 | // Mount point ID 42 | MntID string 43 | // List of inotify lines (structed) in the fdinfo file (kernel 3.8+ only) 44 | InotifyInfos []InotifyInfo 45 | } 46 | 47 | // FDInfo constructor. On kernels older than 3.8, InotifyInfos will always be empty. 48 | func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { 49 | f, err := os.Open(p.path("fdinfo", fd)) 50 | if err != nil { 51 | return nil, err 52 | } 53 | defer f.Close() 54 | 55 | fdinfo, err := ioutil.ReadAll(f) 56 | if err != nil { 57 | return nil, fmt.Errorf("could not read %s: %s", f.Name(), err) 58 | } 59 | 60 | var text, pos, flags, mntid string 61 | var inotify []InotifyInfo 62 | 63 | scanner := bufio.NewScanner(strings.NewReader(string(fdinfo))) 64 | for scanner.Scan() { 65 | text = scanner.Text() 66 | if rPos.MatchString(text) { 67 | pos = rPos.FindStringSubmatch(text)[1] 68 | } else if rFlags.MatchString(text) { 69 | flags = rFlags.FindStringSubmatch(text)[1] 70 | } else if rMntID.MatchString(text) { 71 | mntid = rMntID.FindStringSubmatch(text)[1] 72 | } else if rInotify.MatchString(text) { 73 | newInotify, err := parseInotifyInfo(text) 74 | if err != nil { 75 | return nil, err 76 | } 77 | inotify = append(inotify, *newInotify) 78 | } 79 | } 80 | 81 | i := &ProcFDInfo{ 82 | FD: fd, 83 | Pos: pos, 84 | Flags: flags, 85 | MntID: mntid, 86 | InotifyInfos: inotify, 87 | } 88 | 89 | return i, nil 90 | } 91 | 92 | // InotifyInfo represents a single inotify line in the fdinfo file. 93 | type InotifyInfo struct { 94 | // Watch descriptor number 95 | WD string 96 | // Inode number 97 | Ino string 98 | // Device ID 99 | Sdev string 100 | // Mask of events being monitored 101 | Mask string 102 | } 103 | 104 | // InotifyInfo constructor. Only available on kernel 3.8+. 105 | func parseInotifyInfo(line string) (*InotifyInfo, error) { 106 | r := regexp.MustCompile(`^inotify\s+wd:([0-9a-f]+)\s+ino:([0-9a-f]+)\s+sdev:([0-9a-f]+)\s+mask:([0-9a-f]+)`) 107 | m := r.FindStringSubmatch(line) 108 | i := &InotifyInfo{ 109 | WD: m[1], 110 | Ino: m[2], 111 | Sdev: m[3], 112 | Mask: m[4], 113 | } 114 | return i, nil 115 | } 116 | 117 | // ProcFDInfos represents a list of ProcFDInfo structs. 118 | type ProcFDInfos []ProcFDInfo 119 | 120 | func (p ProcFDInfos) Len() int { return len(p) } 121 | func (p ProcFDInfos) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 122 | func (p ProcFDInfos) Less(i, j int) bool { return p[i].FD < p[j].FD } 123 | 124 | // InotifyWatchLen returns the total number of inotify watches 125 | func (p ProcFDInfos) InotifyWatchLen() (int, error) { 126 | length := 0 127 | for _, f := range p { 128 | length += len(f.InotifyInfos) 129 | } 130 | 131 | return length, nil 132 | } 133 | -------------------------------------------------------------------------------- /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 | // IO creates a new ProcIO instance from a given Proc instance. 43 | func (p Proc) IO() (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 | -------------------------------------------------------------------------------- /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 | // Namespaces reads from /proc//ns/* to get the namespaces of which the 33 | // process is a member. 34 | func (p Proc) Namespaces() (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 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/proc_psi.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | // The PSI / pressure interface is described at 17 | // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/accounting/psi.txt 18 | // Each resource (cpu, io, memory, ...) is exposed as a single file. 19 | // Each file may contain up to two lines, one for "some" pressure and one for "full" pressure. 20 | // Each line contains several averages (over n seconds) and a total in µs. 21 | // 22 | // Example io pressure file: 23 | // > some avg10=0.06 avg60=0.21 avg300=0.99 total=8537362 24 | // > full avg10=0.00 avg60=0.13 avg300=0.96 total=8183134 25 | 26 | import ( 27 | "fmt" 28 | "io" 29 | "io/ioutil" 30 | "os" 31 | "strings" 32 | ) 33 | 34 | const lineFormat = "avg10=%f avg60=%f avg300=%f total=%d" 35 | 36 | // PSILine is a single line of values as returned by /proc/pressure/* 37 | // The Avg entries are averages over n seconds, as a percentage 38 | // The Total line is in microseconds 39 | type PSILine struct { 40 | Avg10 float64 41 | Avg60 float64 42 | Avg300 float64 43 | Total uint64 44 | } 45 | 46 | // PSIStats represent pressure stall information from /proc/pressure/* 47 | // Some indicates the share of time in which at least some tasks are stalled 48 | // Full indicates the share of time in which all non-idle tasks are stalled simultaneously 49 | type PSIStats struct { 50 | Some *PSILine 51 | Full *PSILine 52 | } 53 | 54 | // PSIStatsForResource reads pressure stall information for the specified 55 | // resource from /proc/pressure/. At time of writing this can be 56 | // either "cpu", "memory" or "io". 57 | func (fs FS) PSIStatsForResource(resource string) (PSIStats, error) { 58 | file, err := os.Open(fs.proc.Path(fmt.Sprintf("%s/%s", "pressure", resource))) 59 | if err != nil { 60 | return PSIStats{}, fmt.Errorf("psi_stats: unavailable for %s", resource) 61 | } 62 | 63 | defer file.Close() 64 | return parsePSIStats(resource, file) 65 | } 66 | 67 | // parsePSIStats parses the specified file for pressure stall information 68 | func parsePSIStats(resource string, file io.Reader) (PSIStats, error) { 69 | psiStats := PSIStats{} 70 | stats, err := ioutil.ReadAll(file) 71 | if err != nil { 72 | return psiStats, fmt.Errorf("psi_stats: unable to read data for %s", resource) 73 | } 74 | 75 | for _, l := range strings.Split(string(stats), "\n") { 76 | prefix := strings.Split(l, " ")[0] 77 | switch prefix { 78 | case "some": 79 | psi := PSILine{} 80 | _, err := fmt.Sscanf(l, fmt.Sprintf("some %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) 81 | if err != nil { 82 | return PSIStats{}, err 83 | } 84 | psiStats.Some = &psi 85 | case "full": 86 | psi := PSILine{} 87 | _, err := fmt.Sscanf(l, fmt.Sprintf("full %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) 88 | if err != nil { 89 | return PSIStats{}, err 90 | } 91 | psiStats.Full = &psi 92 | default: 93 | // If we encounter a line with an unknown prefix, ignore it and move on 94 | // Should new measurement types be added in the future we'll simply ignore them instead 95 | // of erroring on retrieval 96 | continue 97 | } 98 | } 99 | 100 | return psiStats, nil 101 | } 102 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/proc_status.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 | "bytes" 18 | "io/ioutil" 19 | "os" 20 | "strconv" 21 | "strings" 22 | ) 23 | 24 | // ProcStatus provides status information about the process, 25 | // read from /proc/[pid]/stat. 26 | type ProcStatus struct { 27 | // The process ID. 28 | PID int 29 | // The process name. 30 | Name string 31 | 32 | // Thread group ID. 33 | TGID int 34 | 35 | // Peak virtual memory size. 36 | VmPeak uint64 37 | // Virtual memory size. 38 | VmSize uint64 39 | // Locked memory size. 40 | VmLck uint64 41 | // Pinned memory size. 42 | VmPin uint64 43 | // Peak resident set size. 44 | VmHWM uint64 45 | // Resident set size (sum of RssAnnon RssFile and RssShmem). 46 | VmRSS uint64 47 | // Size of resident anonymous memory. 48 | RssAnon uint64 49 | // Size of resident file mappings. 50 | RssFile uint64 51 | // Size of resident shared memory. 52 | RssShmem uint64 53 | // Size of data segments. 54 | VmData uint64 55 | // Size of stack segments. 56 | VmStk uint64 57 | // Size of text segments. 58 | VmExe uint64 59 | // Shared library code size. 60 | VmLib uint64 61 | // Page table entries size. 62 | VmPTE uint64 63 | // Size of second-level page tables. 64 | VmPMD uint64 65 | // Swapped-out virtual memory size by anonymous private. 66 | VmSwap uint64 67 | // Size of hugetlb memory portions 68 | HugetlbPages uint64 69 | 70 | // Number of voluntary context switches. 71 | VoluntaryCtxtSwitches uint64 72 | // Number of involuntary context switches. 73 | NonVoluntaryCtxtSwitches uint64 74 | } 75 | 76 | // NewStatus returns the current status information of the process. 77 | func (p Proc) NewStatus() (ProcStatus, error) { 78 | f, err := os.Open(p.path("status")) 79 | if err != nil { 80 | return ProcStatus{}, err 81 | } 82 | defer f.Close() 83 | 84 | data, err := ioutil.ReadAll(f) 85 | if err != nil { 86 | return ProcStatus{}, err 87 | } 88 | 89 | s := ProcStatus{PID: p.PID} 90 | 91 | lines := strings.Split(string(data), "\n") 92 | for _, line := range lines { 93 | if !bytes.Contains([]byte(line), []byte(":")) { 94 | continue 95 | } 96 | 97 | kv := strings.SplitN(line, ":", 2) 98 | 99 | // removes spaces 100 | k := string(strings.TrimSpace(kv[0])) 101 | v := string(strings.TrimSpace(kv[1])) 102 | // removes "kB" 103 | v = string(bytes.Trim([]byte(v), " kB")) 104 | 105 | // value to int when possible 106 | // we can skip error check here, 'cause vKBytes is not used when value is a string 107 | vKBytes, _ := strconv.ParseUint(v, 10, 64) 108 | // convert kB to B 109 | vBytes := vKBytes * 1024 110 | 111 | s.fillStatus(k, v, vKBytes, vBytes) 112 | } 113 | 114 | return s, nil 115 | } 116 | 117 | func (s *ProcStatus) fillStatus(k string, vString string, vUint uint64, vUintBytes uint64) { 118 | switch k { 119 | case "Tgid": 120 | s.TGID = int(vUint) 121 | case "Name": 122 | s.Name = vString 123 | case "VmPeak": 124 | s.VmPeak = vUintBytes 125 | case "VmSize": 126 | s.VmSize = vUintBytes 127 | case "VmLck": 128 | s.VmLck = vUintBytes 129 | case "VmPin": 130 | s.VmPin = vUintBytes 131 | case "VmHWM": 132 | s.VmHWM = vUintBytes 133 | case "VmRSS": 134 | s.VmRSS = vUintBytes 135 | case "RssAnon": 136 | s.RssAnon = vUintBytes 137 | case "RssFile": 138 | s.RssFile = vUintBytes 139 | case "RssShmem": 140 | s.RssShmem = vUintBytes 141 | case "VmData": 142 | s.VmData = vUintBytes 143 | case "VmStk": 144 | s.VmStk = vUintBytes 145 | case "VmExe": 146 | s.VmExe = vUintBytes 147 | case "VmLib": 148 | s.VmLib = vUintBytes 149 | case "VmPTE": 150 | s.VmPTE = vUintBytes 151 | case "VmPMD": 152 | s.VmPMD = vUintBytes 153 | case "VmSwap": 154 | s.VmSwap = vUintBytes 155 | case "HugetlbPages": 156 | s.HugetlbPages = vUintBytes 157 | case "voluntary_ctxt_switches": 158 | s.VoluntaryCtxtSwitches = vUint 159 | case "nonvoluntary_ctxt_switches": 160 | s.NonVoluntaryCtxtSwitches = vUint 161 | } 162 | } 163 | 164 | // TotalCtxtSwitches returns the total context switch. 165 | func (s ProcStatus) TotalCtxtSwitches() uint64 { 166 | return s.VoluntaryCtxtSwitches + s.NonVoluntaryCtxtSwitches 167 | } 168 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/schedstat.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | "errors" 19 | "os" 20 | "regexp" 21 | "strconv" 22 | ) 23 | 24 | var ( 25 | cpuLineRE = regexp.MustCompile(`cpu(\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+)`) 26 | procLineRE = regexp.MustCompile(`(\d+) (\d+) (\d+)`) 27 | ) 28 | 29 | // Schedstat contains scheduler statistics from /proc/schedstat 30 | // 31 | // See 32 | // https://www.kernel.org/doc/Documentation/scheduler/sched-stats.txt 33 | // for a detailed description of what these numbers mean. 34 | // 35 | // Note the current kernel documentation claims some of the time units are in 36 | // jiffies when they are actually in nanoseconds since 2.6.23 with the 37 | // introduction of CFS. A fix to the documentation is pending. See 38 | // https://lore.kernel.org/patchwork/project/lkml/list/?series=403473 39 | type Schedstat struct { 40 | CPUs []*SchedstatCPU 41 | } 42 | 43 | // SchedstatCPU contains the values from one "cpu" line 44 | type SchedstatCPU struct { 45 | CPUNum string 46 | 47 | RunningNanoseconds uint64 48 | WaitingNanoseconds uint64 49 | RunTimeslices uint64 50 | } 51 | 52 | // ProcSchedstat contains the values from /proc//schedstat 53 | type ProcSchedstat struct { 54 | RunningNanoseconds uint64 55 | WaitingNanoseconds uint64 56 | RunTimeslices uint64 57 | } 58 | 59 | // Schedstat reads data from /proc/schedstat 60 | func (fs FS) Schedstat() (*Schedstat, error) { 61 | file, err := os.Open(fs.proc.Path("schedstat")) 62 | if err != nil { 63 | return nil, err 64 | } 65 | defer file.Close() 66 | 67 | stats := &Schedstat{} 68 | scanner := bufio.NewScanner(file) 69 | 70 | for scanner.Scan() { 71 | match := cpuLineRE.FindStringSubmatch(scanner.Text()) 72 | if match != nil { 73 | cpu := &SchedstatCPU{} 74 | cpu.CPUNum = match[1] 75 | 76 | cpu.RunningNanoseconds, err = strconv.ParseUint(match[8], 10, 64) 77 | if err != nil { 78 | continue 79 | } 80 | 81 | cpu.WaitingNanoseconds, err = strconv.ParseUint(match[9], 10, 64) 82 | if err != nil { 83 | continue 84 | } 85 | 86 | cpu.RunTimeslices, err = strconv.ParseUint(match[10], 10, 64) 87 | if err != nil { 88 | continue 89 | } 90 | 91 | stats.CPUs = append(stats.CPUs, cpu) 92 | } 93 | } 94 | 95 | return stats, nil 96 | } 97 | 98 | func parseProcSchedstat(contents string) (stats ProcSchedstat, err error) { 99 | match := procLineRE.FindStringSubmatch(contents) 100 | 101 | if match != nil { 102 | stats.RunningNanoseconds, err = strconv.ParseUint(match[1], 10, 64) 103 | if err != nil { 104 | return 105 | } 106 | 107 | stats.WaitingNanoseconds, err = strconv.ParseUint(match[2], 10, 64) 108 | if err != nil { 109 | return 110 | } 111 | 112 | stats.RunTimeslices, err = strconv.ParseUint(match[3], 10, 64) 113 | return 114 | } 115 | 116 | err = errors.New("could not parse schedstat") 117 | return 118 | } 119 | -------------------------------------------------------------------------------- /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/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/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/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/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 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/asm_windows_arm.s: -------------------------------------------------------------------------------- 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 | #include "textflag.h" 6 | 7 | TEXT ·getprocaddress(SB),NOSPLIT,$0 8 | B syscall·getprocaddress(SB) 9 | 10 | TEXT ·loadlibrary(SB),NOSPLIT,$0 11 | B syscall·loadlibrary(SB) 12 | -------------------------------------------------------------------------------- /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 ( 10 | "syscall" 11 | "unicode/utf16" 12 | "unsafe" 13 | ) 14 | 15 | func Getenv(key string) (value string, found bool) { 16 | return syscall.Getenv(key) 17 | } 18 | 19 | func Setenv(key, value string) error { 20 | return syscall.Setenv(key, value) 21 | } 22 | 23 | func Clearenv() { 24 | syscall.Clearenv() 25 | } 26 | 27 | func Environ() []string { 28 | return syscall.Environ() 29 | } 30 | 31 | // Returns a default environment associated with the token, rather than the current 32 | // process. If inheritExisting is true, then this environment also inherits the 33 | // environment of the current process. 34 | func (token Token) Environ(inheritExisting bool) (env []string, err error) { 35 | var block *uint16 36 | err = CreateEnvironmentBlock(&block, token, inheritExisting) 37 | if err != nil { 38 | return nil, err 39 | } 40 | defer DestroyEnvironmentBlock(block) 41 | blockp := uintptr(unsafe.Pointer(block)) 42 | for { 43 | entry := (*[(1 << 30) - 1]uint16)(unsafe.Pointer(blockp))[:] 44 | for i, v := range entry { 45 | if v == 0 { 46 | entry = entry[:i] 47 | break 48 | } 49 | } 50 | if len(entry) == 0 { 51 | break 52 | } 53 | env = append(env, string(utf16.Decode(entry))) 54 | blockp += 2 * (uintptr(len(entry)) + 1) 55 | } 56 | return env, nil 57 | } 58 | 59 | func Unsetenv(key string) error { 60 | return syscall.Unsetenv(key) 61 | } 62 | -------------------------------------------------------------------------------- /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/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/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/mkerrors.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2019 The Go Authors. All rights reserved. 4 | # Use of this source code is governed by a BSD-style 5 | # license that can be found in the LICENSE file. 6 | 7 | set -e 8 | shopt -s nullglob 9 | 10 | winerror="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/shared/winerror.h | sort -Vr | head -n 1)" 11 | [[ -n $winerror ]] || { echo "Unable to find winerror.h" >&2; exit 1; } 12 | 13 | declare -A errors 14 | 15 | { 16 | echo "// Code generated by 'mkerrors.bash'; DO NOT EDIT." 17 | echo 18 | echo "package windows" 19 | echo "import \"syscall\"" 20 | echo "const (" 21 | 22 | while read -r line; do 23 | unset vtype 24 | if [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?([A-Z][A-Z0-9_]+k?)\)? ]]; then 25 | key="${BASH_REMATCH[1]}" 26 | value="${BASH_REMATCH[3]}" 27 | elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?((0x)?[0-9A-Fa-f]+)L?\)? ]]; then 28 | key="${BASH_REMATCH[1]}" 29 | value="${BASH_REMATCH[3]}" 30 | vtype="${BASH_REMATCH[2]}" 31 | elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +\(\(([A-Z]+)\)((0x)?[0-9A-Fa-f]+)L?\) ]]; then 32 | key="${BASH_REMATCH[1]}" 33 | value="${BASH_REMATCH[3]}" 34 | vtype="${BASH_REMATCH[2]}" 35 | else 36 | continue 37 | fi 38 | [[ -n $key && -n $value ]] || continue 39 | [[ -z ${errors["$key"]} ]] || continue 40 | errors["$key"]="$value" 41 | if [[ -v vtype ]]; then 42 | if [[ $key == FACILITY_* || $key == NO_ERROR ]]; then 43 | vtype="" 44 | elif [[ $vtype == *HANDLE* || $vtype == *HRESULT* ]]; then 45 | vtype="Handle" 46 | else 47 | vtype="syscall.Errno" 48 | fi 49 | last_vtype="$vtype" 50 | else 51 | vtype="" 52 | if [[ $last_vtype == Handle && $value == NO_ERROR ]]; then 53 | value="S_OK" 54 | elif [[ $last_vtype == syscall.Errno && $value == NO_ERROR ]]; then 55 | value="ERROR_SUCCESS" 56 | fi 57 | fi 58 | 59 | echo "$key $vtype = $value" 60 | done < "$winerror" 61 | 62 | echo ")" 63 | } | gofmt > "zerrors_windows.go" 64 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/mkknownfolderids.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2019 The Go Authors. All rights reserved. 4 | # Use of this source code is governed by a BSD-style 5 | # license that can be found in the LICENSE file. 6 | 7 | set -e 8 | shopt -s nullglob 9 | 10 | knownfolders="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/um/KnownFolders.h | sort -Vr | head -n 1)" 11 | [[ -n $knownfolders ]] || { echo "Unable to find KnownFolders.h" >&2; exit 1; } 12 | 13 | { 14 | echo "// Code generated by 'mkknownfolderids.bash'; DO NOT EDIT." 15 | echo 16 | echo "package windows" 17 | echo "type KNOWNFOLDERID GUID" 18 | echo "var (" 19 | while read -r line; do 20 | [[ $line =~ DEFINE_KNOWN_FOLDER\((FOLDERID_[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+)\) ]] || continue 21 | printf "%s = &KNOWNFOLDERID{0x%08x, 0x%04x, 0x%04x, [8]byte{0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x}}\n" \ 22 | "${BASH_REMATCH[1]}" $(( "${BASH_REMATCH[2]}" )) $(( "${BASH_REMATCH[3]}" )) $(( "${BASH_REMATCH[4]}" )) \ 23 | $(( "${BASH_REMATCH[5]}" )) $(( "${BASH_REMATCH[6]}" )) $(( "${BASH_REMATCH[7]}" )) $(( "${BASH_REMATCH[8]}" )) \ 24 | $(( "${BASH_REMATCH[9]}" )) $(( "${BASH_REMATCH[10]}" )) $(( "${BASH_REMATCH[11]}" )) $(( "${BASH_REMATCH[12]}" )) 25 | done < "$knownfolders" 26 | echo ")" 27 | } | gofmt > "zknownfolderids_windows.go" 28 | -------------------------------------------------------------------------------- /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 | // +build generate 6 | 7 | package windows 8 | 9 | //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/types_windows_arm.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 | 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/gopkg.in/alecthomas/kingpin.v2/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: go 3 | install: go get -t -v ./... 4 | go: 1.2 5 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (C) 2014 Alec Thomas 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/actions.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | // Action callback executed at various stages after all values are populated. 4 | // The application, commands, arguments and flags all have corresponding 5 | // actions. 6 | type Action func(*ParseContext) error 7 | 8 | type actionMixin struct { 9 | actions []Action 10 | preActions []Action 11 | } 12 | 13 | type actionApplier interface { 14 | applyActions(*ParseContext) error 15 | applyPreActions(*ParseContext) error 16 | } 17 | 18 | func (a *actionMixin) addAction(action Action) { 19 | a.actions = append(a.actions, action) 20 | } 21 | 22 | func (a *actionMixin) addPreAction(action Action) { 23 | a.preActions = append(a.preActions, action) 24 | } 25 | 26 | func (a *actionMixin) applyActions(context *ParseContext) error { 27 | for _, action := range a.actions { 28 | if err := action(context); err != nil { 29 | return err 30 | } 31 | } 32 | return nil 33 | } 34 | 35 | func (a *actionMixin) applyPreActions(context *ParseContext) error { 36 | for _, preAction := range a.preActions { 37 | if err := preAction(context); err != nil { 38 | return err 39 | } 40 | } 41 | return nil 42 | } 43 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/args.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type argGroup struct { 8 | args []*ArgClause 9 | } 10 | 11 | func newArgGroup() *argGroup { 12 | return &argGroup{} 13 | } 14 | 15 | func (a *argGroup) have() bool { 16 | return len(a.args) > 0 17 | } 18 | 19 | // GetArg gets an argument definition. 20 | // 21 | // This allows existing arguments to be modified after definition but before parsing. Useful for 22 | // modular applications. 23 | func (a *argGroup) GetArg(name string) *ArgClause { 24 | for _, arg := range a.args { 25 | if arg.name == name { 26 | return arg 27 | } 28 | } 29 | return nil 30 | } 31 | 32 | func (a *argGroup) Arg(name, help string) *ArgClause { 33 | arg := newArg(name, help) 34 | a.args = append(a.args, arg) 35 | return arg 36 | } 37 | 38 | func (a *argGroup) init() error { 39 | required := 0 40 | seen := map[string]struct{}{} 41 | previousArgMustBeLast := false 42 | for i, arg := range a.args { 43 | if previousArgMustBeLast { 44 | return fmt.Errorf("Args() can't be followed by another argument '%s'", arg.name) 45 | } 46 | if arg.consumesRemainder() { 47 | previousArgMustBeLast = true 48 | } 49 | if _, ok := seen[arg.name]; ok { 50 | return fmt.Errorf("duplicate argument '%s'", arg.name) 51 | } 52 | seen[arg.name] = struct{}{} 53 | if arg.required && required != i { 54 | return fmt.Errorf("required arguments found after non-required") 55 | } 56 | if arg.required { 57 | required++ 58 | } 59 | if err := arg.init(); err != nil { 60 | return err 61 | } 62 | } 63 | return nil 64 | } 65 | 66 | type ArgClause struct { 67 | actionMixin 68 | parserMixin 69 | completionsMixin 70 | envarMixin 71 | name string 72 | help string 73 | defaultValues []string 74 | required bool 75 | } 76 | 77 | func newArg(name, help string) *ArgClause { 78 | a := &ArgClause{ 79 | name: name, 80 | help: help, 81 | } 82 | return a 83 | } 84 | 85 | func (a *ArgClause) setDefault() error { 86 | if a.HasEnvarValue() { 87 | if v, ok := a.value.(remainderArg); !ok || !v.IsCumulative() { 88 | // Use the value as-is 89 | return a.value.Set(a.GetEnvarValue()) 90 | } 91 | for _, value := range a.GetSplitEnvarValue() { 92 | if err := a.value.Set(value); err != nil { 93 | return err 94 | } 95 | } 96 | return nil 97 | } 98 | 99 | if len(a.defaultValues) > 0 { 100 | for _, defaultValue := range a.defaultValues { 101 | if err := a.value.Set(defaultValue); err != nil { 102 | return err 103 | } 104 | } 105 | return nil 106 | } 107 | 108 | return nil 109 | } 110 | 111 | func (a *ArgClause) needsValue() bool { 112 | haveDefault := len(a.defaultValues) > 0 113 | return a.required && !(haveDefault || a.HasEnvarValue()) 114 | } 115 | 116 | func (a *ArgClause) consumesRemainder() bool { 117 | if r, ok := a.value.(remainderArg); ok { 118 | return r.IsCumulative() 119 | } 120 | return false 121 | } 122 | 123 | // Required arguments must be input by the user. They can not have a Default() value provided. 124 | func (a *ArgClause) Required() *ArgClause { 125 | a.required = true 126 | return a 127 | } 128 | 129 | // Default values for this argument. They *must* be parseable by the value of the argument. 130 | func (a *ArgClause) Default(values ...string) *ArgClause { 131 | a.defaultValues = values 132 | return a 133 | } 134 | 135 | // Envar overrides the default value(s) for a flag from an environment variable, 136 | // if it is set. Several default values can be provided by using new lines to 137 | // separate them. 138 | func (a *ArgClause) Envar(name string) *ArgClause { 139 | a.envar = name 140 | a.noEnvar = false 141 | return a 142 | } 143 | 144 | // NoEnvar forces environment variable defaults to be disabled for this flag. 145 | // Most useful in conjunction with app.DefaultEnvars(). 146 | func (a *ArgClause) NoEnvar() *ArgClause { 147 | a.envar = "" 148 | a.noEnvar = true 149 | return a 150 | } 151 | 152 | func (a *ArgClause) Action(action Action) *ArgClause { 153 | a.addAction(action) 154 | return a 155 | } 156 | 157 | func (a *ArgClause) PreAction(action Action) *ArgClause { 158 | a.addPreAction(action) 159 | return a 160 | } 161 | 162 | // HintAction registers a HintAction (function) for the arg to provide completions 163 | func (a *ArgClause) HintAction(action HintAction) *ArgClause { 164 | a.addHintAction(action) 165 | return a 166 | } 167 | 168 | // HintOptions registers any number of options for the flag to provide completions 169 | func (a *ArgClause) HintOptions(options ...string) *ArgClause { 170 | a.addHintAction(func() []string { 171 | return options 172 | }) 173 | return a 174 | } 175 | 176 | func (a *ArgClause) init() error { 177 | if a.required && len(a.defaultValues) > 0 { 178 | return fmt.Errorf("required argument '%s' with unusable default value", a.name) 179 | } 180 | if a.value == nil { 181 | return fmt.Errorf("no parser defined for arg '%s'", a.name) 182 | } 183 | return nil 184 | } 185 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/completions.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | // HintAction is a function type who is expected to return a slice of possible 4 | // command line arguments. 5 | type HintAction func() []string 6 | type completionsMixin struct { 7 | hintActions []HintAction 8 | builtinHintActions []HintAction 9 | } 10 | 11 | func (a *completionsMixin) addHintAction(action HintAction) { 12 | a.hintActions = append(a.hintActions, action) 13 | } 14 | 15 | // Allow adding of HintActions which are added internally, ie, EnumVar 16 | func (a *completionsMixin) addHintActionBuiltin(action HintAction) { 17 | a.builtinHintActions = append(a.builtinHintActions, action) 18 | } 19 | 20 | func (a *completionsMixin) resolveCompletions() []string { 21 | var hints []string 22 | 23 | options := a.builtinHintActions 24 | if len(a.hintActions) > 0 { 25 | // User specified their own hintActions. Use those instead. 26 | options = a.hintActions 27 | } 28 | 29 | for _, hintAction := range options { 30 | hints = append(hints, hintAction()...) 31 | } 32 | return hints 33 | } 34 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/doc.go: -------------------------------------------------------------------------------- 1 | // Package kingpin provides command line interfaces like this: 2 | // 3 | // $ chat 4 | // usage: chat [] [] [ ...] 5 | // 6 | // Flags: 7 | // --debug enable debug mode 8 | // --help Show help. 9 | // --server=127.0.0.1 server address 10 | // 11 | // Commands: 12 | // help 13 | // Show help for a command. 14 | // 15 | // post [] 16 | // Post a message to a channel. 17 | // 18 | // register 19 | // Register a new user. 20 | // 21 | // $ chat help post 22 | // usage: chat [] post [] [] 23 | // 24 | // Post a message to a channel. 25 | // 26 | // Flags: 27 | // --image=IMAGE image to post 28 | // 29 | // Args: 30 | // channel to post to 31 | // [] text to post 32 | // $ chat post --image=~/Downloads/owls.jpg pics 33 | // 34 | // From code like this: 35 | // 36 | // package main 37 | // 38 | // import "gopkg.in/alecthomas/kingpin.v2" 39 | // 40 | // var ( 41 | // debug = kingpin.Flag("debug", "enable debug mode").Default("false").Bool() 42 | // serverIP = kingpin.Flag("server", "server address").Default("127.0.0.1").IP() 43 | // 44 | // register = kingpin.Command("register", "Register a new user.") 45 | // registerNick = register.Arg("nick", "nickname for user").Required().String() 46 | // registerName = register.Arg("name", "name of user").Required().String() 47 | // 48 | // post = kingpin.Command("post", "Post a message to a channel.") 49 | // postImage = post.Flag("image", "image to post").ExistingFile() 50 | // postChannel = post.Arg("channel", "channel to post to").Required().String() 51 | // postText = post.Arg("text", "text to post").String() 52 | // ) 53 | // 54 | // func main() { 55 | // switch kingpin.Parse() { 56 | // // Register user 57 | // case "register": 58 | // println(*registerNick) 59 | // 60 | // // Post message 61 | // case "post": 62 | // if *postImage != nil { 63 | // } 64 | // if *postText != "" { 65 | // } 66 | // } 67 | // } 68 | package kingpin 69 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/envar.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "os" 5 | "regexp" 6 | ) 7 | 8 | var ( 9 | envVarValuesSeparator = "\r?\n" 10 | envVarValuesTrimmer = regexp.MustCompile(envVarValuesSeparator + "$") 11 | envVarValuesSplitter = regexp.MustCompile(envVarValuesSeparator) 12 | ) 13 | 14 | type envarMixin struct { 15 | envar string 16 | noEnvar bool 17 | } 18 | 19 | func (e *envarMixin) HasEnvarValue() bool { 20 | return e.GetEnvarValue() != "" 21 | } 22 | 23 | func (e *envarMixin) GetEnvarValue() string { 24 | if e.noEnvar || e.envar == "" { 25 | return "" 26 | } 27 | return os.Getenv(e.envar) 28 | } 29 | 30 | func (e *envarMixin) GetSplitEnvarValue() []string { 31 | values := make([]string, 0) 32 | 33 | envarValue := e.GetEnvarValue() 34 | if envarValue == "" { 35 | return values 36 | } 37 | 38 | // Split by new line to extract multiple values, if any. 39 | trimmed := envVarValuesTrimmer.ReplaceAllString(envarValue, "") 40 | for _, value := range envVarValuesSplitter.Split(trimmed, -1) { 41 | values = append(values, value) 42 | } 43 | 44 | return values 45 | } 46 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/global.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | ) 7 | 8 | var ( 9 | // CommandLine is the default Kingpin parser. 10 | CommandLine = New(filepath.Base(os.Args[0]), "") 11 | // Global help flag. Exposed for user customisation. 12 | HelpFlag = CommandLine.HelpFlag 13 | // Top-level help command. Exposed for user customisation. May be nil. 14 | HelpCommand = CommandLine.HelpCommand 15 | // Global version flag. Exposed for user customisation. May be nil. 16 | VersionFlag = CommandLine.VersionFlag 17 | ) 18 | 19 | // Command adds a new command to the default parser. 20 | func Command(name, help string) *CmdClause { 21 | return CommandLine.Command(name, help) 22 | } 23 | 24 | // Flag adds a new flag to the default parser. 25 | func Flag(name, help string) *FlagClause { 26 | return CommandLine.Flag(name, help) 27 | } 28 | 29 | // Arg adds a new argument to the top-level of the default parser. 30 | func Arg(name, help string) *ArgClause { 31 | return CommandLine.Arg(name, help) 32 | } 33 | 34 | // Parse and return the selected command. Will call the termination handler if 35 | // an error is encountered. 36 | func Parse() string { 37 | selected := MustParse(CommandLine.Parse(os.Args[1:])) 38 | if selected == "" && CommandLine.cmdGroup.have() { 39 | Usage() 40 | CommandLine.terminate(0) 41 | } 42 | return selected 43 | } 44 | 45 | // Errorf prints an error message to stderr. 46 | func Errorf(format string, args ...interface{}) { 47 | CommandLine.Errorf(format, args...) 48 | } 49 | 50 | // Fatalf prints an error message to stderr and exits. 51 | func Fatalf(format string, args ...interface{}) { 52 | CommandLine.Fatalf(format, args...) 53 | } 54 | 55 | // FatalIfError prints an error and exits if err is not nil. The error is printed 56 | // with the given prefix. 57 | func FatalIfError(err error, format string, args ...interface{}) { 58 | CommandLine.FatalIfError(err, format, args...) 59 | } 60 | 61 | // FatalUsage prints an error message followed by usage information, then 62 | // exits with a non-zero status. 63 | func FatalUsage(format string, args ...interface{}) { 64 | CommandLine.FatalUsage(format, args...) 65 | } 66 | 67 | // FatalUsageContext writes a printf formatted error message to stderr, then 68 | // usage information for the given ParseContext, before exiting. 69 | func FatalUsageContext(context *ParseContext, format string, args ...interface{}) { 70 | CommandLine.FatalUsageContext(context, format, args...) 71 | } 72 | 73 | // Usage prints usage to stderr. 74 | func Usage() { 75 | CommandLine.Usage(os.Args[1:]) 76 | } 77 | 78 | // Set global usage template to use (defaults to DefaultUsageTemplate). 79 | func UsageTemplate(template string) *Application { 80 | return CommandLine.UsageTemplate(template) 81 | } 82 | 83 | // MustParse can be used with app.Parse(args) to exit with an error if parsing fails. 84 | func MustParse(command string, err error) string { 85 | if err != nil { 86 | Fatalf("%s, try --help", err) 87 | } 88 | return command 89 | } 90 | 91 | // Version adds a flag for displaying the application version number. 92 | func Version(version string) *Application { 93 | return CommandLine.Version(version) 94 | } 95 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/guesswidth.go: -------------------------------------------------------------------------------- 1 | // +build appengine !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd 2 | 3 | package kingpin 4 | 5 | import "io" 6 | 7 | func guessWidth(w io.Writer) int { 8 | return 80 9 | } 10 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/guesswidth_unix.go: -------------------------------------------------------------------------------- 1 | // +build !appengine,linux freebsd darwin dragonfly netbsd openbsd 2 | 3 | package kingpin 4 | 5 | import ( 6 | "io" 7 | "os" 8 | "strconv" 9 | "syscall" 10 | "unsafe" 11 | ) 12 | 13 | func guessWidth(w io.Writer) int { 14 | // check if COLUMNS env is set to comply with 15 | // http://pubs.opengroup.org/onlinepubs/009604499/basedefs/xbd_chap08.html 16 | colsStr := os.Getenv("COLUMNS") 17 | if colsStr != "" { 18 | if cols, err := strconv.Atoi(colsStr); err == nil { 19 | return cols 20 | } 21 | } 22 | 23 | if t, ok := w.(*os.File); ok { 24 | fd := t.Fd() 25 | var dimensions [4]uint16 26 | 27 | if _, _, err := syscall.Syscall6( 28 | syscall.SYS_IOCTL, 29 | uintptr(fd), 30 | uintptr(syscall.TIOCGWINSZ), 31 | uintptr(unsafe.Pointer(&dimensions)), 32 | 0, 0, 0, 33 | ); err == 0 { 34 | return int(dimensions[1]) 35 | } 36 | } 37 | return 80 38 | } 39 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/values.json: -------------------------------------------------------------------------------- 1 | [ 2 | {"type": "bool", "parser": "strconv.ParseBool(s)"}, 3 | {"type": "string", "parser": "s, error(nil)", "format": "string(*f.v)", "plural": "Strings"}, 4 | {"type": "uint", "parser": "strconv.ParseUint(s, 0, 64)", "plural": "Uints"}, 5 | {"type": "uint8", "parser": "strconv.ParseUint(s, 0, 8)"}, 6 | {"type": "uint16", "parser": "strconv.ParseUint(s, 0, 16)"}, 7 | {"type": "uint32", "parser": "strconv.ParseUint(s, 0, 32)"}, 8 | {"type": "uint64", "parser": "strconv.ParseUint(s, 0, 64)"}, 9 | {"type": "int", "parser": "strconv.ParseFloat(s, 64)", "plural": "Ints"}, 10 | {"type": "int8", "parser": "strconv.ParseInt(s, 0, 8)"}, 11 | {"type": "int16", "parser": "strconv.ParseInt(s, 0, 16)"}, 12 | {"type": "int32", "parser": "strconv.ParseInt(s, 0, 32)"}, 13 | {"type": "int64", "parser": "strconv.ParseInt(s, 0, 64)"}, 14 | {"type": "float64", "parser": "strconv.ParseFloat(s, 64)"}, 15 | {"type": "float32", "parser": "strconv.ParseFloat(s, 32)"}, 16 | {"name": "Duration", "type": "time.Duration", "no_value_parser": true}, 17 | {"name": "IP", "type": "net.IP", "no_value_parser": true}, 18 | {"name": "TCPAddr", "Type": "*net.TCPAddr", "plural": "TCPList", "no_value_parser": true}, 19 | {"name": "ExistingFile", "Type": "string", "plural": "ExistingFiles", "no_value_parser": true}, 20 | {"name": "ExistingDir", "Type": "string", "plural": "ExistingDirs", "no_value_parser": true}, 21 | {"name": "ExistingFileOrDir", "Type": "string", "plural": "ExistingFilesOrDirs", "no_value_parser": true}, 22 | {"name": "Regexp", "Type": "*regexp.Regexp", "parser": "regexp.Compile(s)"}, 23 | {"name": "ResolvedIP", "Type": "net.IP", "parser": "resolveHost(s)", "help": "Resolve a hostname or IP to an IP."}, 24 | {"name": "HexBytes", "Type": "[]byte", "parser": "hex.DecodeString(s)", "help": "Bytes as a hex string."} 25 | ] 26 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.4 5 | - 1.5 6 | - 1.6 7 | - 1.7 8 | - 1.8 9 | - 1.9 10 | - tip 11 | 12 | go_import_path: gopkg.in/yaml.v2 13 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/LICENSE.libyaml: -------------------------------------------------------------------------------- 1 | The following files were ported to Go from C files of libyaml, and thus 2 | are still covered by their original copyright and license: 3 | 4 | apic.go 5 | emitterc.go 6 | parserc.go 7 | readerc.go 8 | scannerc.go 9 | writerc.go 10 | yamlh.go 11 | yamlprivateh.go 12 | 13 | Copyright (c) 2006 Kirill Simonov 14 | 15 | Permission is hereby granted, free of charge, to any person obtaining a copy of 16 | this software and associated documentation files (the "Software"), to deal in 17 | the Software without restriction, including without limitation the rights to 18 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 19 | of the Software, and to permit persons to whom the Software is furnished to do 20 | so, subject to the following conditions: 21 | 22 | The above copyright notice and this permission notice shall be included in all 23 | copies or substantial portions of the Software. 24 | 25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 28 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 30 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 31 | SOFTWARE. 32 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2011-2016 Canonical Ltd. 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 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/README.md: -------------------------------------------------------------------------------- 1 | # YAML support for the Go language 2 | 3 | Introduction 4 | ------------ 5 | 6 | The yaml package enables Go programs to comfortably encode and decode YAML 7 | values. It was developed within [Canonical](https://www.canonical.com) as 8 | part of the [juju](https://juju.ubuntu.com) project, and is based on a 9 | pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) 10 | C library to parse and generate YAML data quickly and reliably. 11 | 12 | Compatibility 13 | ------------- 14 | 15 | The yaml package supports most of YAML 1.1 and 1.2, including support for 16 | anchors, tags, map merging, etc. Multi-document unmarshalling is not yet 17 | implemented, and base-60 floats from YAML 1.1 are purposefully not 18 | supported since they're a poor design and are gone in YAML 1.2. 19 | 20 | Installation and usage 21 | ---------------------- 22 | 23 | The import path for the package is *gopkg.in/yaml.v2*. 24 | 25 | To install it, run: 26 | 27 | go get gopkg.in/yaml.v2 28 | 29 | API documentation 30 | ----------------- 31 | 32 | If opened in a browser, the import path itself leads to the API documentation: 33 | 34 | * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) 35 | 36 | API stability 37 | ------------- 38 | 39 | The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). 40 | 41 | 42 | License 43 | ------- 44 | 45 | The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. 46 | 47 | 48 | Example 49 | ------- 50 | 51 | ```Go 52 | package main 53 | 54 | import ( 55 | "fmt" 56 | "log" 57 | 58 | "gopkg.in/yaml.v2" 59 | ) 60 | 61 | var data = ` 62 | a: Easy! 63 | b: 64 | c: 2 65 | d: [3, 4] 66 | ` 67 | 68 | // Note: struct fields must be public in order for unmarshal to 69 | // correctly populate the data. 70 | type T struct { 71 | A string 72 | B struct { 73 | RenamedC int `yaml:"c"` 74 | D []int `yaml:",flow"` 75 | } 76 | } 77 | 78 | func main() { 79 | t := T{} 80 | 81 | err := yaml.Unmarshal([]byte(data), &t) 82 | if err != nil { 83 | log.Fatalf("error: %v", err) 84 | } 85 | fmt.Printf("--- t:\n%v\n\n", t) 86 | 87 | d, err := yaml.Marshal(&t) 88 | if err != nil { 89 | log.Fatalf("error: %v", err) 90 | } 91 | fmt.Printf("--- t dump:\n%s\n\n", string(d)) 92 | 93 | m := make(map[interface{}]interface{}) 94 | 95 | err = yaml.Unmarshal([]byte(data), &m) 96 | if err != nil { 97 | log.Fatalf("error: %v", err) 98 | } 99 | fmt.Printf("--- m:\n%v\n\n", m) 100 | 101 | d, err = yaml.Marshal(&m) 102 | if err != nil { 103 | log.Fatalf("error: %v", err) 104 | } 105 | fmt.Printf("--- m dump:\n%s\n\n", string(d)) 106 | } 107 | ``` 108 | 109 | This example will generate the following output: 110 | 111 | ``` 112 | --- t: 113 | {Easy! {2 [3 4]}} 114 | 115 | --- t dump: 116 | a: Easy! 117 | b: 118 | c: 2 119 | d: [3, 4] 120 | 121 | 122 | --- m: 123 | map[a:Easy! b:map[c:2 d:[3 4]]] 124 | 125 | --- m dump: 126 | a: Easy! 127 | b: 128 | c: 2 129 | d: 130 | - 3 131 | - 4 132 | ``` 133 | 134 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/go.mod: -------------------------------------------------------------------------------- 1 | module "gopkg.in/yaml.v2" 2 | 3 | require ( 4 | "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405 5 | ) 6 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/sorter.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | import ( 4 | "reflect" 5 | "unicode" 6 | ) 7 | 8 | type keyList []reflect.Value 9 | 10 | func (l keyList) Len() int { return len(l) } 11 | func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } 12 | func (l keyList) Less(i, j int) bool { 13 | a := l[i] 14 | b := l[j] 15 | ak := a.Kind() 16 | bk := b.Kind() 17 | for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { 18 | a = a.Elem() 19 | ak = a.Kind() 20 | } 21 | for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { 22 | b = b.Elem() 23 | bk = b.Kind() 24 | } 25 | af, aok := keyFloat(a) 26 | bf, bok := keyFloat(b) 27 | if aok && bok { 28 | if af != bf { 29 | return af < bf 30 | } 31 | if ak != bk { 32 | return ak < bk 33 | } 34 | return numLess(a, b) 35 | } 36 | if ak != reflect.String || bk != reflect.String { 37 | return ak < bk 38 | } 39 | ar, br := []rune(a.String()), []rune(b.String()) 40 | for i := 0; i < len(ar) && i < len(br); i++ { 41 | if ar[i] == br[i] { 42 | continue 43 | } 44 | al := unicode.IsLetter(ar[i]) 45 | bl := unicode.IsLetter(br[i]) 46 | if al && bl { 47 | return ar[i] < br[i] 48 | } 49 | if al || bl { 50 | return bl 51 | } 52 | var ai, bi int 53 | var an, bn int64 54 | if ar[i] == '0' || br[i] == '0' { 55 | for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { 56 | if ar[j] != '0' { 57 | an = 1 58 | bn = 1 59 | break 60 | } 61 | } 62 | } 63 | for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { 64 | an = an*10 + int64(ar[ai]-'0') 65 | } 66 | for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { 67 | bn = bn*10 + int64(br[bi]-'0') 68 | } 69 | if an != bn { 70 | return an < bn 71 | } 72 | if ai != bi { 73 | return ai < bi 74 | } 75 | return ar[i] < br[i] 76 | } 77 | return len(ar) < len(br) 78 | } 79 | 80 | // keyFloat returns a float value for v if it is a number/bool 81 | // and whether it is a number/bool or not. 82 | func keyFloat(v reflect.Value) (f float64, ok bool) { 83 | switch v.Kind() { 84 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 85 | return float64(v.Int()), true 86 | case reflect.Float32, reflect.Float64: 87 | return v.Float(), true 88 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 89 | return float64(v.Uint()), true 90 | case reflect.Bool: 91 | if v.Bool() { 92 | return 1, true 93 | } 94 | return 0, true 95 | } 96 | return 0, false 97 | } 98 | 99 | // numLess returns whether a < b. 100 | // a and b must necessarily have the same kind. 101 | func numLess(a, b reflect.Value) bool { 102 | switch a.Kind() { 103 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 104 | return a.Int() < b.Int() 105 | case reflect.Float32, reflect.Float64: 106 | return a.Float() < b.Float() 107 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 108 | return a.Uint() < b.Uint() 109 | case reflect.Bool: 110 | return !a.Bool() && b.Bool() 111 | } 112 | panic("not a number") 113 | } 114 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/writerc.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | // Set the writer error and return false. 4 | func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { 5 | emitter.error = yaml_WRITER_ERROR 6 | emitter.problem = problem 7 | return false 8 | } 9 | 10 | // Flush the output buffer. 11 | func yaml_emitter_flush(emitter *yaml_emitter_t) bool { 12 | if emitter.write_handler == nil { 13 | panic("write handler not set") 14 | } 15 | 16 | // Check if the buffer is empty. 17 | if emitter.buffer_pos == 0 { 18 | return true 19 | } 20 | 21 | if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { 22 | return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) 23 | } 24 | emitter.buffer_pos = 0 25 | return true 26 | } 27 | -------------------------------------------------------------------------------- /vendor/modules.txt: -------------------------------------------------------------------------------- 1 | # github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 2 | github.com/alecthomas/template 3 | github.com/alecthomas/template/parse 4 | # github.com/alecthomas/units v0.0.0-20190910110746-680d30ca3117 5 | github.com/alecthomas/units 6 | # github.com/beorn7/perks v1.0.1 7 | github.com/beorn7/perks/quantile 8 | # github.com/golang/protobuf v1.3.3-0.20190827175835-822fe56949f5 9 | github.com/golang/protobuf/proto 10 | # github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 11 | github.com/matttproud/golang_protobuf_extensions/pbutil 12 | # github.com/prometheus/client_golang v1.1.1-0.20190913103102-20428fa0bffc 13 | github.com/prometheus/client_golang/prometheus 14 | github.com/prometheus/client_golang/prometheus/internal 15 | github.com/prometheus/client_golang/prometheus/promhttp 16 | # github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 17 | github.com/prometheus/client_model/go 18 | # github.com/prometheus/common v0.7.0 19 | github.com/prometheus/common/expfmt 20 | github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg 21 | github.com/prometheus/common/model 22 | github.com/prometheus/common/version 23 | # github.com/prometheus/procfs v0.0.6-0.20190917143953-de25ac347ef9 24 | github.com/prometheus/procfs 25 | github.com/prometheus/procfs/internal/fs 26 | github.com/prometheus/procfs/internal/util 27 | # golang.org/x/sys v0.0.0-20190919044723-0c1ff786ef13 28 | golang.org/x/sys/windows 29 | # gopkg.in/alecthomas/kingpin.v2 v2.2.6 30 | gopkg.in/alecthomas/kingpin.v2 31 | # gopkg.in/yaml.v2 v2.2.2 32 | gopkg.in/yaml.v2 33 | --------------------------------------------------------------------------------