├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── README.md ├── end_to_end_test.go ├── handler.go ├── ingester ├── checkpoint.go ├── ingester.go ├── locker.go ├── locker_test.go ├── mapper.go ├── mapper_test.go └── series.go ├── main.go ├── store.go └── vendor ├── github.com ├── ChronixDB │ └── chronix.go │ │ └── chronix │ │ ├── LICENSE │ │ ├── client.go │ │ ├── codec.go │ │ ├── elastic.go │ │ ├── pb │ │ └── point.pb.go │ │ ├── solr.go │ │ ├── statscalc.go │ │ ├── storageclient.go │ │ └── timeseries.go ├── Sirupsen │ └── logrus │ │ ├── LICENSE │ │ ├── alt_exit.go │ │ ├── doc.go │ │ ├── entry.go │ │ ├── examples │ │ ├── basic │ │ │ └── basic.go │ │ └── hook │ │ │ └── hook.go │ │ ├── exported.go │ │ ├── formatter.go │ │ ├── hooks.go │ │ ├── hooks │ │ ├── syslog │ │ │ └── syslog.go │ │ └── test │ │ │ └── test.go │ │ ├── json_formatter.go │ │ ├── logger.go │ │ ├── logrus.go │ │ ├── terminal_appengine.go │ │ ├── terminal_bsd.go │ │ ├── terminal_linux.go │ │ ├── terminal_notwindows.go │ │ ├── terminal_solaris.go │ │ ├── terminal_windows.go │ │ ├── text_formatter.go │ │ └── writer.go ├── beorn7 │ └── perks │ │ └── quantile │ │ ├── LICENSE │ │ └── stream.go ├── gogo │ └── protobuf │ │ ├── proto │ │ ├── LICENSE │ │ ├── clone.go │ │ ├── decode.go │ │ ├── decode_gogo.go │ │ ├── duration.go │ │ ├── duration_gogo.go │ │ ├── encode.go │ │ ├── encode_gogo.go │ │ ├── equal.go │ │ ├── extensions.go │ │ ├── extensions_gogo.go │ │ ├── lib.go │ │ ├── lib_gogo.go │ │ ├── message_set.go │ │ ├── pointer_reflect.go │ │ ├── pointer_unsafe.go │ │ ├── pointer_unsafe_gogo.go │ │ ├── properties.go │ │ ├── properties_gogo.go │ │ ├── proto3_proto │ │ │ └── proto3.pb.go │ │ ├── skip_gogo.go │ │ ├── text.go │ │ ├── text_gogo.go │ │ ├── text_parser.go │ │ ├── timestamp.go │ │ └── timestamp_gogo.go │ │ ├── sortkeys │ │ ├── LICENSE │ │ └── sortkeys.go │ │ └── types │ │ ├── LICENSE │ │ ├── any.go │ │ ├── any.pb.go │ │ ├── doc.go │ │ ├── duration.go │ │ ├── duration.pb.go │ │ ├── duration_gogo.go │ │ ├── empty.pb.go │ │ ├── field_mask.pb.go │ │ ├── struct.pb.go │ │ ├── timestamp.go │ │ ├── timestamp.pb.go │ │ ├── timestamp_gogo.go │ │ └── wrappers.pb.go ├── golang │ ├── protobuf │ │ ├── proto │ │ │ ├── LICENSE │ │ │ ├── clone.go │ │ │ ├── decode.go │ │ │ ├── encode.go │ │ │ ├── equal.go │ │ │ ├── extensions.go │ │ │ ├── lib.go │ │ │ ├── message_set.go │ │ │ ├── pointer_reflect.go │ │ │ ├── pointer_unsafe.go │ │ │ ├── properties.go │ │ │ ├── proto3_proto │ │ │ │ └── proto3.pb.go │ │ │ ├── text.go │ │ │ └── text_parser.go │ │ └── ptypes │ │ │ └── any │ │ │ ├── LICENSE │ │ │ └── any.pb.go │ └── snappy │ │ ├── LICENSE │ │ ├── cmd │ │ └── snappytool │ │ │ └── main.cpp │ │ ├── decode.go │ │ ├── decode_amd64.go │ │ ├── decode_amd64.s │ │ ├── decode_other.go │ │ ├── encode.go │ │ ├── encode_amd64.go │ │ ├── encode_amd64.s │ │ ├── encode_other.go │ │ └── snappy.go ├── influxdata │ └── influxdb │ │ ├── models │ │ ├── LICENSE │ │ ├── consistency.go │ │ ├── inline_fnv.go │ │ ├── inline_strconv_parse.go │ │ ├── points.go │ │ ├── rows.go │ │ ├── statistic.go │ │ └── time.go │ │ └── pkg │ │ └── escape │ │ ├── LICENSE │ │ ├── bytes.go │ │ └── strings.go ├── influxdb │ └── influxdb │ │ └── client │ │ ├── LICENSE │ │ ├── influxdb.go │ │ └── v2 │ │ ├── client.go │ │ └── udp.go ├── matttproud │ └── golang_protobuf_extensions │ │ └── pbutil │ │ ├── LICENSE │ │ ├── decode.go │ │ ├── doc.go │ │ └── encode.go └── prometheus │ ├── client_golang │ └── prometheus │ │ ├── LICENSE │ │ ├── collector.go │ │ ├── counter.go │ │ ├── desc.go │ │ ├── doc.go │ │ ├── expvar_collector.go │ │ ├── fnv.go │ │ ├── gauge.go │ │ ├── go_collector.go │ │ ├── histogram.go │ │ ├── http.go │ │ ├── metric.go │ │ ├── process_collector.go │ │ ├── promhttp │ │ └── http.go │ │ ├── push │ │ └── push.go │ │ ├── registry.go │ │ ├── summary.go │ │ ├── untyped.go │ │ ├── value.go │ │ └── vec.go │ ├── client_model │ └── go │ │ ├── LICENSE │ │ └── metrics.pb.go │ ├── common │ ├── expfmt │ │ ├── LICENSE │ │ ├── decode.go │ │ ├── encode.go │ │ ├── expfmt.go │ │ ├── fuzz.go │ │ ├── text_create.go │ │ └── text_parse.go │ ├── internal │ │ └── bitbucket.org │ │ │ └── ww │ │ │ └── goautoneg │ │ │ ├── LICENSE │ │ │ └── autoneg.go │ ├── log │ │ ├── LICENSE │ │ ├── eventlog_formatter.go │ │ ├── log.go │ │ └── syslog_formatter.go │ └── model │ │ ├── LICENSE │ │ ├── alert.go │ │ ├── fingerprinting.go │ │ ├── fnv.go │ │ ├── labels.go │ │ ├── labelset.go │ │ ├── metric.go │ │ ├── model.go │ │ ├── signature.go │ │ ├── silence.go │ │ ├── time.go │ │ └── value.go │ ├── procfs │ ├── LICENSE │ ├── doc.go │ ├── fs.go │ ├── ipvs.go │ ├── mdstat.go │ ├── proc.go │ ├── proc_io.go │ ├── proc_limits.go │ ├── proc_stat.go │ └── stat.go │ └── prometheus │ ├── config │ ├── LICENSE │ └── config.go │ ├── relabel │ ├── LICENSE │ └── relabel.go │ ├── storage │ ├── LICENSE │ ├── fanin │ │ └── fanin.go │ ├── local │ │ ├── chunk │ │ │ ├── chunk.go │ │ │ ├── delta.go │ │ │ ├── delta_helpers.go │ │ │ ├── doubledelta.go │ │ │ ├── instrumentation.go │ │ │ ├── varbit.go │ │ │ └── varbit_helpers.go │ │ ├── codable │ │ │ └── codable.go │ │ ├── crashrecovery.go │ │ ├── heads.go │ │ ├── index │ │ │ ├── index.go │ │ │ ├── interface.go │ │ │ └── leveldb.go │ │ ├── instrumentation.go │ │ ├── interface.go │ │ ├── locker.go │ │ ├── mapper.go │ │ ├── noop_storage.go │ │ ├── persistence.go │ │ ├── series.go │ │ ├── storage.go │ │ ├── storagetool │ │ │ └── main.go │ │ └── test_helpers.go │ ├── metric │ │ ├── matcher.go │ │ ├── metric.go │ │ └── sample.go │ ├── remote │ │ ├── client.go │ │ ├── ewma.go │ │ ├── iterator.go │ │ ├── queue_manager.go │ │ ├── read.go │ │ ├── remote.pb.go │ │ └── write.go │ └── storage.go │ └── util │ ├── cli │ ├── LICENSE │ └── cli.go │ ├── flock │ ├── LICENSE │ ├── flock.go │ ├── flock_plan9.go │ ├── flock_solaris.go │ ├── flock_unix.go │ └── flock_windows.go │ ├── httputil │ ├── LICENSE │ ├── client.go │ └── compression.go │ └── testutil │ ├── LICENSE │ ├── directory.go │ └── error.go ├── golang.org └── x │ ├── net │ └── context │ │ ├── LICENSE │ │ ├── context.go │ │ ├── ctxhttp │ │ ├── ctxhttp.go │ │ └── ctxhttp_pre17.go │ │ ├── go17.go │ │ └── pre_go17.go │ └── sys │ └── windows │ ├── LICENSE │ ├── asm_windows_386.s │ ├── asm_windows_amd64.s │ ├── dll_windows.go │ ├── env_unset.go │ ├── env_windows.go │ ├── eventlog.go │ ├── exec_windows.go │ ├── mksyscall.go │ ├── race.go │ ├── race0.go │ ├── registry │ ├── key.go │ ├── mksyscall.go │ ├── syscall.go │ ├── value.go │ └── zsyscall_windows.go │ ├── security_windows.go │ ├── service.go │ ├── str.go │ ├── svc │ ├── debug │ │ ├── log.go │ │ └── service.go │ ├── event.go │ ├── eventlog │ │ ├── install.go │ │ └── log.go │ ├── example │ │ ├── beep.go │ │ ├── install.go │ │ ├── main.go │ │ ├── manage.go │ │ └── service.go │ ├── go12.c │ ├── go12.go │ ├── go13.go │ ├── mgr │ │ ├── config.go │ │ ├── mgr.go │ │ └── service.go │ ├── security.go │ ├── service.go │ ├── sys_386.s │ └── sys_amd64.s │ ├── syscall.go │ ├── syscall_windows.go │ ├── zsyscall_windows.go │ ├── ztypes_windows.go │ ├── ztypes_windows_386.go │ └── ztypes_windows_amd64.go ├── gopkg.in ├── gemnasium │ └── logrus-airbrake-hook.v2 │ │ ├── LICENSE │ │ └── airbrake.go └── yaml.v2 │ ├── LICENSE │ ├── apic.go │ ├── decode.go │ ├── emitterc.go │ ├── encode.go │ ├── parserc.go │ ├── readerc.go │ ├── resolve.go │ ├── scannerc.go │ ├── sorter.go │ ├── writerc.go │ ├── yaml.go │ ├── yamlh.go │ └── yamlprivateh.go └── manifest /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.9 5 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # build stage 2 | FROM golang:alpine AS build-env 3 | WORKDIR /go 4 | ADD . src/github.com/ChronixDB/chronix.ingester 5 | WORKDIR ./src/github.com/ChronixDB/chronix.ingester 6 | 7 | RUN apk add --no-cache git \ 8 | && go env \ 9 | && go get -v ./... \ 10 | && go build -o chronix.ingester \ 11 | && apk del git 12 | 13 | # final stage 14 | FROM alpine 15 | 16 | RUN apk update \ 17 | && apk add --no-cache ca-certificates 18 | 19 | WORKDIR /chronix 20 | COPY --from=build-env /go/src/github.com/ChronixDB/chronix.ingester/chronix.ingester . 21 | 22 | EXPOSE 8080/tcp 23 | ENTRYPOINT ["./chronix.ingester"] 24 | CMD ["-h"] 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/ChronixDB/chronix.ingester.svg?branch=master)](https://travis-ci.org/ChronixDB/chronix.ingester) 2 | 3 | # chronix.ingester 4 | 5 | The Chronix Ingester batches up sample data from various sources and 6 | stores it as chunks in Chronix. Currently, only [Prometheus](https://prometheus.io/) 7 | is supported. 8 | 9 | ## Building 10 | 11 | Building requires [Go](https://golang.org/dl/) 1.7 or newer, as well as a 12 | working [`GOPATH` setup](https://golang.org/doc/code.html). 13 | 14 | To build the ingester: 15 | 16 | ``` 17 | go build 18 | ``` 19 | 20 | ## Running 21 | 22 | Example: 23 | 24 | ``` 25 | ./chronix.ingester -url=http://my-solr-host:8983/solr/chronix -max-chunk-age=30m 26 | ``` 27 | 28 | To show all flags: 29 | 30 | ``` 31 | ./chronix.ingester -h 32 | Usage of chronix.ingester.exe: 33 | -checkpoint-file string 34 | The path to the checkpoint file. (default "checkpoint.db") 35 | -checkpoint-interval duration 36 | The interval between checkpoints. (default 5m0s) 37 | -chronix-commit-within duration 38 | The duration after which updates to Chronix should be committed. (default 5s) 39 | -create-statistics 40 | Whether to store some additional statistical data for each data chunk. 41 | -es.deleteIndexIfExists 42 | Deletes the index only with es.withIndex=true 43 | -es.sniffNodes 44 | Should elastic client sniff for ES nodes (only used with elastic search) (default true) 45 | -es.withIndex 46 | Creates an index (only used with elastic search (default true) 47 | -flush-on-shutdown 48 | Whether to flush all chunks to Chronix on shutdown, rather than saving them to a checkpoint. A checkpoint will still be written, but will be empty. 49 | -kind string 50 | Possible values are: 'solr' or 'elastic' (default "solr") 51 | -listen-addr string 52 | The address to listen on. (default ":8080") 53 | -log.format value 54 | Set the log target and format. Example: "logger:syslog?appname=bob&local=7" or "logger:stdout?json=true" (default "logger:stderr") 55 | -log.level value 56 | Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal] (default "info") 57 | -max-chunk-age duration 58 | The maximum age of a chunk before it is closed and persisted. (default 1h0m0s) 59 | -url string 60 | The URL of the Chronix endpoint. (default "http://localhost:8983/solr/chronix") 61 | 62 | ``` 63 | 64 | ## Run in Docker container 65 | A docker image is provided on [Docker Hub](https://hub.docker.com/r/chronix/chronix.ingester/). 66 | The Dockerfile defines the entrypoint to the chronix.ingester binary but no program arguments. You have to 67 | set the commands yourself, e.g.: 68 | 69 | `docker run --rm -it chronix/chronix.ingester -url=http://localhost:9200 -kind=elastic -es.deleteIndexIfExists=true` 70 | 71 | ## Testing 72 | 73 | To run tests: 74 | 75 | ``` 76 | go test ./... 77 | ``` 78 | 79 | ## Configuring Prometheus 80 | 81 | Sending samples to the Chronix ingester from Prometheus requires Prometheus 82 | version 1.2.0 or newer. To configure Prometheus to send samples to the 83 | ingester, add the following stanza to your Prometheus configuration file: 84 | 85 | ```yml 86 | remote_write: 87 | url: http://:/ingest 88 | ``` 89 | -------------------------------------------------------------------------------- /handler.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | 8 | "github.com/gogo/protobuf/proto" 9 | "github.com/golang/snappy" 10 | "github.com/prometheus/common/log" 11 | "github.com/prometheus/common/model" 12 | "github.com/prometheus/prometheus/storage" 13 | "github.com/prometheus/prometheus/storage/remote" 14 | ) 15 | 16 | // ingestHandler returns an http.Handler that accepts proto encoded samples. 17 | func ingestHandler(appender storage.SampleAppender) http.Handler { 18 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 19 | if v := r.Header.Get("X-Prometheus-Remote-Write-Version"); v != "0.1.0" { 20 | msg := fmt.Sprintf("Unsupported remote write protocol version %q", v) 21 | log.Errorln(msg) 22 | http.Error(w, msg, http.StatusBadRequest) 23 | return 24 | } 25 | 26 | compressed, err := ioutil.ReadAll(r.Body) 27 | if err != nil { 28 | log.Errorf("Error reading request body: %v", err) 29 | http.Error(w, err.Error(), http.StatusInternalServerError) 30 | return 31 | } 32 | 33 | reqBuf, err := snappy.Decode(nil, compressed) 34 | if err != nil { 35 | log.Errorf("Error decompressing request body: %v", err) 36 | http.Error(w, err.Error(), http.StatusBadRequest) 37 | return 38 | } 39 | 40 | var req remote.WriteRequest 41 | if err := proto.Unmarshal(reqBuf, &req); err != nil { 42 | log.Errorf("Error unmarshalling request body: %v", err) 43 | http.Error(w, err.Error(), http.StatusBadRequest) 44 | return 45 | } 46 | 47 | for _, ts := range req.Timeseries { 48 | metric := model.Metric{} 49 | for _, l := range ts.Labels { 50 | metric[model.LabelName(l.Name)] = model.LabelValue(l.Value) 51 | } 52 | 53 | for _, s := range ts.Samples { 54 | err := appender.Append(&model.Sample{ 55 | Metric: metric, 56 | Value: model.SampleValue(s.Value), 57 | Timestamp: model.Time(s.TimestampMs), 58 | }) 59 | if err != nil { 60 | log.Errorf("Error appending sample: %v", err) 61 | http.Error(w, err.Error(), http.StatusInternalServerError) 62 | return 63 | } 64 | } 65 | } 66 | }) 67 | } 68 | -------------------------------------------------------------------------------- /ingester/locker.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 ingester 15 | 16 | import ( 17 | "sync" 18 | "unsafe" 19 | 20 | "github.com/prometheus/common/model" 21 | ) 22 | 23 | const ( 24 | cacheLineSize = 64 25 | ) 26 | 27 | // Avoid false sharing when using array of mutexes. 28 | type paddedMutex struct { 29 | sync.Mutex 30 | pad [cacheLineSize - unsafe.Sizeof(sync.Mutex{})]byte 31 | } 32 | 33 | // fingerprintLocker allows locking individual fingerprints. To limit the number 34 | // of mutexes needed for that, only a fixed number of mutexes are 35 | // allocated. Fingerprints to be locked are assigned to those pre-allocated 36 | // mutexes by their value. Collisions are not detected. If two fingerprints get 37 | // assigned to the same mutex, only one of them can be locked at the same 38 | // time. As long as the number of pre-allocated mutexes is much larger than the 39 | // number of goroutines requiring a fingerprint lock concurrently, the loss in 40 | // efficiency is small. However, a goroutine must never lock more than one 41 | // fingerprint at the same time. (In that case a collision would try to acquire 42 | // the same mutex twice). 43 | type fingerprintLocker struct { 44 | fpMtxs []paddedMutex 45 | numFpMtxs uint 46 | } 47 | 48 | // newFingerprintLocker returns a new fingerprintLocker ready for use. At least 49 | // 1024 preallocated mutexes are used, even if preallocatedMutexes is lower. 50 | func newFingerprintLocker(preallocatedMutexes int) *fingerprintLocker { 51 | if preallocatedMutexes < 1024 { 52 | preallocatedMutexes = 1024 53 | } 54 | return &fingerprintLocker{ 55 | make([]paddedMutex, preallocatedMutexes), 56 | uint(preallocatedMutexes), 57 | } 58 | } 59 | 60 | // Lock locks the given fingerprint. 61 | func (l *fingerprintLocker) Lock(fp model.Fingerprint) { 62 | l.fpMtxs[hashFP(fp)%l.numFpMtxs].Lock() 63 | } 64 | 65 | // Unlock unlocks the given fingerprint. 66 | func (l *fingerprintLocker) Unlock(fp model.Fingerprint) { 67 | l.fpMtxs[hashFP(fp)%l.numFpMtxs].Unlock() 68 | } 69 | 70 | // hashFP simply moves entropy from the most significant 48 bits of the 71 | // fingerprint into the least significant 16 bits (by XORing) so that a simple 72 | // MOD on the result can be used to pick a mutex while still making use of 73 | // changes in more significant bits of the fingerprint. (The fast fingerprinting 74 | // function we use is prone to only change a few bits for similar metrics. We 75 | // really want to make use of every change in the fingerprint to vary mutex 76 | // selection.) 77 | func hashFP(fp model.Fingerprint) uint { 78 | return uint(fp ^ (fp >> 32) ^ (fp >> 16)) 79 | } 80 | -------------------------------------------------------------------------------- /ingester/locker_test.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 ingester 15 | 16 | import ( 17 | "sync" 18 | "testing" 19 | 20 | "github.com/prometheus/common/model" 21 | ) 22 | 23 | func BenchmarkFingerprintLockerParallel(b *testing.B) { 24 | numGoroutines := 10 25 | numFingerprints := 10 26 | numLockOps := b.N 27 | locker := newFingerprintLocker(100) 28 | 29 | wg := sync.WaitGroup{} 30 | b.ResetTimer() 31 | for i := 0; i < numGoroutines; i++ { 32 | wg.Add(1) 33 | go func(i int) { 34 | for j := 0; j < numLockOps; j++ { 35 | fp1 := model.Fingerprint(j % numFingerprints) 36 | fp2 := model.Fingerprint(j%numFingerprints + numFingerprints) 37 | locker.Lock(fp1) 38 | locker.Lock(fp2) 39 | locker.Unlock(fp2) 40 | locker.Unlock(fp1) 41 | } 42 | wg.Done() 43 | }(i) 44 | } 45 | wg.Wait() 46 | } 47 | 48 | func BenchmarkFingerprintLockerSerial(b *testing.B) { 49 | numFingerprints := 10 50 | locker := newFingerprintLocker(100) 51 | 52 | b.ResetTimer() 53 | for i := 0; i < b.N; i++ { 54 | fp := model.Fingerprint(i % numFingerprints) 55 | locker.Lock(fp) 56 | locker.Unlock(fp) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /store.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/ChronixDB/chronix.go/chronix" 8 | "github.com/prometheus/common/model" 9 | "github.com/prometheus/prometheus/storage/local/chunk" 10 | ) 11 | 12 | type chronixStore struct { 13 | chronix chronix.Client 14 | commitWithin time.Duration 15 | } 16 | 17 | func (s *chronixStore) Put(metric model.Metric, descs []*chunk.Desc) error { 18 | for _, desc := range descs { 19 | ts, err := transcodeChunk(metric, desc) 20 | if err != nil { 21 | return fmt.Errorf("error transcoding chunk: %v", err) 22 | } 23 | if err := s.chronix.Store([]*chronix.TimeSeries{ts}, false, s.commitWithin); err != nil { 24 | return fmt.Errorf("error storing chunk: %v", err) 25 | } 26 | } 27 | return nil 28 | } 29 | 30 | func transcodeChunk(metric model.Metric, desc *chunk.Desc) (*chronix.TimeSeries, error) { 31 | ts := &chronix.TimeSeries{ 32 | Name: string(metric[model.MetricNameLabel]), 33 | Type: "metric", 34 | Attributes: map[string]string{}, 35 | } 36 | for k, v := range metric { 37 | if k == model.MetricNameLabel { 38 | continue 39 | } 40 | ts.Attributes[string(k)] = string(v) 41 | } 42 | 43 | it := desc.C.NewIterator() 44 | for it.Scan() { 45 | sp := it.Value() 46 | ts.Points = append(ts.Points, chronix.Point{ 47 | Value: float64(sp.Value), 48 | Timestamp: sp.Timestamp.UnixNano() / 1e6, 49 | }) 50 | } 51 | if it.Err() != nil { 52 | return nil, it.Err() 53 | } 54 | return ts, nil 55 | } 56 | -------------------------------------------------------------------------------- /vendor/github.com/ChronixDB/chronix.go/chronix/client.go: -------------------------------------------------------------------------------- 1 | package chronix 2 | 3 | import ( 4 | "time" 5 | "encoding/base64" 6 | "fmt" 7 | ) 8 | 9 | // Client is a client that allows storing time series in Chronix. 10 | type Client interface { 11 | Store(ts []*TimeSeries, commit bool, commitWithin time.Duration) error 12 | // TODO: Return a more interpreted query result on the Chronix level. 13 | Query(q, fq, fl string) ([]byte, error) 14 | } 15 | 16 | type client struct { 17 | storage StorageClient 18 | createStatistics bool 19 | } 20 | 21 | // New creates a new Chronix client. The client does not create statistics for the individual data chunks in the storage. 22 | func New(s StorageClient) Client { 23 | return &client{ 24 | storage: s, 25 | createStatistics: false, 26 | } 27 | } 28 | 29 | // creates a new Chronix client. The client does create statistics for the individual data chunks in the storage. 30 | func NewWithStatistics(s StorageClient) Client { 31 | return &client{ 32 | storage: s, 33 | createStatistics: true, 34 | } 35 | } 36 | 37 | func (c *client) Store(series []*TimeSeries, commit bool, commitWithin time.Duration) error { 38 | if len(series) == 0 { 39 | return nil 40 | } 41 | 42 | var update []map[string]interface{} 43 | for _, ts := range series { 44 | if len(ts.Points) == 0 { 45 | continue 46 | } 47 | 48 | data, err := encode(ts.Points, 0) 49 | if err != nil { 50 | return fmt.Errorf("error encoding points: %v", err) 51 | } 52 | encData := base64.StdEncoding.EncodeToString(data) 53 | fields := map[string]interface{}{ 54 | "start": ts.Points[0].Timestamp, 55 | "end": ts.Points[len(ts.Points)-1].Timestamp, 56 | "data": encData, 57 | "name": ts.Name, 58 | "type": ts.Type, 59 | } 60 | 61 | if c.storage.NeedPostfixOnDynamicField() { 62 | for k, v := range ts.Attributes { 63 | fields[k+"_s"] = v 64 | } 65 | } else { 66 | for k, v := range ts.Attributes { 67 | fields[k] = v 68 | } 69 | } 70 | 71 | err = c.addStatistics(ts, &fields) 72 | if err != nil { 73 | return fmt.Errorf("error adding statistics: %v", err) 74 | } 75 | 76 | update = append(update, fields) 77 | } 78 | return c.storage.Update(update, commit, commitWithin) 79 | } 80 | 81 | func (c *client) addStatistics(series *TimeSeries, fields *map[string]interface{}) error { 82 | if !c.createStatistics { 83 | return nil 84 | } 85 | 86 | stats, err := calculateStats(series) 87 | if err != nil { 88 | return err 89 | } 90 | 91 | suffix := "" 92 | if c.storage.NeedPostfixOnDynamicField() { 93 | suffix = "_f" 94 | } 95 | 96 | (*fields)["stats_timespan" + suffix] = stats.timespan 97 | (*fields)["stats_count" + suffix] = stats.count 98 | (*fields)["stats_min" + suffix] = stats.min 99 | (*fields)["stats_max" + suffix] = stats.max 100 | (*fields)["stats_avg" + suffix] = stats.avg 101 | return nil 102 | } 103 | 104 | func (c *client) Query(q, fq, fl string) ([]byte, error) { 105 | return c.storage.Query(q, fq, fl) 106 | } 107 | -------------------------------------------------------------------------------- /vendor/github.com/ChronixDB/chronix.go/chronix/solr.go: -------------------------------------------------------------------------------- 1 | package chronix 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io/ioutil" 8 | "net" 9 | "net/http" 10 | "net/url" 11 | "path" 12 | "time" 13 | ) 14 | 15 | // CancelableTransport is like net.Transport but provides 16 | // per-request cancelation functionality. 17 | type CancelableTransport interface { 18 | http.RoundTripper 19 | CancelRequest(req *http.Request) 20 | } 21 | 22 | // DefaultTransport is used by the solrClient when no explicit transport is provided. 23 | var DefaultTransport CancelableTransport = &http.Transport{ 24 | Proxy: http.ProxyFromEnvironment, 25 | Dial: (&net.Dialer{ 26 | Timeout: 30 * time.Second, 27 | KeepAlive: 30 * time.Second, 28 | }).Dial, 29 | TLSHandshakeTimeout: 10 * time.Second, 30 | } 31 | 32 | type solrClient struct { 33 | url *url.URL 34 | httpClient http.Client 35 | } 36 | 37 | // NewSolrStorage creates a new Solr client. 38 | func NewSolrStorage(url *url.URL, transport CancelableTransport) StorageClient { 39 | if transport == nil { 40 | transport = DefaultTransport 41 | } 42 | return &solrClient{ 43 | url: url, 44 | httpClient: http.Client{ 45 | Transport: transport, 46 | }, 47 | } 48 | } 49 | 50 | // Update implements SolrClient. 51 | func (c *solrClient) Update(data []map[string]interface{}, commit bool, commitWithin time.Duration) error { 52 | u := *c.url 53 | u.Path = path.Join(c.url.Path, "/update") 54 | qs := u.Query() 55 | if commit { 56 | qs.Set("commit", "true") 57 | } 58 | if commitWithin != 0 { 59 | qs.Set("commitWithin", fmt.Sprintf("%d", commitWithin.Nanoseconds()/1e6)) 60 | } 61 | u.RawQuery = qs.Encode() 62 | 63 | buf, err := json.Marshal(data) 64 | if err != nil { 65 | return fmt.Errorf("error marshalling JSON: %v", err) 66 | } 67 | req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(buf)) 68 | if err != nil { 69 | return fmt.Errorf("error creating request: %v", err) 70 | } 71 | req.Header.Set("Content-Type", "application/json") 72 | 73 | resp, err := c.httpClient.Do(req) 74 | if err != nil { 75 | return fmt.Errorf("error sending request: %v", err) 76 | } 77 | defer resp.Body.Close() 78 | if resp.StatusCode != http.StatusOK { 79 | return fmt.Errorf("bad HTTP response code: %s", resp.Status) 80 | } 81 | return nil 82 | } 83 | 84 | func (c *solrClient) Query(q, cj, fl string) ([]byte, error) { 85 | u := *c.url 86 | u.Path = path.Join(c.url.Path, "/select") 87 | qs := u.Query() 88 | qs.Set("q", q) 89 | qs.Set("cj", cj) 90 | qs.Set("fl", fl) 91 | qs.Set("wt", "json") 92 | u.RawQuery = qs.Encode() 93 | 94 | resp, err := c.httpClient.Get(u.String()) 95 | if err != nil { 96 | return nil, fmt.Errorf("error sending request: %v", err) 97 | } 98 | defer resp.Body.Close() 99 | if resp.StatusCode != http.StatusOK { 100 | return nil, fmt.Errorf("bad HTTP response code: %s", resp.Status) 101 | } 102 | 103 | body, err := ioutil.ReadAll(resp.Body) 104 | if err != nil { 105 | return nil, fmt.Errorf("error reading response body: %v", err) 106 | } 107 | return body, nil 108 | } 109 | 110 | func (c *solrClient) NeedPostfixOnDynamicField() bool { 111 | return true 112 | } 113 | -------------------------------------------------------------------------------- /vendor/github.com/ChronixDB/chronix.go/chronix/statscalc.go: -------------------------------------------------------------------------------- 1 | package chronix 2 | 3 | import ( 4 | "errors" 5 | "math/big" 6 | "math" 7 | ) 8 | 9 | type stats struct { 10 | count int64 11 | min float64 12 | max float64 13 | avg float64 14 | timespan int64 15 | } 16 | 17 | // Calculates the statistics for one TimeSeries 18 | func calculateStats(timeSeries *TimeSeries) (stats, error) { 19 | points := &timeSeries.Points 20 | 21 | result := stats{} 22 | 23 | if len(*points) == 0 { 24 | return stats{}, errors.New("TimeSeries has no Points") 25 | } 26 | 27 | result.count = int64(len(*points)) 28 | result.min = (*points)[0].Value 29 | result.max = (*points)[0].Value 30 | 31 | var sum = big.NewFloat(0) 32 | var number int64 = 0 33 | 34 | for _, point := range *points { 35 | if math.IsNaN(point.Value) { 36 | continue 37 | } 38 | if point.Value > result.max { 39 | result.max = point.Value 40 | } else if point.Value < result.min { 41 | result.min = point.Value 42 | } 43 | 44 | number++ 45 | sum.Add(sum, big.NewFloat(point.Value)) 46 | } 47 | 48 | result.avg, _ = sum.Quo(sum, big.NewFloat(float64(number))).Float64() 49 | result.timespan = (*points)[len(*points) - 1].Timestamp - (*points)[0].Timestamp 50 | 51 | return result, nil 52 | } 53 | -------------------------------------------------------------------------------- /vendor/github.com/ChronixDB/chronix.go/chronix/storageclient.go: -------------------------------------------------------------------------------- 1 | package chronix 2 | 3 | import "time" 4 | 5 | // A StorageClient allows updating documents in Solr. 6 | type StorageClient interface { 7 | Update(data []map[string]interface{}, commit bool, commitWithin time.Duration) error 8 | // TODO: Return a more interpreted result on the Solr level. 9 | Query(q, fq, fl string) ([]byte, error) 10 | 11 | NeedPostfixOnDynamicField() bool 12 | } 13 | -------------------------------------------------------------------------------- /vendor/github.com/ChronixDB/chronix.go/chronix/timeseries.go: -------------------------------------------------------------------------------- 1 | package chronix 2 | 3 | // A TimeSeries models a Chronix time series chunk. 4 | type TimeSeries struct { 5 | Name string 6 | Type string 7 | Attributes map[string]string 8 | Points []Point 9 | } 10 | 11 | // A Point models a Chronix time series sample. 12 | type Point struct { 13 | Timestamp int64 14 | Value float64 15 | } 16 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Simon Eskildsen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/alt_exit.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | // The following code was sourced and modified from the 4 | // https://bitbucket.org/tebeka/atexit package governed by the following license: 5 | // 6 | // Copyright (c) 2012 Miki Tebeka . 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in 10 | // the Software without restriction, including without limitation the rights to 11 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 12 | // the Software, and to permit persons to whom the Software is furnished to do so, 13 | // subject to the following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 20 | // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 21 | // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 22 | // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 23 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | import ( 26 | "fmt" 27 | "os" 28 | ) 29 | 30 | var handlers = []func(){} 31 | 32 | func runHandler(handler func()) { 33 | defer func() { 34 | if err := recover(); err != nil { 35 | fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) 36 | } 37 | }() 38 | 39 | handler() 40 | } 41 | 42 | func runHandlers() { 43 | for _, handler := range handlers { 44 | runHandler(handler) 45 | } 46 | } 47 | 48 | // Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) 49 | func Exit(code int) { 50 | runHandlers() 51 | os.Exit(code) 52 | } 53 | 54 | // RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke 55 | // all handlers. The handlers will also be invoked when any Fatal log entry is 56 | // made. 57 | // 58 | // This method is useful when a caller wishes to use logrus to log a fatal 59 | // message but also needs to gracefully shutdown. An example usecase could be 60 | // closing database connections, or sending a alert that the application is 61 | // closing. 62 | func RegisterExitHandler(handler func()) { 63 | handlers = append(handlers, handler) 64 | } 65 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package logrus is a structured logger for Go, completely API compatible with the standard library logger. 3 | 4 | 5 | The simplest way to use Logrus is simply the package-level exported logger: 6 | 7 | package main 8 | 9 | import ( 10 | log "github.com/Sirupsen/logrus" 11 | ) 12 | 13 | func main() { 14 | log.WithFields(log.Fields{ 15 | "animal": "walrus", 16 | "number": 1, 17 | "size": 10, 18 | }).Info("A walrus appears") 19 | } 20 | 21 | Output: 22 | time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 23 | 24 | For a full guide visit https://github.com/Sirupsen/logrus 25 | */ 26 | package logrus 27 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/examples/basic/basic.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Sirupsen/logrus" 5 | ) 6 | 7 | var log = logrus.New() 8 | 9 | func init() { 10 | log.Formatter = new(logrus.JSONFormatter) 11 | log.Formatter = new(logrus.TextFormatter) // default 12 | log.Level = logrus.DebugLevel 13 | } 14 | 15 | func main() { 16 | defer func() { 17 | err := recover() 18 | if err != nil { 19 | log.WithFields(logrus.Fields{ 20 | "omg": true, 21 | "err": err, 22 | "number": 100, 23 | }).Fatal("The ice breaks!") 24 | } 25 | }() 26 | 27 | log.WithFields(logrus.Fields{ 28 | "animal": "walrus", 29 | "number": 8, 30 | }).Debug("Started observing beach") 31 | 32 | log.WithFields(logrus.Fields{ 33 | "animal": "walrus", 34 | "size": 10, 35 | }).Info("A group of walrus emerges from the ocean") 36 | 37 | log.WithFields(logrus.Fields{ 38 | "omg": true, 39 | "number": 122, 40 | }).Warn("The group's number increased tremendously!") 41 | 42 | log.WithFields(logrus.Fields{ 43 | "temperature": -4, 44 | }).Debug("Temperature changes") 45 | 46 | log.WithFields(logrus.Fields{ 47 | "animal": "orca", 48 | "size": 9009, 49 | }).Panic("It's over 9000!") 50 | } 51 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/examples/hook/hook.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Sirupsen/logrus" 5 | "gopkg.in/gemnasium/logrus-airbrake-hook.v2" 6 | ) 7 | 8 | var log = logrus.New() 9 | 10 | func init() { 11 | log.Formatter = new(logrus.TextFormatter) // default 12 | log.Hooks.Add(airbrake.NewHook(123, "xyz", "development")) 13 | } 14 | 15 | func main() { 16 | log.WithFields(logrus.Fields{ 17 | "animal": "walrus", 18 | "size": 10, 19 | }).Info("A group of walrus emerges from the ocean") 20 | 21 | log.WithFields(logrus.Fields{ 22 | "omg": true, 23 | "number": 122, 24 | }).Warn("The group's number increased tremendously!") 25 | 26 | log.WithFields(logrus.Fields{ 27 | "omg": true, 28 | "number": 100, 29 | }).Fatal("The ice breaks!") 30 | } 31 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/formatter.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import "time" 4 | 5 | const DefaultTimestampFormat = time.RFC3339 6 | 7 | // The Formatter interface is used to implement a custom Formatter. It takes an 8 | // `Entry`. It exposes all the fields, including the default ones: 9 | // 10 | // * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. 11 | // * `entry.Data["time"]`. The timestamp. 12 | // * `entry.Data["level"]. The level the entry was logged at. 13 | // 14 | // Any additional fields added with `WithField` or `WithFields` are also in 15 | // `entry.Data`. Format is expected to return an array of bytes which are then 16 | // logged to `logger.Out`. 17 | type Formatter interface { 18 | Format(*Entry) ([]byte, error) 19 | } 20 | 21 | // This is to not silently overwrite `time`, `msg` and `level` fields when 22 | // dumping it. If this code wasn't there doing: 23 | // 24 | // logrus.WithField("level", 1).Info("hello") 25 | // 26 | // Would just silently drop the user provided level. Instead with this code 27 | // it'll logged as: 28 | // 29 | // {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} 30 | // 31 | // It's not exported because it's still using Data in an opinionated way. It's to 32 | // avoid code duplication between the two default formatters. 33 | func prefixFieldClashes(data Fields) { 34 | if t, ok := data["time"]; ok { 35 | data["fields.time"] = t 36 | } 37 | 38 | if m, ok := data["msg"]; ok { 39 | data["fields.msg"] = m 40 | } 41 | 42 | if l, ok := data["level"]; ok { 43 | data["fields.level"] = l 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/hooks.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | // A hook to be fired when logging on the logging levels returned from 4 | // `Levels()` on your implementation of the interface. Note that this is not 5 | // fired in a goroutine or a channel with workers, you should handle such 6 | // functionality yourself if your call is non-blocking and you don't wish for 7 | // the logging calls for levels returned from `Levels()` to block. 8 | type Hook interface { 9 | Levels() []Level 10 | Fire(*Entry) error 11 | } 12 | 13 | // Internal type for storing the hooks on a logger instance. 14 | type LevelHooks map[Level][]Hook 15 | 16 | // Add a hook to an instance of logger. This is called with 17 | // `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. 18 | func (hooks LevelHooks) Add(hook Hook) { 19 | for _, level := range hook.Levels() { 20 | hooks[level] = append(hooks[level], hook) 21 | } 22 | } 23 | 24 | // Fire all the hooks for the passed level. Used by `entry.log` to fire 25 | // appropriate hooks for a log entry. 26 | func (hooks LevelHooks) Fire(level Level, entry *Entry) error { 27 | for _, hook := range hooks[level] { 28 | if err := hook.Fire(entry); err != nil { 29 | return err 30 | } 31 | } 32 | 33 | return nil 34 | } 35 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go: -------------------------------------------------------------------------------- 1 | // +build !windows,!nacl,!plan9 2 | 3 | package logrus_syslog 4 | 5 | import ( 6 | "fmt" 7 | "github.com/Sirupsen/logrus" 8 | "log/syslog" 9 | "os" 10 | ) 11 | 12 | // SyslogHook to send logs via syslog. 13 | type SyslogHook struct { 14 | Writer *syslog.Writer 15 | SyslogNetwork string 16 | SyslogRaddr string 17 | } 18 | 19 | // Creates a hook to be added to an instance of logger. This is called with 20 | // `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")` 21 | // `if err == nil { log.Hooks.Add(hook) }` 22 | func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) { 23 | w, err := syslog.Dial(network, raddr, priority, tag) 24 | return &SyslogHook{w, network, raddr}, err 25 | } 26 | 27 | func (hook *SyslogHook) Fire(entry *logrus.Entry) error { 28 | line, err := entry.String() 29 | if err != nil { 30 | fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err) 31 | return err 32 | } 33 | 34 | switch entry.Level { 35 | case logrus.PanicLevel: 36 | return hook.Writer.Crit(line) 37 | case logrus.FatalLevel: 38 | return hook.Writer.Crit(line) 39 | case logrus.ErrorLevel: 40 | return hook.Writer.Err(line) 41 | case logrus.WarnLevel: 42 | return hook.Writer.Warning(line) 43 | case logrus.InfoLevel: 44 | return hook.Writer.Info(line) 45 | case logrus.DebugLevel: 46 | return hook.Writer.Debug(line) 47 | default: 48 | return nil 49 | } 50 | } 51 | 52 | func (hook *SyslogHook) Levels() []logrus.Level { 53 | return logrus.AllLevels 54 | } 55 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/hooks/test/test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "io/ioutil" 5 | 6 | "github.com/Sirupsen/logrus" 7 | ) 8 | 9 | // test.Hook is a hook designed for dealing with logs in test scenarios. 10 | type Hook struct { 11 | Entries []*logrus.Entry 12 | } 13 | 14 | // Installs a test hook for the global logger. 15 | func NewGlobal() *Hook { 16 | 17 | hook := new(Hook) 18 | logrus.AddHook(hook) 19 | 20 | return hook 21 | 22 | } 23 | 24 | // Installs a test hook for a given local logger. 25 | func NewLocal(logger *logrus.Logger) *Hook { 26 | 27 | hook := new(Hook) 28 | logger.Hooks.Add(hook) 29 | 30 | return hook 31 | 32 | } 33 | 34 | // Creates a discarding logger and installs the test hook. 35 | func NewNullLogger() (*logrus.Logger, *Hook) { 36 | 37 | logger := logrus.New() 38 | logger.Out = ioutil.Discard 39 | 40 | return logger, NewLocal(logger) 41 | 42 | } 43 | 44 | func (t *Hook) Fire(e *logrus.Entry) error { 45 | t.Entries = append(t.Entries, e) 46 | return nil 47 | } 48 | 49 | func (t *Hook) Levels() []logrus.Level { 50 | return logrus.AllLevels 51 | } 52 | 53 | // LastEntry returns the last entry that was logged or nil. 54 | func (t *Hook) LastEntry() (l *logrus.Entry) { 55 | 56 | if i := len(t.Entries) - 1; i < 0 { 57 | return nil 58 | } else { 59 | return t.Entries[i] 60 | } 61 | 62 | } 63 | 64 | // Reset removes all Entries from this test hook. 65 | func (t *Hook) Reset() { 66 | t.Entries = make([]*logrus.Entry, 0) 67 | } 68 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/json_formatter.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type JSONFormatter struct { 9 | // TimestampFormat sets the format used for marshaling timestamps. 10 | TimestampFormat string 11 | } 12 | 13 | func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { 14 | data := make(Fields, len(entry.Data)+3) 15 | for k, v := range entry.Data { 16 | switch v := v.(type) { 17 | case error: 18 | // Otherwise errors are ignored by `encoding/json` 19 | // https://github.com/Sirupsen/logrus/issues/137 20 | data[k] = v.Error() 21 | default: 22 | data[k] = v 23 | } 24 | } 25 | prefixFieldClashes(data) 26 | 27 | timestampFormat := f.TimestampFormat 28 | if timestampFormat == "" { 29 | timestampFormat = DefaultTimestampFormat 30 | } 31 | 32 | data["time"] = entry.Time.Format(timestampFormat) 33 | data["msg"] = entry.Message 34 | data["level"] = entry.Level.String() 35 | 36 | serialized, err := json.Marshal(data) 37 | if err != nil { 38 | return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) 39 | } 40 | return append(serialized, '\n'), nil 41 | } 42 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/terminal_appengine.go: -------------------------------------------------------------------------------- 1 | // +build appengine 2 | 3 | package logrus 4 | 5 | // IsTerminal returns true if stderr's file descriptor is a terminal. 6 | func IsTerminal() bool { 7 | return true 8 | } 9 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/terminal_bsd.go: -------------------------------------------------------------------------------- 1 | // +build darwin freebsd openbsd netbsd dragonfly 2 | // +build !appengine 3 | 4 | package logrus 5 | 6 | import "syscall" 7 | 8 | const ioctlReadTermios = syscall.TIOCGETA 9 | 10 | type Termios syscall.Termios 11 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/terminal_linux.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build !appengine 7 | 8 | package logrus 9 | 10 | import "syscall" 11 | 12 | const ioctlReadTermios = syscall.TCGETS 13 | 14 | type Termios syscall.Termios 15 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/terminal_notwindows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build linux darwin freebsd openbsd netbsd dragonfly 7 | // +build !appengine 8 | 9 | package logrus 10 | 11 | import ( 12 | "syscall" 13 | "unsafe" 14 | ) 15 | 16 | // IsTerminal returns true if stderr's file descriptor is a terminal. 17 | func IsTerminal() bool { 18 | fd := syscall.Stderr 19 | var termios Termios 20 | _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) 21 | return err == 0 22 | } 23 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/terminal_solaris.go: -------------------------------------------------------------------------------- 1 | // +build solaris,!appengine 2 | 3 | package logrus 4 | 5 | import ( 6 | "os" 7 | 8 | "golang.org/x/sys/unix" 9 | ) 10 | 11 | // IsTerminal returns true if the given file descriptor is a terminal. 12 | func IsTerminal() bool { 13 | _, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA) 14 | return err == nil 15 | } 16 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/terminal_windows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build windows,!appengine 7 | 8 | package logrus 9 | 10 | import ( 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | var kernel32 = syscall.NewLazyDLL("kernel32.dll") 16 | 17 | var ( 18 | procGetConsoleMode = kernel32.NewProc("GetConsoleMode") 19 | ) 20 | 21 | // IsTerminal returns true if stderr's file descriptor is a terminal. 22 | func IsTerminal() bool { 23 | fd := syscall.Stderr 24 | var st uint32 25 | r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0) 26 | return r != 0 && e == 0 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/Sirupsen/logrus/writer.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | "runtime" 7 | ) 8 | 9 | func (logger *Logger) Writer() *io.PipeWriter { 10 | return logger.WriterLevel(InfoLevel) 11 | } 12 | 13 | func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { 14 | reader, writer := io.Pipe() 15 | 16 | var printFunc func(args ...interface{}) 17 | switch level { 18 | case DebugLevel: 19 | printFunc = logger.Debug 20 | case InfoLevel: 21 | printFunc = logger.Info 22 | case WarnLevel: 23 | printFunc = logger.Warn 24 | case ErrorLevel: 25 | printFunc = logger.Error 26 | case FatalLevel: 27 | printFunc = logger.Fatal 28 | case PanicLevel: 29 | printFunc = logger.Panic 30 | default: 31 | printFunc = logger.Print 32 | } 33 | 34 | go logger.writerScanner(reader, printFunc) 35 | runtime.SetFinalizer(writer, writerFinalizer) 36 | 37 | return writer 38 | } 39 | 40 | func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { 41 | scanner := bufio.NewScanner(reader) 42 | for scanner.Scan() { 43 | printFunc(scanner.Text()) 44 | } 45 | if err := scanner.Err(); err != nil { 46 | logger.Errorf("Error while reading from Writer: %s", err) 47 | } 48 | reader.Close() 49 | } 50 | 51 | func writerFinalizer(writer *io.PipeWriter) { 52 | writer.Close() 53 | } 54 | -------------------------------------------------------------------------------- /vendor/github.com/beorn7/perks/quantile/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/gogo/protobuf/proto/LICENSE: -------------------------------------------------------------------------------- 1 | Protocol Buffers for Go with Gadgets 2 | 3 | Copyright (c) 2013, The GoGo Authors. All rights reserved. 4 | http://github.com/gogo/protobuf 5 | 6 | Go support for Protocol Buffers - Google's data interchange format 7 | 8 | Copyright 2010 The Go Authors. All rights reserved. 9 | https://github.com/golang/protobuf 10 | 11 | Redistribution and use in source and binary forms, with or without 12 | modification, are permitted provided that the following conditions are 13 | met: 14 | 15 | * Redistributions of source code must retain the above copyright 16 | notice, this list of conditions and the following disclaimer. 17 | * Redistributions in binary form must reproduce the above 18 | copyright notice, this list of conditions and the following disclaimer 19 | in the documentation and/or other materials provided with the 20 | distribution. 21 | * Neither the name of Google Inc. nor the names of its 22 | contributors may be used to endorse or promote products derived from 23 | this software without specific prior written permission. 24 | 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 26 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 27 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 28 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 29 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 30 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 31 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 32 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 33 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 34 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 35 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 | 37 | -------------------------------------------------------------------------------- /vendor/github.com/gogo/protobuf/proto/lib_gogo.go: -------------------------------------------------------------------------------- 1 | // Protocol Buffers for Go with Gadgets 2 | // 3 | // Copyright (c) 2013, The GoGo Authors. All rights reserved. 4 | // http://github.com/gogo/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 | // 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 | package proto 30 | 31 | import ( 32 | "encoding/json" 33 | "strconv" 34 | ) 35 | 36 | func MarshalJSONEnum(m map[int32]string, value int32) ([]byte, error) { 37 | s, ok := m[value] 38 | if !ok { 39 | s = strconv.Itoa(int(value)) 40 | } 41 | return json.Marshal(s) 42 | } 43 | -------------------------------------------------------------------------------- /vendor/github.com/gogo/protobuf/proto/text_gogo.go: -------------------------------------------------------------------------------- 1 | // Protocol Buffers for Go with Gadgets 2 | // 3 | // Copyright (c) 2013, The GoGo Authors. All rights reserved. 4 | // http://github.com/gogo/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 | // 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 | package proto 30 | 31 | import ( 32 | "fmt" 33 | "reflect" 34 | ) 35 | 36 | func (tm *TextMarshaler) writeEnum(w *textWriter, v reflect.Value, props *Properties) error { 37 | m, ok := enumStringMaps[props.Enum] 38 | if !ok { 39 | if err := tm.writeAny(w, v, props); err != nil { 40 | return err 41 | } 42 | } 43 | key := int32(0) 44 | if v.Kind() == reflect.Ptr { 45 | key = int32(v.Elem().Int()) 46 | } else { 47 | key = int32(v.Int()) 48 | } 49 | s, ok := m[key] 50 | if !ok { 51 | if err := tm.writeAny(w, v, props); err != nil { 52 | return err 53 | } 54 | } 55 | _, err := fmt.Fprint(w, s) 56 | return err 57 | } 58 | -------------------------------------------------------------------------------- /vendor/github.com/gogo/protobuf/sortkeys/LICENSE: -------------------------------------------------------------------------------- 1 | Protocol Buffers for Go with Gadgets 2 | 3 | Copyright (c) 2013, The GoGo Authors. All rights reserved. 4 | http://github.com/gogo/protobuf 5 | 6 | Go support for Protocol Buffers - Google's data interchange format 7 | 8 | Copyright 2010 The Go Authors. All rights reserved. 9 | https://github.com/golang/protobuf 10 | 11 | Redistribution and use in source and binary forms, with or without 12 | modification, are permitted provided that the following conditions are 13 | met: 14 | 15 | * Redistributions of source code must retain the above copyright 16 | notice, this list of conditions and the following disclaimer. 17 | * Redistributions in binary form must reproduce the above 18 | copyright notice, this list of conditions and the following disclaimer 19 | in the documentation and/or other materials provided with the 20 | distribution. 21 | * Neither the name of Google Inc. nor the names of its 22 | contributors may be used to endorse or promote products derived from 23 | this software without specific prior written permission. 24 | 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 26 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 27 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 28 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 29 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 30 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 31 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 32 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 33 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 34 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 35 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 | 37 | -------------------------------------------------------------------------------- /vendor/github.com/gogo/protobuf/types/LICENSE: -------------------------------------------------------------------------------- 1 | Protocol Buffers for Go with Gadgets 2 | 3 | Copyright (c) 2013, The GoGo Authors. All rights reserved. 4 | http://github.com/gogo/protobuf 5 | 6 | Go support for Protocol Buffers - Google's data interchange format 7 | 8 | Copyright 2010 The Go Authors. All rights reserved. 9 | https://github.com/golang/protobuf 10 | 11 | Redistribution and use in source and binary forms, with or without 12 | modification, are permitted provided that the following conditions are 13 | met: 14 | 15 | * Redistributions of source code must retain the above copyright 16 | notice, this list of conditions and the following disclaimer. 17 | * Redistributions in binary form must reproduce the above 18 | copyright notice, this list of conditions and the following disclaimer 19 | in the documentation and/or other materials provided with the 20 | distribution. 21 | * Neither the name of Google Inc. nor the names of its 22 | contributors may be used to endorse or promote products derived from 23 | this software without specific prior written permission. 24 | 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 26 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 27 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 28 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 29 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 30 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 31 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 32 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 33 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 34 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 35 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 | 37 | -------------------------------------------------------------------------------- /vendor/github.com/gogo/protobuf/types/doc.go: -------------------------------------------------------------------------------- 1 | // Go support for Protocol Buffers - Google's data interchange format 2 | // 3 | // Copyright 2016 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 | /* 33 | Package types contains code for interacting with well-known types. 34 | */ 35 | package types 36 | -------------------------------------------------------------------------------- /vendor/github.com/gogo/protobuf/types/duration_gogo.go: -------------------------------------------------------------------------------- 1 | // Protocol Buffers for Go with Gadgets 2 | // 3 | // Copyright (c) 2016, The GoGo Authors. All rights reserved. 4 | // http://github.com/gogo/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 | // 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 | package types 30 | 31 | import ( 32 | "fmt" 33 | "time" 34 | ) 35 | 36 | func NewPopulatedDuration(r interface { 37 | Int63() int64 38 | }, easy bool) *Duration { 39 | this := &Duration{} 40 | maxSecs := time.Hour.Nanoseconds() / 1e9 41 | max := 2 * maxSecs 42 | s := int64(r.Int63()) % max 43 | s -= maxSecs 44 | neg := int64(1) 45 | if s < 0 { 46 | neg = -1 47 | } 48 | this.Seconds = s 49 | this.Nanos = int32(neg * (r.Int63() % 1e9)) 50 | return this 51 | } 52 | 53 | func (d *Duration) String() string { 54 | td, err := DurationFromProto(d) 55 | if err != nil { 56 | return fmt.Sprintf("(%v)", err) 57 | } 58 | return td.String() 59 | } 60 | 61 | func NewPopulatedStdDuration(r interface { 62 | Int63() int64 63 | }, easy bool) *time.Duration { 64 | dur := NewPopulatedDuration(r, easy) 65 | d, err := DurationFromProto(dur) 66 | if err != nil { 67 | return nil 68 | } 69 | return &d 70 | } 71 | 72 | func SizeOfStdDuration(d time.Duration) int { 73 | dur := DurationProto(d) 74 | return dur.Size() 75 | } 76 | 77 | func StdDurationMarshal(d time.Duration) ([]byte, error) { 78 | size := SizeOfStdDuration(d) 79 | buf := make([]byte, size) 80 | _, err := StdDurationMarshalTo(d, buf) 81 | return buf, err 82 | } 83 | 84 | func StdDurationMarshalTo(d time.Duration, data []byte) (int, error) { 85 | dur := DurationProto(d) 86 | return dur.MarshalTo(data) 87 | } 88 | 89 | func StdDurationUnmarshal(d *time.Duration, data []byte) error { 90 | dur := &Duration{} 91 | if err := dur.Unmarshal(data); err != nil { 92 | return err 93 | } 94 | dd, err := DurationFromProto(dur) 95 | if err != nil { 96 | return err 97 | } 98 | *d = dd 99 | return nil 100 | } 101 | -------------------------------------------------------------------------------- /vendor/github.com/gogo/protobuf/types/timestamp_gogo.go: -------------------------------------------------------------------------------- 1 | // Protocol Buffers for Go with Gadgets 2 | // 3 | // Copyright (c) 2016, The GoGo Authors. All rights reserved. 4 | // http://github.com/gogo/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 | // 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 | package types 30 | 31 | import ( 32 | "time" 33 | ) 34 | 35 | func NewPopulatedTimestamp(r interface { 36 | Int63() int64 37 | }, easy bool) *Timestamp { 38 | this := &Timestamp{} 39 | ns := int64(r.Int63()) 40 | this.Seconds = ns / 1e9 41 | this.Nanos = int32(ns % 1e9) 42 | return this 43 | } 44 | 45 | func (ts *Timestamp) String() string { 46 | return TimestampString(ts) 47 | } 48 | 49 | func NewPopulatedStdTime(r interface { 50 | Int63() int64 51 | }, easy bool) *time.Time { 52 | timestamp := NewPopulatedTimestamp(r, easy) 53 | t, err := TimestampFromProto(timestamp) 54 | if err != nil { 55 | return nil 56 | } 57 | return &t 58 | } 59 | 60 | func SizeOfStdTime(t time.Time) int { 61 | ts, err := TimestampProto(t) 62 | if err != nil { 63 | return 0 64 | } 65 | return ts.Size() 66 | } 67 | 68 | func StdTimeMarshal(t time.Time) ([]byte, error) { 69 | size := SizeOfStdTime(t) 70 | buf := make([]byte, size) 71 | _, err := StdTimeMarshalTo(t, buf) 72 | return buf, err 73 | } 74 | 75 | func StdTimeMarshalTo(t time.Time, data []byte) (int, error) { 76 | ts, err := TimestampProto(t) 77 | if err != nil { 78 | return 0, err 79 | } 80 | return ts.MarshalTo(data) 81 | } 82 | 83 | func StdTimeUnmarshal(t *time.Time, data []byte) error { 84 | ts := &Timestamp{} 85 | if err := ts.Unmarshal(data); err != nil { 86 | return err 87 | } 88 | tt, err := TimestampFromProto(ts) 89 | if err != nil { 90 | return err 91 | } 92 | *t = tt 93 | return nil 94 | } 95 | -------------------------------------------------------------------------------- /vendor/github.com/golang/protobuf/proto/LICENSE: -------------------------------------------------------------------------------- 1 | Go support for Protocol Buffers - Google's data interchange format 2 | 3 | Copyright 2010 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 | -------------------------------------------------------------------------------- /vendor/github.com/golang/protobuf/ptypes/any/LICENSE: -------------------------------------------------------------------------------- 1 | Go support for Protocol Buffers - Google's data interchange format 2 | 3 | Copyright 2010 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 | -------------------------------------------------------------------------------- /vendor/github.com/golang/snappy/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/github.com/golang/snappy/cmd/snappytool/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | To build the snappytool binary: 3 | g++ main.cpp /usr/lib/libsnappy.a -o snappytool 4 | or, if you have built the C++ snappy library from source: 5 | g++ main.cpp /path/to/your/snappy/.libs/libsnappy.a -o snappytool 6 | after running "make" from your snappy checkout directory. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "snappy.h" 15 | 16 | #define N 1000000 17 | 18 | char dst[N]; 19 | char src[N]; 20 | 21 | int main(int argc, char** argv) { 22 | // Parse args. 23 | if (argc != 2) { 24 | fprintf(stderr, "exactly one of -d or -e must be given\n"); 25 | return 1; 26 | } 27 | bool decode = strcmp(argv[1], "-d") == 0; 28 | bool encode = strcmp(argv[1], "-e") == 0; 29 | if (decode == encode) { 30 | fprintf(stderr, "exactly one of -d or -e must be given\n"); 31 | return 1; 32 | } 33 | 34 | // Read all of stdin into src[:s]. 35 | size_t s = 0; 36 | while (1) { 37 | if (s == N) { 38 | fprintf(stderr, "input too large\n"); 39 | return 1; 40 | } 41 | ssize_t n = read(0, src+s, N-s); 42 | if (n == 0) { 43 | break; 44 | } 45 | if (n < 0) { 46 | fprintf(stderr, "read error: %s\n", strerror(errno)); 47 | // TODO: handle EAGAIN, EINTR? 48 | return 1; 49 | } 50 | s += n; 51 | } 52 | 53 | // Encode or decode src[:s] to dst[:d], and write to stdout. 54 | size_t d = 0; 55 | if (encode) { 56 | if (N < snappy::MaxCompressedLength(s)) { 57 | fprintf(stderr, "input too large after encoding\n"); 58 | return 1; 59 | } 60 | snappy::RawCompress(src, s, dst, &d); 61 | } else { 62 | if (!snappy::GetUncompressedLength(src, s, &d)) { 63 | fprintf(stderr, "could not get uncompressed length\n"); 64 | return 1; 65 | } 66 | if (N < d) { 67 | fprintf(stderr, "input too large after decoding\n"); 68 | return 1; 69 | } 70 | if (!snappy::RawUncompress(src, s, dst)) { 71 | fprintf(stderr, "input was not valid Snappy-compressed data\n"); 72 | return 1; 73 | } 74 | } 75 | write(1, dst, d); 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /vendor/github.com/golang/snappy/decode_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Snappy-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 !appengine 6 | // +build gc 7 | // +build !noasm 8 | 9 | package snappy 10 | 11 | // decode has the same semantics as in decode_other.go. 12 | // 13 | //go:noescape 14 | func decode(dst, src []byte) int 15 | -------------------------------------------------------------------------------- /vendor/github.com/golang/snappy/encode_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Snappy-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 !appengine 6 | // +build gc 7 | // +build !noasm 8 | 9 | package snappy 10 | 11 | // emitLiteral has the same semantics as in encode_other.go. 12 | // 13 | //go:noescape 14 | func emitLiteral(dst, lit []byte) int 15 | 16 | // emitCopy has the same semantics as in encode_other.go. 17 | // 18 | //go:noescape 19 | func emitCopy(dst []byte, offset, length int) int 20 | 21 | // extendMatch has the same semantics as in encode_other.go. 22 | // 23 | //go:noescape 24 | func extendMatch(src []byte, i, j int) int 25 | 26 | // encodeBlock has the same semantics as in encode_other.go. 27 | // 28 | //go:noescape 29 | func encodeBlock(dst, src []byte) (d int) -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/models/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013-2016 Errplane Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/models/consistency.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "errors" 5 | "strings" 6 | ) 7 | 8 | // ConsistencyLevel represent a required replication criteria before a write can 9 | // be returned as successful 10 | type ConsistencyLevel int 11 | 12 | const ( 13 | // ConsistencyLevelAny allows for hinted hand off, potentially no write happened yet 14 | ConsistencyLevelAny ConsistencyLevel = iota 15 | 16 | // ConsistencyLevelOne requires at least one data node acknowledged a write 17 | ConsistencyLevelOne 18 | 19 | // ConsistencyLevelQuorum requires a quorum of data nodes to acknowledge a write 20 | ConsistencyLevelQuorum 21 | 22 | // ConsistencyLevelAll requires all data nodes to acknowledge a write 23 | ConsistencyLevelAll 24 | ) 25 | 26 | var ( 27 | // ErrInvalidConsistencyLevel is returned when parsing the string version 28 | // of a consistency level. 29 | ErrInvalidConsistencyLevel = errors.New("invalid consistency level") 30 | ) 31 | 32 | // ParseConsistencyLevel converts a consistency level string to the corresponding ConsistencyLevel const 33 | func ParseConsistencyLevel(level string) (ConsistencyLevel, error) { 34 | switch strings.ToLower(level) { 35 | case "any": 36 | return ConsistencyLevelAny, nil 37 | case "one": 38 | return ConsistencyLevelOne, nil 39 | case "quorum": 40 | return ConsistencyLevelQuorum, nil 41 | case "all": 42 | return ConsistencyLevelAll, nil 43 | default: 44 | return 0, ErrInvalidConsistencyLevel 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/models/inline_fnv.go: -------------------------------------------------------------------------------- 1 | package models // import "github.com/influxdata/influxdb/models" 2 | 3 | // from stdlib hash/fnv/fnv.go 4 | const ( 5 | prime64 = 1099511628211 6 | offset64 = 14695981039346656037 7 | ) 8 | 9 | // InlineFNV64a is an alloc-free port of the standard library's fnv64a. 10 | type InlineFNV64a uint64 11 | 12 | func NewInlineFNV64a() InlineFNV64a { 13 | return offset64 14 | } 15 | 16 | func (s *InlineFNV64a) Write(data []byte) (int, error) { 17 | hash := uint64(*s) 18 | for _, c := range data { 19 | hash ^= uint64(c) 20 | hash *= prime64 21 | } 22 | *s = InlineFNV64a(hash) 23 | return len(data), nil 24 | } 25 | func (s *InlineFNV64a) Sum64() uint64 { 26 | return uint64(*s) 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/models/inline_strconv_parse.go: -------------------------------------------------------------------------------- 1 | package models // import "github.com/influxdata/influxdb/models" 2 | 3 | import ( 4 | "reflect" 5 | "strconv" 6 | "unsafe" 7 | ) 8 | 9 | // parseIntBytes is a zero-alloc wrapper around strconv.ParseInt. 10 | func parseIntBytes(b []byte, base int, bitSize int) (i int64, err error) { 11 | s := unsafeBytesToString(b) 12 | return strconv.ParseInt(s, base, bitSize) 13 | } 14 | 15 | // parseFloatBytes is a zero-alloc wrapper around strconv.ParseFloat. 16 | func parseFloatBytes(b []byte, bitSize int) (float64, error) { 17 | s := unsafeBytesToString(b) 18 | return strconv.ParseFloat(s, bitSize) 19 | } 20 | 21 | // parseBoolBytes is a zero-alloc wrapper around strconv.ParseBool. 22 | func parseBoolBytes(b []byte) (bool, error) { 23 | return strconv.ParseBool(unsafeBytesToString(b)) 24 | } 25 | 26 | // unsafeBytesToString converts a []byte to a string without a heap allocation. 27 | // 28 | // It is unsafe, and is intended to prepare input to short-lived functions 29 | // that require strings. 30 | func unsafeBytesToString(in []byte) string { 31 | src := *(*reflect.SliceHeader)(unsafe.Pointer(&in)) 32 | dst := reflect.StringHeader{ 33 | Data: src.Data, 34 | Len: src.Len, 35 | } 36 | s := *(*string)(unsafe.Pointer(&dst)) 37 | return s 38 | } 39 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/models/rows.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | // Row represents a single row returned from the execution of a statement. 8 | type Row struct { 9 | Name string `json:"name,omitempty"` 10 | Tags map[string]string `json:"tags,omitempty"` 11 | Columns []string `json:"columns,omitempty"` 12 | Values [][]interface{} `json:"values,omitempty"` 13 | } 14 | 15 | // SameSeries returns true if r contains values for the same series as o. 16 | func (r *Row) SameSeries(o *Row) bool { 17 | return r.tagsHash() == o.tagsHash() && r.Name == o.Name 18 | } 19 | 20 | // tagsHash returns a hash of tag key/value pairs. 21 | func (r *Row) tagsHash() uint64 { 22 | h := NewInlineFNV64a() 23 | keys := r.tagsKeys() 24 | for _, k := range keys { 25 | h.Write([]byte(k)) 26 | h.Write([]byte(r.Tags[k])) 27 | } 28 | return h.Sum64() 29 | } 30 | 31 | // tagKeys returns a sorted list of tag keys. 32 | func (r *Row) tagsKeys() []string { 33 | a := make([]string, 0, len(r.Tags)) 34 | for k := range r.Tags { 35 | a = append(a, k) 36 | } 37 | sort.Strings(a) 38 | return a 39 | } 40 | 41 | // Rows represents a collection of rows. Rows implements sort.Interface. 42 | type Rows []*Row 43 | 44 | func (p Rows) Len() int { return len(p) } 45 | 46 | func (p Rows) Less(i, j int) bool { 47 | // Sort by name first. 48 | if p[i].Name != p[j].Name { 49 | return p[i].Name < p[j].Name 50 | } 51 | 52 | // Sort by tag set hash. Tags don't have a meaningful sort order so we 53 | // just compute a hash and sort by that instead. This allows the tests 54 | // to receive rows in a predictable order every time. 55 | return p[i].tagsHash() < p[j].tagsHash() 56 | } 57 | 58 | func (p Rows) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 59 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/models/statistic.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type Statistic struct { 4 | Name string `json:"name"` 5 | Tags map[string]string `json:"tags"` 6 | Values map[string]interface{} `json:"values"` 7 | } 8 | 9 | func NewStatistic(name string) Statistic { 10 | return Statistic{ 11 | Name: name, 12 | Tags: make(map[string]string), 13 | Values: make(map[string]interface{}), 14 | } 15 | } 16 | 17 | // StatisticTags is a map that can be merged with others without causing 18 | // mutations to either map. 19 | type StatisticTags map[string]string 20 | 21 | // Merge creates a new map containing the merged contents of tags and t. 22 | // If both tags and the receiver map contain the same key, the value in tags 23 | // is used in the resulting map. 24 | // 25 | // Merge always returns a usable map. 26 | func (t StatisticTags) Merge(tags map[string]string) map[string]string { 27 | // Add everything in tags to the result. 28 | out := make(map[string]string, len(tags)) 29 | for k, v := range tags { 30 | out[k] = v 31 | } 32 | 33 | // Only add values from t that don't appear in tags. 34 | for k, v := range t { 35 | if _, ok := tags[k]; !ok { 36 | out[k] = v 37 | } 38 | } 39 | return out 40 | } 41 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/models/time.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | // Helper time methods since parsing time can easily overflow and we only support a 4 | // specific time range. 5 | 6 | import ( 7 | "fmt" 8 | "math" 9 | "time" 10 | ) 11 | 12 | const ( 13 | // MinNanoTime is the minumum time that can be represented. 14 | // 15 | // 1677-09-21 00:12:43.145224194 +0000 UTC 16 | // 17 | // The two lowest minimum integers are used as sentinel values. The 18 | // minimum value needs to be used as a value lower than any other value for 19 | // comparisons and another separate value is needed to act as a sentinel 20 | // default value that is unusable by the user, but usable internally. 21 | // Because these two values need to be used for a special purpose, we do 22 | // not allow users to write points at these two times. 23 | MinNanoTime = int64(math.MinInt64) + 2 24 | 25 | // MaxNanoTime is the maximum time that can be represented. 26 | // 27 | // 2262-04-11 23:47:16.854775806 +0000 UTC 28 | // 29 | // The highest time represented by a nanosecond needs to be used for an 30 | // exclusive range in the shard group, so the maximum time needs to be one 31 | // less than the possible maximum number of nanoseconds representable by an 32 | // int64 so that we don't lose a point at that one time. 33 | MaxNanoTime = int64(math.MaxInt64) - 1 34 | ) 35 | 36 | var ( 37 | minNanoTime = time.Unix(0, MinNanoTime).UTC() 38 | maxNanoTime = time.Unix(0, MaxNanoTime).UTC() 39 | 40 | // ErrTimeOutOfRange gets returned when time is out of the representable range using int64 nanoseconds since the epoch. 41 | ErrTimeOutOfRange = fmt.Errorf("time outside range %d - %d", MinNanoTime, MaxNanoTime) 42 | ) 43 | 44 | // SafeCalcTime safely calculates the time given. Will return error if the time is outside the 45 | // supported range. 46 | func SafeCalcTime(timestamp int64, precision string) (time.Time, error) { 47 | mult := GetPrecisionMultiplier(precision) 48 | if t, ok := safeSignedMult(timestamp, mult); ok { 49 | tme := time.Unix(0, t).UTC() 50 | return tme, CheckTime(tme) 51 | } 52 | 53 | return time.Time{}, ErrTimeOutOfRange 54 | } 55 | 56 | // CheckTime checks that a time is within the safe range. 57 | func CheckTime(t time.Time) error { 58 | if t.Before(minNanoTime) || t.After(maxNanoTime) { 59 | return ErrTimeOutOfRange 60 | } 61 | return nil 62 | } 63 | 64 | // Perform the multiplication and check to make sure it didn't overflow. 65 | func safeSignedMult(a, b int64) (int64, bool) { 66 | if a == 0 || b == 0 || a == 1 || b == 1 { 67 | return a * b, true 68 | } 69 | if a == MinNanoTime || b == MaxNanoTime { 70 | return 0, false 71 | } 72 | c := a * b 73 | return c, c/b == a 74 | } 75 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/pkg/escape/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013-2016 Errplane Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/pkg/escape/bytes.go: -------------------------------------------------------------------------------- 1 | package escape // import "github.com/influxdata/influxdb/pkg/escape" 2 | 3 | import ( 4 | "bytes" 5 | "strings" 6 | ) 7 | 8 | func Bytes(in []byte) []byte { 9 | for b, esc := range Codes { 10 | in = bytes.Replace(in, []byte{b}, esc, -1) 11 | } 12 | return in 13 | } 14 | 15 | const escapeChars = `," =` 16 | 17 | func IsEscaped(b []byte) bool { 18 | for len(b) > 0 { 19 | i := bytes.IndexByte(b, '\\') 20 | if i < 0 { 21 | return false 22 | } 23 | 24 | if i+1 < len(b) && strings.IndexByte(escapeChars, b[i+1]) >= 0 { 25 | return true 26 | } 27 | b = b[i+1:] 28 | } 29 | return false 30 | } 31 | 32 | func AppendUnescaped(dst, src []byte) []byte { 33 | var pos int 34 | for len(src) > 0 { 35 | next := bytes.IndexByte(src[pos:], '\\') 36 | if next < 0 || pos+next+1 >= len(src) { 37 | return append(dst, src...) 38 | } 39 | 40 | if pos+next+1 < len(src) && strings.IndexByte(escapeChars, src[pos+next+1]) >= 0 { 41 | if pos+next > 0 { 42 | dst = append(dst, src[:pos+next]...) 43 | } 44 | src = src[pos+next+1:] 45 | pos = 0 46 | } else { 47 | pos += next + 1 48 | } 49 | } 50 | 51 | return dst 52 | } 53 | 54 | func Unescape(in []byte) []byte { 55 | if len(in) == 0 { 56 | return nil 57 | } 58 | 59 | if bytes.IndexByte(in, '\\') == -1 { 60 | return in 61 | } 62 | 63 | i := 0 64 | inLen := len(in) 65 | var out []byte 66 | 67 | for { 68 | if i >= inLen { 69 | break 70 | } 71 | if in[i] == '\\' && i+1 < inLen { 72 | switch in[i+1] { 73 | case ',': 74 | out = append(out, ',') 75 | i += 2 76 | continue 77 | case '"': 78 | out = append(out, '"') 79 | i += 2 80 | continue 81 | case ' ': 82 | out = append(out, ' ') 83 | i += 2 84 | continue 85 | case '=': 86 | out = append(out, '=') 87 | i += 2 88 | continue 89 | } 90 | } 91 | out = append(out, in[i]) 92 | i += 1 93 | } 94 | return out 95 | } 96 | -------------------------------------------------------------------------------- /vendor/github.com/influxdata/influxdb/pkg/escape/strings.go: -------------------------------------------------------------------------------- 1 | package escape 2 | 3 | import "strings" 4 | 5 | var ( 6 | Codes = map[byte][]byte{ 7 | ',': []byte(`\,`), 8 | '"': []byte(`\"`), 9 | ' ': []byte(`\ `), 10 | '=': []byte(`\=`), 11 | } 12 | 13 | codesStr = map[string]string{} 14 | ) 15 | 16 | func init() { 17 | for k, v := range Codes { 18 | codesStr[string(k)] = string(v) 19 | } 20 | } 21 | 22 | func UnescapeString(in string) string { 23 | if strings.IndexByte(in, '\\') == -1 { 24 | return in 25 | } 26 | 27 | for b, esc := range codesStr { 28 | in = strings.Replace(in, esc, b, -1) 29 | } 30 | return in 31 | } 32 | 33 | func String(in string) string { 34 | for b, esc := range codesStr { 35 | in = strings.Replace(in, b, esc, -1) 36 | } 37 | return in 38 | } 39 | -------------------------------------------------------------------------------- /vendor/github.com/influxdb/influxdb/client/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013-2016 Errplane Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /vendor/github.com/influxdb/influxdb/client/v2/udp.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "net" 7 | "time" 8 | ) 9 | 10 | const ( 11 | // UDPPayloadSize is a reasonable default payload size for UDP packets that 12 | // could be travelling over the internet. 13 | UDPPayloadSize = 512 14 | ) 15 | 16 | // UDPConfig is the config data needed to create a UDP Client 17 | type UDPConfig struct { 18 | // Addr should be of the form "host:port" 19 | // or "[ipv6-host%zone]:port". 20 | Addr string 21 | 22 | // PayloadSize is the maximum size of a UDP client message, optional 23 | // Tune this based on your network. Defaults to UDPPayloadSize. 24 | PayloadSize int 25 | } 26 | 27 | // NewUDPClient returns a client interface for writing to an InfluxDB UDP 28 | // service from the given config. 29 | func NewUDPClient(conf UDPConfig) (Client, error) { 30 | var udpAddr *net.UDPAddr 31 | udpAddr, err := net.ResolveUDPAddr("udp", conf.Addr) 32 | if err != nil { 33 | return nil, err 34 | } 35 | 36 | conn, err := net.DialUDP("udp", nil, udpAddr) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | payloadSize := conf.PayloadSize 42 | if payloadSize == 0 { 43 | payloadSize = UDPPayloadSize 44 | } 45 | 46 | return &udpclient{ 47 | conn: conn, 48 | payloadSize: payloadSize, 49 | }, nil 50 | } 51 | 52 | // Close releases the udpclient's resources. 53 | func (uc *udpclient) Close() error { 54 | return uc.conn.Close() 55 | } 56 | 57 | type udpclient struct { 58 | conn io.WriteCloser 59 | payloadSize int 60 | } 61 | 62 | func (uc *udpclient) Write(bp BatchPoints) error { 63 | var b = make([]byte, 0, uc.payloadSize) // initial buffer size, it will grow as needed 64 | var d, _ = time.ParseDuration("1" + bp.Precision()) 65 | 66 | var delayedError error 67 | 68 | var checkBuffer = func(n int) { 69 | if len(b) > 0 && len(b)+n > uc.payloadSize { 70 | if _, err := uc.conn.Write(b); err != nil { 71 | delayedError = err 72 | } 73 | b = b[:0] 74 | } 75 | } 76 | 77 | for _, p := range bp.Points() { 78 | p.pt.Round(d) 79 | pointSize := p.pt.StringSize() + 1 // include newline in size 80 | //point := p.pt.RoundedString(d) + "\n" 81 | 82 | checkBuffer(pointSize) 83 | 84 | if p.Time().IsZero() || pointSize <= uc.payloadSize { 85 | b = p.pt.AppendString(b) 86 | b = append(b, '\n') 87 | continue 88 | } 89 | 90 | points := p.pt.Split(uc.payloadSize - 1) // account for newline character 91 | for _, sp := range points { 92 | checkBuffer(sp.StringSize() + 1) 93 | b = sp.AppendString(b) 94 | b = append(b, '\n') 95 | } 96 | } 97 | 98 | if len(b) > 0 { 99 | if _, err := uc.conn.Write(b); err != nil { 100 | return err 101 | } 102 | } 103 | return delayedError 104 | } 105 | 106 | func (uc *udpclient) Query(q Query) (*Response, error) { 107 | return nil, fmt.Errorf("Querying via UDP is not supported") 108 | } 109 | 110 | func (uc *udpclient) Ping(timeout time.Duration) (time.Duration, string, error) { 111 | return 0, "", nil 112 | } 113 | -------------------------------------------------------------------------------- /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/prometheus/fnv.go: -------------------------------------------------------------------------------- 1 | package prometheus 2 | 3 | // Inline and byte-free variant of hash/fnv's fnv64a. 4 | 5 | const ( 6 | offset64 = 14695981039346656037 7 | prime64 = 1099511628211 8 | ) 9 | 10 | // hashNew initializies a new fnv64a hash value. 11 | func hashNew() uint64 { 12 | return offset64 13 | } 14 | 15 | // hashAdd adds a string to a fnv64a hash value, returning the updated hash. 16 | func hashAdd(h uint64, s string) uint64 { 17 | for i := 0; i < len(s); i++ { 18 | h ^= uint64(s[i]) 19 | h *= prime64 20 | } 21 | return h 22 | } 23 | 24 | // hashAddByte adds a byte to a fnv64a hash value, returning the updated hash. 25 | func hashAddByte(h uint64, b byte) uint64 { 26 | h ^= uint64(b) 27 | h *= prime64 28 | return h 29 | } 30 | -------------------------------------------------------------------------------- /vendor/github.com/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 | // A package for reading and writing Prometheus metrics. 15 | package expfmt 16 | 17 | type Format string 18 | 19 | const ( 20 | TextVersion = "0.0.4" 21 | 22 | ProtoType = `application/vnd.google.protobuf` 23 | ProtoProtocol = `io.prometheus.client.MetricFamily` 24 | ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" 25 | 26 | // The Content-Type values for the different wire protocols. 27 | FmtUnknown Format = `` 28 | FmtText Format = `text/plain; version=` + TextVersion 29 | FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` 30 | FmtProtoText Format = ProtoFmt + ` encoding=text` 31 | FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` 32 | ) 33 | 34 | const ( 35 | hdrContentType = "Content-Type" 36 | hdrAccept = "Accept" 37 | ) 38 | -------------------------------------------------------------------------------- /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/log/eventlog_formatter.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 | // +build windows 15 | 16 | package log 17 | 18 | import ( 19 | "fmt" 20 | "os" 21 | 22 | "golang.org/x/sys/windows/svc/eventlog" 23 | 24 | "github.com/Sirupsen/logrus" 25 | ) 26 | 27 | func init() { 28 | setEventlogFormatter = func(name string, debugAsInfo bool) error { 29 | if name == "" { 30 | return fmt.Errorf("missing name parameter") 31 | } 32 | 33 | fmter, err := newEventlogger(name, debugAsInfo, origLogger.Formatter) 34 | if err != nil { 35 | fmt.Fprintf(os.Stderr, "error creating eventlog formatter: %v\n", err) 36 | origLogger.Errorf("can't connect logger to eventlog: %v", err) 37 | return err 38 | } 39 | origLogger.Formatter = fmter 40 | return nil 41 | } 42 | } 43 | 44 | type eventlogger struct { 45 | log *eventlog.Log 46 | debugAsInfo bool 47 | wrap logrus.Formatter 48 | } 49 | 50 | func newEventlogger(name string, debugAsInfo bool, fmter logrus.Formatter) (*eventlogger, error) { 51 | logHandle, err := eventlog.Open(name) 52 | if err != nil { 53 | return nil, err 54 | } 55 | return &eventlogger{log: logHandle, debugAsInfo: debugAsInfo, wrap: fmter}, nil 56 | } 57 | 58 | func (s *eventlogger) Format(e *logrus.Entry) ([]byte, error) { 59 | data, err := s.wrap.Format(e) 60 | if err != nil { 61 | fmt.Fprintf(os.Stderr, "eventlogger: can't format entry: %v\n", err) 62 | return data, err 63 | } 64 | 65 | switch e.Level { 66 | case logrus.PanicLevel: 67 | fallthrough 68 | case logrus.FatalLevel: 69 | fallthrough 70 | case logrus.ErrorLevel: 71 | err = s.log.Error(102, e.Message) 72 | case logrus.WarnLevel: 73 | err = s.log.Warning(101, e.Message) 74 | case logrus.InfoLevel: 75 | err = s.log.Info(100, e.Message) 76 | case logrus.DebugLevel: 77 | if s.debugAsInfo { 78 | err = s.log.Info(100, e.Message) 79 | } 80 | default: 81 | err = s.log.Info(100, e.Message) 82 | } 83 | 84 | if err != nil { 85 | fmt.Fprintf(os.Stderr, "eventlogger: can't send log to eventlog: %v\n", err) 86 | } 87 | 88 | return data, err 89 | } 90 | -------------------------------------------------------------------------------- /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/metric.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package model 15 | 16 | import ( 17 | "fmt" 18 | "regexp" 19 | "sort" 20 | "strings" 21 | ) 22 | 23 | var ( 24 | separator = []byte{0} 25 | MetricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`) 26 | ) 27 | 28 | // A Metric is similar to a LabelSet, but the key difference is that a Metric is 29 | // a singleton and refers to one and only one stream of samples. 30 | type Metric LabelSet 31 | 32 | // Equal compares the metrics. 33 | func (m Metric) Equal(o Metric) bool { 34 | return LabelSet(m).Equal(LabelSet(o)) 35 | } 36 | 37 | // Before compares the metrics' underlying label sets. 38 | func (m Metric) Before(o Metric) bool { 39 | return LabelSet(m).Before(LabelSet(o)) 40 | } 41 | 42 | // Clone returns a copy of the Metric. 43 | func (m Metric) Clone() Metric { 44 | clone := Metric{} 45 | for k, v := range m { 46 | clone[k] = v 47 | } 48 | return clone 49 | } 50 | 51 | func (m Metric) String() string { 52 | metricName, hasName := m[MetricNameLabel] 53 | numLabels := len(m) - 1 54 | if !hasName { 55 | numLabels = len(m) 56 | } 57 | labelStrings := make([]string, 0, numLabels) 58 | for label, value := range m { 59 | if label != MetricNameLabel { 60 | labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value)) 61 | } 62 | } 63 | 64 | switch numLabels { 65 | case 0: 66 | if hasName { 67 | return string(metricName) 68 | } 69 | return "{}" 70 | default: 71 | sort.Strings(labelStrings) 72 | return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", ")) 73 | } 74 | } 75 | 76 | // Fingerprint returns a Metric's Fingerprint. 77 | func (m Metric) Fingerprint() Fingerprint { 78 | return LabelSet(m).Fingerprint() 79 | } 80 | 81 | // FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing 82 | // algorithm, which is, however, more susceptible to hash collisions. 83 | func (m Metric) FastFingerprint() Fingerprint { 84 | return LabelSet(m).FastFingerprint() 85 | } 86 | 87 | // IsValidMetricName returns true iff name matches the pattern of MetricNameRE. 88 | func IsValidMetricName(n LabelValue) bool { 89 | if len(n) == 0 { 90 | return false 91 | } 92 | for i, b := range n { 93 | if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == ':' || (b >= '0' && b <= '9' && i > 0)) { 94 | return false 95 | } 96 | } 97 | return true 98 | } 99 | -------------------------------------------------------------------------------- /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/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 | package procfs 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path" 7 | ) 8 | 9 | // FS represents the pseudo-filesystem proc, which provides an interface to 10 | // kernel data structures. 11 | type FS string 12 | 13 | // DefaultMountPoint is the common mount point of the proc filesystem. 14 | const DefaultMountPoint = "/proc" 15 | 16 | // NewFS returns a new FS mounted under the given mountPoint. It will error 17 | // if the mount point can't be read. 18 | func NewFS(mountPoint string) (FS, error) { 19 | info, err := os.Stat(mountPoint) 20 | if err != nil { 21 | return "", fmt.Errorf("could not read %s: %s", mountPoint, err) 22 | } 23 | if !info.IsDir() { 24 | return "", fmt.Errorf("mount point %s is not a directory", mountPoint) 25 | } 26 | 27 | return FS(mountPoint), nil 28 | } 29 | 30 | // Path returns the path of the given subsystem relative to the procfs root. 31 | func (fs FS) Path(p ...string) string { 32 | return path.Join(append([]string{string(fs)}, p...)...) 33 | } 34 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/proc_io.go: -------------------------------------------------------------------------------- 1 | package procfs 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | ) 8 | 9 | // ProcIO models the content of /proc//io. 10 | type ProcIO struct { 11 | // Chars read. 12 | RChar uint64 13 | // Chars written. 14 | WChar uint64 15 | // Read syscalls. 16 | SyscR uint64 17 | // Write syscalls. 18 | SyscW uint64 19 | // Bytes read. 20 | ReadBytes uint64 21 | // Bytes written. 22 | WriteBytes uint64 23 | // Bytes written, but taking into account truncation. See 24 | // Documentation/filesystems/proc.txt in the kernel sources for 25 | // detailed explanation. 26 | CancelledWriteBytes int64 27 | } 28 | 29 | // NewIO creates a new ProcIO instance from a given Proc instance. 30 | func (p Proc) NewIO() (ProcIO, error) { 31 | pio := ProcIO{} 32 | 33 | f, err := os.Open(p.path("io")) 34 | if err != nil { 35 | return pio, err 36 | } 37 | defer f.Close() 38 | 39 | data, err := ioutil.ReadAll(f) 40 | if err != nil { 41 | return pio, err 42 | } 43 | 44 | ioFormat := "rchar: %d\nwchar: %d\nsyscr: %d\nsyscw: %d\n" + 45 | "read_bytes: %d\nwrite_bytes: %d\n" + 46 | "cancelled_write_bytes: %d\n" 47 | 48 | _, err = fmt.Sscanf(string(data), ioFormat, &pio.RChar, &pio.WChar, &pio.SyscR, 49 | &pio.SyscW, &pio.ReadBytes, &pio.WriteBytes, &pio.CancelledWriteBytes) 50 | if err != nil { 51 | return pio, err 52 | } 53 | 54 | return pio, nil 55 | } 56 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/procfs/stat.go: -------------------------------------------------------------------------------- 1 | package procfs 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | // Stat represents kernel/system statistics. 12 | type Stat struct { 13 | // Boot time in seconds since the Epoch. 14 | BootTime int64 15 | } 16 | 17 | // NewStat returns kernel/system statistics read from /proc/stat. 18 | func NewStat() (Stat, error) { 19 | fs, err := NewFS(DefaultMountPoint) 20 | if err != nil { 21 | return Stat{}, err 22 | } 23 | 24 | return fs.NewStat() 25 | } 26 | 27 | // NewStat returns an information about current kernel/system statistics. 28 | func (fs FS) NewStat() (Stat, error) { 29 | f, err := os.Open(fs.Path("stat")) 30 | if err != nil { 31 | return Stat{}, err 32 | } 33 | defer f.Close() 34 | 35 | s := bufio.NewScanner(f) 36 | for s.Scan() { 37 | line := s.Text() 38 | if !strings.HasPrefix(line, "btime") { 39 | continue 40 | } 41 | fields := strings.Fields(line) 42 | if len(fields) != 2 { 43 | return Stat{}, fmt.Errorf("couldn't parse %s line %s", f.Name(), line) 44 | } 45 | i, err := strconv.ParseInt(fields[1], 10, 32) 46 | if err != nil { 47 | return Stat{}, fmt.Errorf("couldn't parse %s: %s", fields[1], err) 48 | } 49 | return Stat{BootTime: i}, nil 50 | } 51 | if err := s.Err(); err != nil { 52 | return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err) 53 | } 54 | 55 | return Stat{}, fmt.Errorf("couldn't parse %s, missing btime", f.Name()) 56 | } 57 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/local/chunk/delta_helpers.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 chunk 15 | 16 | import ( 17 | "math" 18 | 19 | "github.com/prometheus/common/model" 20 | ) 21 | 22 | type deltaBytes byte 23 | 24 | const ( 25 | d0 deltaBytes = 0 26 | d1 deltaBytes = 1 27 | d2 deltaBytes = 2 28 | d4 deltaBytes = 4 29 | d8 deltaBytes = 8 30 | ) 31 | 32 | func bytesNeededForUnsignedTimestampDelta(deltaT model.Time) deltaBytes { 33 | switch { 34 | case deltaT > math.MaxUint32: 35 | return d8 36 | case deltaT > math.MaxUint16: 37 | return d4 38 | case deltaT > math.MaxUint8: 39 | return d2 40 | default: 41 | return d1 42 | } 43 | } 44 | 45 | func bytesNeededForSignedTimestampDelta(deltaT model.Time) deltaBytes { 46 | switch { 47 | case deltaT > math.MaxInt32 || deltaT < math.MinInt32: 48 | return d8 49 | case deltaT > math.MaxInt16 || deltaT < math.MinInt16: 50 | return d4 51 | case deltaT > math.MaxInt8 || deltaT < math.MinInt8: 52 | return d2 53 | default: 54 | return d1 55 | } 56 | } 57 | 58 | func bytesNeededForIntegerSampleValueDelta(deltaV model.SampleValue) deltaBytes { 59 | switch { 60 | case deltaV < math.MinInt32 || deltaV > math.MaxInt32: 61 | return d8 62 | case deltaV < math.MinInt16 || deltaV > math.MaxInt16: 63 | return d4 64 | case deltaV < math.MinInt8 || deltaV > math.MaxInt8: 65 | return d2 66 | case deltaV != 0: 67 | return d1 68 | default: 69 | return d0 70 | } 71 | } 72 | 73 | func max(a, b deltaBytes) deltaBytes { 74 | if a > b { 75 | return a 76 | } 77 | return b 78 | } 79 | 80 | // isInt64 returns true if v can be represented as an int64. 81 | func isInt64(v model.SampleValue) bool { 82 | // Note: Using math.Modf is slower than the conversion approach below. 83 | return model.SampleValue(int64(v)) == v 84 | } 85 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/local/chunk/varbit_helpers.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 chunk 15 | 16 | import "github.com/prometheus/common/model" 17 | 18 | var ( 19 | // bit masks for consecutive bits in a byte at various offsets. 20 | bitMask = [][]byte{ 21 | {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0 bit 22 | {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}, // 1 bit 23 | {0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01}, // 2 bit 24 | {0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x01}, // 3 bit 25 | {0xF0, 0x78, 0x3C, 0x1E, 0x0F, 0x07, 0x03, 0x01}, // 4 bit 26 | {0xF8, 0x7C, 0x3E, 0x1F, 0x0F, 0x07, 0x03, 0x01}, // 5 bit 27 | {0xFC, 0x7E, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01}, // 6 bit 28 | {0xFE, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01}, // 7 bit 29 | {0xFF, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01}, // 8 bit 30 | } 31 | ) 32 | 33 | // isInt32 returns true if v can be represented as an int32. 34 | func isInt32(v model.SampleValue) bool { 35 | return model.SampleValue(int32(v)) == v 36 | } 37 | 38 | // countBits returs the number of leading zero bits and the number of 39 | // significant bits after that in the given bit pattern. The maximum number of 40 | // leading zeros is 31 (so that it can be represented by a 5bit number). Leading 41 | // zeros beyond that are considered part of the significant bits. 42 | func countBits(pattern uint64) (leading, significant byte) { 43 | // TODO(beorn7): This would probably be faster with ugly endless switch 44 | // statements. 45 | if pattern == 0 { 46 | return 47 | } 48 | for pattern < 1<<63 { 49 | leading++ 50 | pattern <<= 1 51 | } 52 | for pattern > 0 { 53 | significant++ 54 | pattern <<= 1 55 | } 56 | if leading > 31 { // 5 bit limit. 57 | significant += leading - 31 58 | leading = 31 59 | } 60 | return 61 | } 62 | 63 | // isSignedIntN returns if n can be represented as a signed int with the given 64 | // bit length. 65 | func isSignedIntN(i int64, n byte) bool { 66 | upper := int64(1) << (n - 1) 67 | if i >= upper { 68 | return false 69 | } 70 | lower := upper - (1 << n) 71 | if i < lower { 72 | return false 73 | } 74 | return true 75 | } 76 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/local/index/interface.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 index 15 | 16 | import "encoding" 17 | 18 | // KeyValueStore persists key/value pairs. Implementations must be fundamentally 19 | // goroutine-safe. However, it is the caller's responsibility that keys and 20 | // values can be safely marshaled and unmarshaled (via the MarshalBinary and 21 | // UnmarshalBinary methods of the keys and values). For example, if you call the 22 | // Put method of a KeyValueStore implementation, but the key or the value are 23 | // modified concurrently while being marshaled into its binary representation, 24 | // you obviously have a problem. Methods of KeyValueStore return only after 25 | // (un)marshaling is complete. 26 | type KeyValueStore interface { 27 | Put(key, value encoding.BinaryMarshaler) error 28 | // Get unmarshals the result into value. It returns false if no entry 29 | // could be found for key. If value is nil, Get behaves like Has. 30 | Get(key encoding.BinaryMarshaler, value encoding.BinaryUnmarshaler) (bool, error) 31 | Has(key encoding.BinaryMarshaler) (bool, error) 32 | // Delete returns (false, nil) if key does not exist. 33 | Delete(key encoding.BinaryMarshaler) (bool, error) 34 | 35 | NewBatch() Batch 36 | Commit(b Batch) error 37 | 38 | // ForEach iterates through the complete KeyValueStore and calls the 39 | // supplied function for each mapping. 40 | ForEach(func(kv KeyValueAccessor) error) error 41 | 42 | Close() error 43 | } 44 | 45 | // KeyValueAccessor allows access to the key and value of an entry in a 46 | // KeyValueStore. 47 | type KeyValueAccessor interface { 48 | Key(encoding.BinaryUnmarshaler) error 49 | Value(encoding.BinaryUnmarshaler) error 50 | } 51 | 52 | // Batch allows KeyValueStore mutations to be pooled and committed together. An 53 | // implementation does not have to be goroutine-safe. Never modify a Batch 54 | // concurrently or commit the same batch multiple times concurrently. Marshaling 55 | // of keys and values is guaranteed to be complete when the Put or Delete methods 56 | // have returned. 57 | type Batch interface { 58 | Put(key, value encoding.BinaryMarshaler) error 59 | Delete(key encoding.BinaryMarshaler) error 60 | Reset() 61 | } 62 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/local/instrumentation.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 local 15 | 16 | const ( 17 | namespace = "prometheus" 18 | subsystem = "local_storage" 19 | 20 | opTypeLabel = "type" 21 | 22 | // Op-types for seriesOps. 23 | create = "create" 24 | archive = "archive" 25 | unarchive = "unarchive" 26 | memoryPurge = "purge_from_memory" 27 | archivePurge = "purge_from_archive" 28 | requestedPurge = "purge_on_request" 29 | memoryMaintenance = "maintenance_in_memory" 30 | archiveMaintenance = "maintenance_in_archive" 31 | completedQurantine = "quarantine_completed" 32 | droppedQuarantine = "quarantine_dropped" 33 | failedQuarantine = "quarantine_failed" 34 | 35 | seriesLocationLabel = "location" 36 | 37 | // Maintenance types for maintainSeriesDuration. 38 | maintainInMemory = "memory" 39 | maintainArchived = "archived" 40 | 41 | discardReasonLabel = "reason" 42 | 43 | // Reasons to discard samples. 44 | outOfOrderTimestamp = "timestamp_out_of_order" 45 | duplicateSample = "multiple_values_for_timestamp" 46 | ) 47 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/local/locker.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 local 15 | 16 | import ( 17 | "sync" 18 | "unsafe" 19 | 20 | "github.com/prometheus/common/model" 21 | ) 22 | 23 | const ( 24 | cacheLineSize = 64 25 | ) 26 | 27 | // Avoid false sharing when using array of mutexes. 28 | type paddedMutex struct { 29 | sync.Mutex 30 | pad [cacheLineSize - unsafe.Sizeof(sync.Mutex{})]byte 31 | } 32 | 33 | // fingerprintLocker allows locking individual fingerprints. To limit the number 34 | // of mutexes needed for that, only a fixed number of mutexes are 35 | // allocated. Fingerprints to be locked are assigned to those pre-allocated 36 | // mutexes by their value. Collisions are not detected. If two fingerprints get 37 | // assigned to the same mutex, only one of them can be locked at the same 38 | // time. As long as the number of pre-allocated mutexes is much larger than the 39 | // number of goroutines requiring a fingerprint lock concurrently, the loss in 40 | // efficiency is small. However, a goroutine must never lock more than one 41 | // fingerprint at the same time. (In that case a collision would try to acquire 42 | // the same mutex twice). 43 | type fingerprintLocker struct { 44 | fpMtxs []paddedMutex 45 | numFpMtxs uint 46 | } 47 | 48 | // newFingerprintLocker returns a new fingerprintLocker ready for use. At least 49 | // 1024 preallocated mutexes are used, even if preallocatedMutexes is lower. 50 | func newFingerprintLocker(preallocatedMutexes int) *fingerprintLocker { 51 | if preallocatedMutexes < 1024 { 52 | preallocatedMutexes = 1024 53 | } 54 | return &fingerprintLocker{ 55 | make([]paddedMutex, preallocatedMutexes), 56 | uint(preallocatedMutexes), 57 | } 58 | } 59 | 60 | // Lock locks the given fingerprint. 61 | func (l *fingerprintLocker) Lock(fp model.Fingerprint) { 62 | l.fpMtxs[hashFP(fp)%l.numFpMtxs].Lock() 63 | } 64 | 65 | // Unlock unlocks the given fingerprint. 66 | func (l *fingerprintLocker) Unlock(fp model.Fingerprint) { 67 | l.fpMtxs[hashFP(fp)%l.numFpMtxs].Unlock() 68 | } 69 | 70 | // hashFP simply moves entropy from the most significant 48 bits of the 71 | // fingerprint into the least significant 16 bits (by XORing) so that a simple 72 | // MOD on the result can be used to pick a mutex while still making use of 73 | // changes in more significant bits of the fingerprint. (The fast fingerprinting 74 | // function we use is prone to only change a few bits for similar metrics. We 75 | // really want to make use of every change in the fingerprint to vary mutex 76 | // selection.) 77 | func hashFP(fp model.Fingerprint) uint { 78 | return uint(fp ^ (fp >> 32) ^ (fp >> 16)) 79 | } 80 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/local/storagetool/main.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 main 15 | 16 | import ( 17 | "fmt" 18 | "os" 19 | 20 | "github.com/prometheus/common/version" 21 | "github.com/prometheus/prometheus/storage/local" 22 | "github.com/prometheus/prometheus/util/cli" 23 | ) 24 | 25 | // DumpHeadsCmd dumps metadata of a heads.db file. 26 | func DumpHeadsCmd(t cli.Term, args ...string) int { 27 | if len(args) != 1 { 28 | t.Infof("usage: storagetool dump-heads ") 29 | return 2 30 | } 31 | if err := local.DumpHeads(args[0], t.Out()); err != nil { 32 | t.Errorf(" FAILED: %s", err) 33 | return 1 34 | } 35 | return 0 36 | } 37 | 38 | // VersionCmd prints the binaries version information. 39 | func VersionCmd(t cli.Term, _ ...string) int { 40 | fmt.Fprintln(os.Stdout, version.Print("storagetool")) 41 | return 0 42 | } 43 | 44 | func main() { 45 | app := cli.NewApp("storagetool") 46 | 47 | app.Register("dump-heads", &cli.Command{ 48 | Desc: "dump metadata of a heads.db checkpoint file", 49 | Run: DumpHeadsCmd, 50 | }) 51 | 52 | app.Register("version", &cli.Command{ 53 | Desc: "print the version of this binary", 54 | Run: VersionCmd, 55 | }) 56 | 57 | t := cli.BasicTerm(os.Stdout, os.Stderr) 58 | os.Exit(app.Run(t, os.Args[1:]...)) 59 | } 60 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/local/test_helpers.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 | // NOTE ON FILENAME: Do not rename this file helpers_test.go (which might appear 15 | // an obvious choice). We need NewTestStorage in tests outside of the local 16 | // package, too. On the other hand, moving NewTestStorage in its own package 17 | // would cause circular dependencies in the tests in packages local. 18 | 19 | package local 20 | 21 | import ( 22 | "time" 23 | 24 | "github.com/prometheus/common/model" 25 | "github.com/prometheus/prometheus/storage/local/chunk" 26 | "github.com/prometheus/prometheus/util/testutil" 27 | ) 28 | 29 | type testStorageCloser struct { 30 | storage Storage 31 | directory testutil.Closer 32 | } 33 | 34 | func (t *testStorageCloser) Close() { 35 | if err := t.storage.Stop(); err != nil { 36 | panic(err) 37 | } 38 | t.directory.Close() 39 | } 40 | 41 | // NewTestStorage creates a storage instance backed by files in a temporary 42 | // directory. The returned storage is already in serving state. Upon closing the 43 | // returned test.Closer, the temporary directory is cleaned up. 44 | func NewTestStorage(t testutil.T, encoding chunk.Encoding) (*MemorySeriesStorage, testutil.Closer) { 45 | chunk.DefaultEncoding = encoding 46 | directory := testutil.NewTemporaryDirectory("test_storage", t) 47 | o := &MemorySeriesStorageOptions{ 48 | TargetHeapSize: 1000000000, 49 | PersistenceRetentionPeriod: 24 * time.Hour * 365 * 100, // Enough to never trigger purging. 50 | PersistenceStoragePath: directory.Path(), 51 | HeadChunkTimeout: 5 * time.Minute, 52 | CheckpointInterval: time.Hour, 53 | SyncStrategy: Adaptive, 54 | } 55 | storage := NewMemorySeriesStorage(o) 56 | storage.archiveHighWatermark = model.Latest 57 | if err := storage.Start(); err != nil { 58 | directory.Close() 59 | t.Fatalf("Error creating storage: %s", err) 60 | } 61 | 62 | closer := &testStorageCloser{ 63 | storage: storage, 64 | directory: directory, 65 | } 66 | 67 | return storage, closer 68 | } 69 | 70 | func makeFingerprintSeriesPair(s *MemorySeriesStorage, fp model.Fingerprint) fingerprintSeriesPair { 71 | return fingerprintSeriesPair{fp, s.seriesForRange(fp, model.Earliest, model.Latest)} 72 | } 73 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/metric/metric.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 metric 15 | 16 | import "github.com/prometheus/common/model" 17 | 18 | // Metric wraps a model.Metric and copies it upon modification if Copied is false. 19 | type Metric struct { 20 | Copied bool 21 | Metric model.Metric 22 | } 23 | 24 | // Set sets a label name in the wrapped Metric to a given value and copies the 25 | // Metric initially, if it is not already a copy. 26 | func (m *Metric) Set(ln model.LabelName, lv model.LabelValue) { 27 | m.Copy() 28 | m.Metric[ln] = lv 29 | } 30 | 31 | // Del deletes a given label name from the wrapped Metric and copies the 32 | // Metric initially, if it is not already a copy. 33 | func (m *Metric) Del(ln model.LabelName) { 34 | m.Copy() 35 | delete(m.Metric, ln) 36 | } 37 | 38 | // Get the value for the given label name. An empty value is returned 39 | // if the label does not exist in the metric. 40 | func (m *Metric) Get(ln model.LabelName) model.LabelValue { 41 | return m.Metric[ln] 42 | } 43 | 44 | // Gets behaves as Get but the returned boolean is false iff the label 45 | // does not exist. 46 | func (m *Metric) Gets(ln model.LabelName) (model.LabelValue, bool) { 47 | lv, ok := m.Metric[ln] 48 | return lv, ok 49 | } 50 | 51 | // Copy the underlying Metric if it is not already a copy. 52 | func (m *Metric) Copy() *Metric { 53 | if !m.Copied { 54 | m.Metric = m.Metric.Clone() 55 | m.Copied = true 56 | } 57 | return m 58 | } 59 | 60 | // String implements fmt.Stringer. 61 | func (m Metric) String() string { 62 | return m.Metric.String() 63 | } 64 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/metric/sample.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 metric 15 | 16 | import "github.com/prometheus/common/model" 17 | 18 | // Interval describes the inclusive interval between two Timestamps. 19 | type Interval struct { 20 | OldestInclusive model.Time 21 | NewestInclusive model.Time 22 | } 23 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/remote/ewma.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 remote 15 | 16 | import ( 17 | "sync" 18 | "sync/atomic" 19 | "time" 20 | ) 21 | 22 | // ewmaRate tracks an exponentially weighted moving average of a per-second rate. 23 | type ewmaRate struct { 24 | newEvents int64 25 | alpha float64 26 | interval time.Duration 27 | lastRate float64 28 | init bool 29 | mutex sync.Mutex 30 | } 31 | 32 | // newEWMARate always allocates a new ewmaRate, as this guarantees the atomically 33 | // accessed int64 will be aligned on ARM. See prometheus#2666. 34 | func newEWMARate(alpha float64, interval time.Duration) *ewmaRate { 35 | return &ewmaRate{ 36 | alpha: alpha, 37 | interval: interval, 38 | } 39 | } 40 | 41 | // rate returns the per-second rate. 42 | func (r *ewmaRate) rate() float64 { 43 | r.mutex.Lock() 44 | defer r.mutex.Unlock() 45 | return r.lastRate 46 | } 47 | 48 | // tick assumes to be called every r.interval. 49 | func (r *ewmaRate) tick() { 50 | newEvents := atomic.LoadInt64(&r.newEvents) 51 | atomic.AddInt64(&r.newEvents, -newEvents) 52 | instantRate := float64(newEvents) / r.interval.Seconds() 53 | 54 | r.mutex.Lock() 55 | defer r.mutex.Unlock() 56 | 57 | if r.init { 58 | r.lastRate += r.alpha * (instantRate - r.lastRate) 59 | } else { 60 | r.init = true 61 | r.lastRate = instantRate 62 | } 63 | } 64 | 65 | // inc counts one event. 66 | func (r *ewmaRate) incr(incr int64) { 67 | atomic.AddInt64(&r.newEvents, incr) 68 | } 69 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/remote/iterator.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 remote 15 | 16 | import ( 17 | "sort" 18 | 19 | "github.com/prometheus/common/model" 20 | "github.com/prometheus/prometheus/storage/metric" 21 | ) 22 | 23 | // This is a struct and not just a renamed type because otherwise the Metric 24 | // field and Metric() methods would clash. 25 | type sampleStreamIterator struct { 26 | ss *model.SampleStream 27 | } 28 | 29 | func (it sampleStreamIterator) Metric() metric.Metric { 30 | return metric.Metric{Metric: it.ss.Metric} 31 | } 32 | 33 | func (it sampleStreamIterator) ValueAtOrBeforeTime(ts model.Time) model.SamplePair { 34 | // TODO: This is a naive inefficient approach - in reality, queries go mostly 35 | // linearly through iterators, and we will want to make successive calls to 36 | // this method more efficient by taking into account the last result index 37 | // somehow (similarly to how it's done in Prometheus's 38 | // memorySeriesIterators). 39 | i := sort.Search(len(it.ss.Values), func(n int) bool { 40 | return it.ss.Values[n].Timestamp.After(ts) 41 | }) 42 | if i == 0 { 43 | return model.SamplePair{Timestamp: model.Earliest} 44 | } 45 | return it.ss.Values[i-1] 46 | } 47 | 48 | func (it sampleStreamIterator) RangeValues(in metric.Interval) []model.SamplePair { 49 | n := len(it.ss.Values) 50 | start := sort.Search(n, func(i int) bool { 51 | return !it.ss.Values[i].Timestamp.Before(in.OldestInclusive) 52 | }) 53 | end := sort.Search(n, func(i int) bool { 54 | return it.ss.Values[i].Timestamp.After(in.NewestInclusive) 55 | }) 56 | 57 | if start == n { 58 | return nil 59 | } 60 | 61 | return it.ss.Values[start:end] 62 | } 63 | 64 | func (it sampleStreamIterator) Close() {} 65 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/remote/write.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 remote 15 | 16 | import ( 17 | "sync" 18 | 19 | "github.com/prometheus/common/model" 20 | 21 | "github.com/prometheus/prometheus/config" 22 | ) 23 | 24 | // Writer allows queueing samples for remote writes. 25 | type Writer struct { 26 | mtx sync.RWMutex 27 | queues []*QueueManager 28 | } 29 | 30 | // ApplyConfig updates the state as the new config requires. 31 | func (w *Writer) ApplyConfig(conf *config.Config) error { 32 | w.mtx.Lock() 33 | defer w.mtx.Unlock() 34 | 35 | newQueues := []*QueueManager{} 36 | // TODO: we should only stop & recreate queues which have changes, 37 | // as this can be quite disruptive. 38 | for i, rwConf := range conf.RemoteWriteConfigs { 39 | c, err := NewClient(i, &ClientConfig{ 40 | URL: rwConf.URL, 41 | Timeout: rwConf.RemoteTimeout, 42 | HTTPClientConfig: rwConf.HTTPClientConfig, 43 | }) 44 | if err != nil { 45 | return err 46 | } 47 | newQueues = append(newQueues, NewQueueManager( 48 | rwConf.QueueConfig, 49 | conf.GlobalConfig.ExternalLabels, 50 | rwConf.WriteRelabelConfigs, 51 | c, 52 | )) 53 | } 54 | 55 | for _, q := range w.queues { 56 | q.Stop() 57 | } 58 | 59 | w.queues = newQueues 60 | for _, q := range w.queues { 61 | q.Start() 62 | } 63 | return nil 64 | } 65 | 66 | // Stop the background processing of the storage queues. 67 | func (w *Writer) Stop() { 68 | for _, q := range w.queues { 69 | q.Stop() 70 | } 71 | } 72 | 73 | // Append implements storage.SampleAppender. Always returns nil. 74 | func (w *Writer) Append(smpl *model.Sample) error { 75 | w.mtx.RLock() 76 | defer w.mtx.RUnlock() 77 | 78 | for _, q := range w.queues { 79 | q.Append(smpl) 80 | } 81 | return nil 82 | } 83 | 84 | // NeedsThrottling implements storage.SampleAppender. It will always return 85 | // false as a remote storage drops samples on the floor if backlogging instead 86 | // of asking for throttling. 87 | func (w *Writer) NeedsThrottling() bool { 88 | return false 89 | } 90 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/storage/storage.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 storage 15 | 16 | import ( 17 | "github.com/prometheus/common/model" 18 | ) 19 | 20 | // SampleAppender is the interface to append samples to both, local and remote 21 | // storage. All methods are goroutine-safe. 22 | type SampleAppender interface { 23 | // Append appends a sample to the underlying storage. Depending on the 24 | // storage implementation, there are different guarantees for the fate 25 | // of the sample after Append has returned. Remote storage 26 | // implementation will simply drop samples if they cannot keep up with 27 | // sending samples. Local storage implementations will only drop metrics 28 | // upon unrecoverable errors. 29 | Append(*model.Sample) error 30 | // NeedsThrottling returns true if the underlying storage wishes to not 31 | // receive any more samples. Append will still work but might lead to 32 | // undue resource usage. It is recommended to call NeedsThrottling once 33 | // before an upcoming batch of Append calls (e.g. a full scrape of a 34 | // target or the evaluation of a rule group) and only proceed with the 35 | // batch if NeedsThrottling returns false. In that way, the result of a 36 | // scrape or of an evaluation of a rule group will always be appended 37 | // completely or not at all, and the work of scraping or evaluation will 38 | // not be performed in vain. Also, a call of NeedsThrottling is 39 | // potentially expensive, so limiting the number of calls is reasonable. 40 | // 41 | // Only SampleAppenders for which it is considered critical to receive 42 | // each and every sample should ever return true. SampleAppenders that 43 | // tolerate not receiving all samples should always return false and 44 | // instead drop samples as they see fit to avoid overload. 45 | NeedsThrottling() bool 46 | } 47 | 48 | // Fanout is a SampleAppender that appends every sample to each SampleAppender 49 | // in its list. 50 | type Fanout []SampleAppender 51 | 52 | // Append implements SampleAppender. It appends the provided sample to all 53 | // SampleAppenders in the Fanout slice and waits for each append to complete 54 | // before proceeding with the next. 55 | // If any of the SampleAppenders returns an error, the first one is returned 56 | // at the end. 57 | func (f Fanout) Append(s *model.Sample) error { 58 | var err error 59 | for _, a := range f { 60 | if e := a.Append(s); e != nil && err == nil { 61 | err = e 62 | } 63 | } 64 | return err 65 | } 66 | 67 | // NeedsThrottling returns true if at least one of the SampleAppenders in the 68 | // Fanout slice is throttled. 69 | func (f Fanout) NeedsThrottling() bool { 70 | for _, a := range f { 71 | if a.NeedsThrottling() { 72 | return true 73 | } 74 | } 75 | return false 76 | } 77 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/util/flock/flock.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 flock provides portable file locking. It is essentially ripped out 15 | // from the code of github.com/syndtr/goleveldb. Strange enough that the 16 | // standard library does not provide this functionality. Once this package has 17 | // proven to work as expected, we should probably turn it into a separate 18 | // general purpose package for humanity. 19 | package flock 20 | 21 | import ( 22 | "os" 23 | "path/filepath" 24 | ) 25 | 26 | // Releaser provides the Release method to release a file lock. 27 | type Releaser interface { 28 | Release() error 29 | } 30 | 31 | // New locks the file with the provided name. If the file does not exist, it is 32 | // created. The returned Releaser is used to release the lock. existed is true 33 | // if the file to lock already existed. A non-nil error is returned if the 34 | // locking has failed. Neither this function nor the returned Releaser is 35 | // goroutine-safe. 36 | func New(fileName string) (r Releaser, existed bool, err error) { 37 | if err = os.MkdirAll(filepath.Dir(fileName), 0755); err != nil { 38 | return 39 | } 40 | 41 | _, err = os.Stat(fileName) 42 | existed = err == nil 43 | 44 | r, err = newLock(fileName) 45 | return 46 | } 47 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/util/flock/flock_plan9.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 flock 15 | 16 | import "os" 17 | 18 | type plan9Lock struct { 19 | f *os.File 20 | } 21 | 22 | func (l *plan9Lock) Release() error { 23 | return l.f.Close() 24 | } 25 | 26 | func newLock(fileName string) (Releaser, error) { 27 | f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModeExclusive|0644) 28 | if err != nil { 29 | return nil, err 30 | } 31 | return &plan9Lock{f}, nil 32 | } 33 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/util/flock/flock_solaris.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 | // +build solaris 15 | 16 | package flock 17 | 18 | import ( 19 | "os" 20 | "syscall" 21 | ) 22 | 23 | type unixLock struct { 24 | f *os.File 25 | } 26 | 27 | func (l *unixLock) Release() error { 28 | if err := l.set(false); err != nil { 29 | return err 30 | } 31 | return l.f.Close() 32 | } 33 | 34 | func (l *unixLock) set(lock bool) error { 35 | flock := syscall.Flock_t{ 36 | Type: syscall.F_UNLCK, 37 | Start: 0, 38 | Len: 0, 39 | Whence: 1, 40 | } 41 | if lock { 42 | flock.Type = syscall.F_WRLCK 43 | } 44 | return syscall.FcntlFlock(l.f.Fd(), syscall.F_SETLK, &flock) 45 | } 46 | 47 | func newLock(fileName string) (Releaser, error) { 48 | f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) 49 | if err != nil { 50 | return nil, err 51 | } 52 | l := &unixLock{f} 53 | err = l.set(true) 54 | if err != nil { 55 | f.Close() 56 | return nil, err 57 | } 58 | return l, nil 59 | } 60 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/util/flock/flock_unix.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 | // +build darwin dragonfly freebsd linux netbsd openbsd 15 | 16 | package flock 17 | 18 | import ( 19 | "os" 20 | "syscall" 21 | ) 22 | 23 | type unixLock struct { 24 | f *os.File 25 | } 26 | 27 | func (l *unixLock) Release() error { 28 | if err := l.set(false); err != nil { 29 | return err 30 | } 31 | return l.f.Close() 32 | } 33 | 34 | func (l *unixLock) set(lock bool) error { 35 | how := syscall.LOCK_UN 36 | if lock { 37 | how = syscall.LOCK_EX 38 | } 39 | return syscall.Flock(int(l.f.Fd()), how|syscall.LOCK_NB) 40 | } 41 | 42 | func newLock(fileName string) (Releaser, error) { 43 | f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) 44 | if err != nil { 45 | return nil, err 46 | } 47 | l := &unixLock{f} 48 | err = l.set(true) 49 | if err != nil { 50 | f.Close() 51 | return nil, err 52 | } 53 | return l, nil 54 | } 55 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/util/flock/flock_windows.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 flock 15 | 16 | import "syscall" 17 | 18 | type windowsLock struct { 19 | fd syscall.Handle 20 | } 21 | 22 | func (fl *windowsLock) Release() error { 23 | return syscall.Close(fl.fd) 24 | } 25 | 26 | func newLock(fileName string) (Releaser, error) { 27 | pathp, err := syscall.UTF16PtrFromString(fileName) 28 | if err != nil { 29 | return nil, err 30 | } 31 | fd, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.CREATE_ALWAYS, syscall.FILE_ATTRIBUTE_NORMAL, 0) 32 | if err != nil { 33 | return nil, err 34 | } 35 | return &windowsLock{fd}, nil 36 | } 37 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/util/httputil/compression.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 httputil 15 | 16 | import ( 17 | "compress/gzip" 18 | "compress/zlib" 19 | "io" 20 | "net/http" 21 | "strings" 22 | ) 23 | 24 | const ( 25 | acceptEncodingHeader = "Accept-Encoding" 26 | contentEncodingHeader = "Content-Encoding" 27 | gzipEncoding = "gzip" 28 | deflateEncoding = "deflate" 29 | ) 30 | 31 | // Wrapper around http.Handler which adds suitable response compression based 32 | // on the client's Accept-Encoding headers. 33 | type compressedResponseWriter struct { 34 | http.ResponseWriter 35 | writer io.Writer 36 | } 37 | 38 | // Writes HTTP response content data. 39 | func (c *compressedResponseWriter) Write(p []byte) (int, error) { 40 | return c.writer.Write(p) 41 | } 42 | 43 | // Closes the compressedResponseWriter and ensures to flush all data before. 44 | func (c *compressedResponseWriter) Close() { 45 | if zlibWriter, ok := c.writer.(*zlib.Writer); ok { 46 | zlibWriter.Flush() 47 | } 48 | if gzipWriter, ok := c.writer.(*gzip.Writer); ok { 49 | gzipWriter.Flush() 50 | } 51 | if closer, ok := c.writer.(io.Closer); ok { 52 | defer closer.Close() 53 | } 54 | } 55 | 56 | // Constructs a new compressedResponseWriter based on client request headers. 57 | func newCompressedResponseWriter(writer http.ResponseWriter, req *http.Request) *compressedResponseWriter { 58 | encodings := strings.Split(req.Header.Get(acceptEncodingHeader), ",") 59 | for _, encoding := range encodings { 60 | switch strings.TrimSpace(encoding) { 61 | case gzipEncoding: 62 | writer.Header().Set(contentEncodingHeader, gzipEncoding) 63 | return &compressedResponseWriter{ 64 | ResponseWriter: writer, 65 | writer: gzip.NewWriter(writer), 66 | } 67 | case deflateEncoding: 68 | writer.Header().Set(contentEncodingHeader, deflateEncoding) 69 | return &compressedResponseWriter{ 70 | ResponseWriter: writer, 71 | writer: zlib.NewWriter(writer), 72 | } 73 | } 74 | } 75 | return &compressedResponseWriter{ 76 | ResponseWriter: writer, 77 | writer: writer, 78 | } 79 | } 80 | 81 | // CompressionHandler is a wrapper around http.Handler which adds suitable 82 | // response compression based on the client's Accept-Encoding headers. 83 | type CompressionHandler struct { 84 | Handler http.Handler 85 | } 86 | 87 | // ServeHTTP adds compression to the original http.Handler's ServeHTTP() method. 88 | func (c CompressionHandler) ServeHTTP(writer http.ResponseWriter, req *http.Request) { 89 | compWriter := newCompressedResponseWriter(writer, req) 90 | c.Handler.ServeHTTP(compWriter, req) 91 | compWriter.Close() 92 | } 93 | -------------------------------------------------------------------------------- /vendor/github.com/prometheus/prometheus/util/testutil/error.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 testutil 15 | 16 | // ErrorEqual compares Go errors for equality. 17 | func ErrorEqual(left, right error) bool { 18 | if left == right { 19 | return true 20 | } 21 | 22 | if left != nil && right != nil { 23 | if left.Error() == right.Error() { 24 | return true 25 | } 26 | 27 | return false 28 | } 29 | 30 | return false 31 | } 32 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/context/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/net/context/ctxhttp/ctxhttp.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 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 go1.7 6 | 7 | // Package ctxhttp provides helper functions for performing context-aware HTTP requests. 8 | package ctxhttp // import "golang.org/x/net/context/ctxhttp" 9 | 10 | import ( 11 | "io" 12 | "net/http" 13 | "net/url" 14 | "strings" 15 | 16 | "golang.org/x/net/context" 17 | ) 18 | 19 | // Do sends an HTTP request with the provided http.Client and returns 20 | // an HTTP response. 21 | // 22 | // If the client is nil, http.DefaultClient is used. 23 | // 24 | // The provided ctx must be non-nil. If it is canceled or times out, 25 | // ctx.Err() will be returned. 26 | func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { 27 | if client == nil { 28 | client = http.DefaultClient 29 | } 30 | resp, err := client.Do(req.WithContext(ctx)) 31 | // If we got an error, and the context has been canceled, 32 | // the context's error is probably more useful. 33 | if err != nil { 34 | select { 35 | case <-ctx.Done(): 36 | err = ctx.Err() 37 | default: 38 | } 39 | } 40 | return resp, err 41 | } 42 | 43 | // Get issues a GET request via the Do function. 44 | func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { 45 | req, err := http.NewRequest("GET", url, nil) 46 | if err != nil { 47 | return nil, err 48 | } 49 | return Do(ctx, client, req) 50 | } 51 | 52 | // Head issues a HEAD request via the Do function. 53 | func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { 54 | req, err := http.NewRequest("HEAD", url, nil) 55 | if err != nil { 56 | return nil, err 57 | } 58 | return Do(ctx, client, req) 59 | } 60 | 61 | // Post issues a POST request via the Do function. 62 | func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { 63 | req, err := http.NewRequest("POST", url, body) 64 | if err != nil { 65 | return nil, err 66 | } 67 | req.Header.Set("Content-Type", bodyType) 68 | return Do(ctx, client, req) 69 | } 70 | 71 | // PostForm issues a POST request via the Do function. 72 | func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { 73 | return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 74 | } 75 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/context/go17.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 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 go1.7 6 | 7 | package context 8 | 9 | import ( 10 | "context" // standard library's context, as of Go 1.7 11 | "time" 12 | ) 13 | 14 | var ( 15 | todo = context.TODO() 16 | background = context.Background() 17 | ) 18 | 19 | // Canceled is the error returned by Context.Err when the context is canceled. 20 | var Canceled = context.Canceled 21 | 22 | // DeadlineExceeded is the error returned by Context.Err when the context's 23 | // deadline passes. 24 | var DeadlineExceeded = context.DeadlineExceeded 25 | 26 | // WithCancel returns a copy of parent with a new Done channel. The returned 27 | // context's Done channel is closed when the returned cancel function is called 28 | // or when the parent context's Done channel is closed, whichever happens first. 29 | // 30 | // Canceling this context releases resources associated with it, so code should 31 | // call cancel as soon as the operations running in this Context complete. 32 | func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { 33 | ctx, f := context.WithCancel(parent) 34 | return ctx, CancelFunc(f) 35 | } 36 | 37 | // WithDeadline returns a copy of the parent context with the deadline adjusted 38 | // to be no later than d. If the parent's deadline is already earlier than d, 39 | // WithDeadline(parent, d) is semantically equivalent to parent. The returned 40 | // context's Done channel is closed when the deadline expires, when the returned 41 | // cancel function is called, or when the parent context's Done channel is 42 | // closed, whichever happens first. 43 | // 44 | // Canceling this context releases resources associated with it, so code should 45 | // call cancel as soon as the operations running in this Context complete. 46 | func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { 47 | ctx, f := context.WithDeadline(parent, deadline) 48 | return ctx, CancelFunc(f) 49 | } 50 | 51 | // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). 52 | // 53 | // Canceling this context releases resources associated with it, so code should 54 | // call cancel as soon as the operations running in this Context complete: 55 | // 56 | // func slowOperationWithTimeout(ctx context.Context) (Result, error) { 57 | // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) 58 | // defer cancel() // releases resources if slowOperation completes before timeout elapses 59 | // return slowOperation(ctx) 60 | // } 61 | func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { 62 | return WithDeadline(parent, time.Now().Add(timeout)) 63 | } 64 | 65 | // WithValue returns a copy of parent in which the value associated with key is 66 | // val. 67 | // 68 | // Use context Values only for request-scoped data that transits processes and 69 | // APIs, not for passing optional parameters to functions. 70 | func WithValue(parent Context, key interface{}, val interface{}) Context { 71 | return context.WithValue(parent, key, val) 72 | } 73 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/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/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-8 10 | JMP syscall·getprocaddress(SB) 11 | 12 | TEXT ·loadlibrary(SB), 7, $0-4 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-8 13 | JMP syscall·loadlibrary(SB) 14 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/env_unset.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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.4 7 | 8 | package windows 9 | 10 | import "syscall" 11 | 12 | func Unsetenv(key string) error { 13 | // This was added in Go 1.4. 14 | return syscall.Unsetenv(key) 15 | } 16 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/env_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Windows environment variables. 6 | 7 | package windows 8 | 9 | import "syscall" 10 | 11 | func Getenv(key string) (value string, found bool) { 12 | return syscall.Getenv(key) 13 | } 14 | 15 | func Setenv(key, value string) error { 16 | return syscall.Setenv(key, value) 17 | } 18 | 19 | func Clearenv() { 20 | syscall.Clearenv() 21 | } 22 | 23 | func Environ() []string { 24 | return syscall.Environ() 25 | } 26 | -------------------------------------------------------------------------------- /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/mksyscall.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package windows 6 | 7 | //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go 8 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/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/registry/mksyscall.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 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 registry 6 | 7 | //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go 8 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/registry/syscall.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 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 registry 8 | 9 | import "syscall" 10 | 11 | const ( 12 | _REG_OPTION_NON_VOLATILE = 0 13 | 14 | _REG_CREATED_NEW_KEY = 1 15 | _REG_OPENED_EXISTING_KEY = 2 16 | 17 | _ERROR_NO_MORE_ITEMS syscall.Errno = 259 18 | ) 19 | 20 | func LoadRegLoadMUIString() error { 21 | return procRegLoadMUIStringW.Find() 22 | } 23 | 24 | //sys regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) = advapi32.RegCreateKeyExW 25 | //sys regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) = advapi32.RegDeleteKeyW 26 | //sys regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) = advapi32.RegSetValueExW 27 | //sys regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegEnumValueW 28 | //sys regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) = advapi32.RegDeleteValueW 29 | //sys regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) = advapi32.RegLoadMUIStringW 30 | 31 | //sys expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW 32 | -------------------------------------------------------------------------------- /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/svc/debug/log.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 debug 8 | 9 | import ( 10 | "os" 11 | "strconv" 12 | ) 13 | 14 | // Log interface allows different log implementations to be used. 15 | type Log interface { 16 | Close() error 17 | Info(eid uint32, msg string) error 18 | Warning(eid uint32, msg string) error 19 | Error(eid uint32, msg string) error 20 | } 21 | 22 | // ConsoleLog provides access to the console. 23 | type ConsoleLog struct { 24 | Name string 25 | } 26 | 27 | // New creates new ConsoleLog. 28 | func New(source string) *ConsoleLog { 29 | return &ConsoleLog{Name: source} 30 | } 31 | 32 | // Close closes console log l. 33 | func (l *ConsoleLog) Close() error { 34 | return nil 35 | } 36 | 37 | func (l *ConsoleLog) report(kind string, eid uint32, msg string) error { 38 | s := l.Name + "." + kind + "(" + strconv.Itoa(int(eid)) + "): " + msg + "\n" 39 | _, err := os.Stdout.Write([]byte(s)) 40 | return err 41 | } 42 | 43 | // Info writes an information event msg with event id eid to the console l. 44 | func (l *ConsoleLog) Info(eid uint32, msg string) error { 45 | return l.report("info", eid, msg) 46 | } 47 | 48 | // Warning writes an warning event msg with event id eid to the console l. 49 | func (l *ConsoleLog) Warning(eid uint32, msg string) error { 50 | return l.report("warn", eid, msg) 51 | } 52 | 53 | // Error writes an error event msg with event id eid to the console l. 54 | func (l *ConsoleLog) Error(eid uint32, msg string) error { 55 | return l.report("error", eid, msg) 56 | } 57 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/debug/service.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 debug provides facilities to execute svc.Handler on console. 8 | // 9 | package debug 10 | 11 | import ( 12 | "os" 13 | "os/signal" 14 | "syscall" 15 | 16 | "golang.org/x/sys/windows/svc" 17 | ) 18 | 19 | // Run executes service name by calling appropriate handler function. 20 | // The process is running on console, unlike real service. Use Ctrl+C to 21 | // send "Stop" command to your service. 22 | func Run(name string, handler svc.Handler) error { 23 | cmds := make(chan svc.ChangeRequest) 24 | changes := make(chan svc.Status) 25 | 26 | sig := make(chan os.Signal) 27 | signal.Notify(sig) 28 | 29 | go func() { 30 | status := svc.Status{State: svc.Stopped} 31 | for { 32 | select { 33 | case <-sig: 34 | cmds <- svc.ChangeRequest{svc.Stop, status} 35 | case status = <-changes: 36 | } 37 | } 38 | }() 39 | 40 | _, errno := handler.Execute([]string{name}, cmds, changes) 41 | if errno != 0 { 42 | return syscall.Errno(errno) 43 | } 44 | return nil 45 | } 46 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/event.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 svc 8 | 9 | import ( 10 | "errors" 11 | 12 | "golang.org/x/sys/windows" 13 | ) 14 | 15 | // event represents auto-reset, initially non-signaled Windows event. 16 | // It is used to communicate between go and asm parts of this package. 17 | type event struct { 18 | h windows.Handle 19 | } 20 | 21 | func newEvent() (*event, error) { 22 | h, err := windows.CreateEvent(nil, 0, 0, nil) 23 | if err != nil { 24 | return nil, err 25 | } 26 | return &event{h: h}, nil 27 | } 28 | 29 | func (e *event) Close() error { 30 | return windows.CloseHandle(e.h) 31 | } 32 | 33 | func (e *event) Set() error { 34 | return windows.SetEvent(e.h) 35 | } 36 | 37 | func (e *event) Wait() error { 38 | s, err := windows.WaitForSingleObject(e.h, windows.INFINITE) 39 | switch s { 40 | case windows.WAIT_OBJECT_0: 41 | break 42 | case windows.WAIT_FAILED: 43 | return err 44 | default: 45 | return errors.New("unexpected result from WaitForSingleObject") 46 | } 47 | return nil 48 | } 49 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/eventlog/install.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 eventlog 8 | 9 | import ( 10 | "errors" 11 | 12 | "golang.org/x/sys/windows" 13 | "golang.org/x/sys/windows/registry" 14 | ) 15 | 16 | const ( 17 | // Log levels. 18 | Info = windows.EVENTLOG_INFORMATION_TYPE 19 | Warning = windows.EVENTLOG_WARNING_TYPE 20 | Error = windows.EVENTLOG_ERROR_TYPE 21 | ) 22 | 23 | const addKeyName = `SYSTEM\CurrentControlSet\Services\EventLog\Application` 24 | 25 | // Install modifies PC registry to allow logging with an event source src. 26 | // It adds all required keys and values to the event log registry key. 27 | // Install uses msgFile as the event message file. If useExpandKey is true, 28 | // the event message file is installed as REG_EXPAND_SZ value, 29 | // otherwise as REG_SZ. Use bitwise of log.Error, log.Warning and 30 | // log.Info to specify events supported by the new event source. 31 | func Install(src, msgFile string, useExpandKey bool, eventsSupported uint32) error { 32 | appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.CREATE_SUB_KEY) 33 | if err != nil { 34 | return err 35 | } 36 | defer appkey.Close() 37 | 38 | sk, alreadyExist, err := registry.CreateKey(appkey, src, registry.SET_VALUE) 39 | if err != nil { 40 | return err 41 | } 42 | defer sk.Close() 43 | if alreadyExist { 44 | return errors.New(addKeyName + `\` + src + " registry key already exists") 45 | } 46 | 47 | err = sk.SetDWordValue("CustomSource", 1) 48 | if err != nil { 49 | return err 50 | } 51 | if useExpandKey { 52 | err = sk.SetExpandStringValue("EventMessageFile", msgFile) 53 | } else { 54 | err = sk.SetStringValue("EventMessageFile", msgFile) 55 | } 56 | if err != nil { 57 | return err 58 | } 59 | err = sk.SetDWordValue("TypesSupported", eventsSupported) 60 | if err != nil { 61 | return err 62 | } 63 | return nil 64 | } 65 | 66 | // InstallAsEventCreate is the same as Install, but uses 67 | // %SystemRoot%\System32\EventCreate.exe as the event message file. 68 | func InstallAsEventCreate(src string, eventsSupported uint32) error { 69 | return Install(src, "%SystemRoot%\\System32\\EventCreate.exe", true, eventsSupported) 70 | } 71 | 72 | // Remove deletes all registry elements installed by the correspondent Install. 73 | func Remove(src string) error { 74 | appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.SET_VALUE) 75 | if err != nil { 76 | return err 77 | } 78 | defer appkey.Close() 79 | return registry.DeleteKey(appkey, src) 80 | } 81 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/eventlog/log.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 eventlog implements access to Windows event log. 8 | // 9 | package eventlog 10 | 11 | import ( 12 | "errors" 13 | "syscall" 14 | 15 | "golang.org/x/sys/windows" 16 | ) 17 | 18 | // Log provides access to the system log. 19 | type Log struct { 20 | Handle windows.Handle 21 | } 22 | 23 | // Open retrieves a handle to the specified event log. 24 | func Open(source string) (*Log, error) { 25 | return OpenRemote("", source) 26 | } 27 | 28 | // OpenRemote does the same as Open, but on different computer host. 29 | func OpenRemote(host, source string) (*Log, error) { 30 | if source == "" { 31 | return nil, errors.New("Specify event log source") 32 | } 33 | var s *uint16 34 | if host != "" { 35 | s = syscall.StringToUTF16Ptr(host) 36 | } 37 | h, err := windows.RegisterEventSource(s, syscall.StringToUTF16Ptr(source)) 38 | if err != nil { 39 | return nil, err 40 | } 41 | return &Log{Handle: h}, nil 42 | } 43 | 44 | // Close closes event log l. 45 | func (l *Log) Close() error { 46 | return windows.DeregisterEventSource(l.Handle) 47 | } 48 | 49 | func (l *Log) report(etype uint16, eid uint32, msg string) error { 50 | ss := []*uint16{syscall.StringToUTF16Ptr(msg)} 51 | return windows.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil) 52 | } 53 | 54 | // Info writes an information event msg with event id eid to the end of event log l. 55 | // When EventCreate.exe is used, eid must be between 1 and 1000. 56 | func (l *Log) Info(eid uint32, msg string) error { 57 | return l.report(windows.EVENTLOG_INFORMATION_TYPE, eid, msg) 58 | } 59 | 60 | // Warning writes an warning event msg with event id eid to the end of event log l. 61 | // When EventCreate.exe is used, eid must be between 1 and 1000. 62 | func (l *Log) Warning(eid uint32, msg string) error { 63 | return l.report(windows.EVENTLOG_WARNING_TYPE, eid, msg) 64 | } 65 | 66 | // Error writes an error event msg with event id eid to the end of event log l. 67 | // When EventCreate.exe is used, eid must be between 1 and 1000. 68 | func (l *Log) Error(eid uint32, msg string) error { 69 | return l.report(windows.EVENTLOG_ERROR_TYPE, eid, msg) 70 | } 71 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/example/beep.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 main 8 | 9 | import ( 10 | "syscall" 11 | ) 12 | 13 | // BUG(brainman): MessageBeep Windows api is broken on Windows 7, 14 | // so this example does not beep when runs as service on Windows 7. 15 | 16 | var ( 17 | beepFunc = syscall.MustLoadDLL("user32.dll").MustFindProc("MessageBeep") 18 | ) 19 | 20 | func beep() { 21 | beepFunc.Call(0xffffffff) 22 | } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/example/install.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 main 8 | 9 | import ( 10 | "fmt" 11 | "os" 12 | "path/filepath" 13 | 14 | "golang.org/x/sys/windows/svc/eventlog" 15 | "golang.org/x/sys/windows/svc/mgr" 16 | ) 17 | 18 | func exePath() (string, error) { 19 | prog := os.Args[0] 20 | p, err := filepath.Abs(prog) 21 | if err != nil { 22 | return "", err 23 | } 24 | fi, err := os.Stat(p) 25 | if err == nil { 26 | if !fi.Mode().IsDir() { 27 | return p, nil 28 | } 29 | err = fmt.Errorf("%s is directory", p) 30 | } 31 | if filepath.Ext(p) == "" { 32 | p += ".exe" 33 | fi, err := os.Stat(p) 34 | if err == nil { 35 | if !fi.Mode().IsDir() { 36 | return p, nil 37 | } 38 | err = fmt.Errorf("%s is directory", p) 39 | } 40 | } 41 | return "", err 42 | } 43 | 44 | func installService(name, desc string) error { 45 | exepath, err := exePath() 46 | if err != nil { 47 | return err 48 | } 49 | m, err := mgr.Connect() 50 | if err != nil { 51 | return err 52 | } 53 | defer m.Disconnect() 54 | s, err := m.OpenService(name) 55 | if err == nil { 56 | s.Close() 57 | return fmt.Errorf("service %s already exists", name) 58 | } 59 | s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc}, "is", "auto-started") 60 | if err != nil { 61 | return err 62 | } 63 | defer s.Close() 64 | err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info) 65 | if err != nil { 66 | s.Delete() 67 | return fmt.Errorf("SetupEventLogSource() failed: %s", err) 68 | } 69 | return nil 70 | } 71 | 72 | func removeService(name string) error { 73 | m, err := mgr.Connect() 74 | if err != nil { 75 | return err 76 | } 77 | defer m.Disconnect() 78 | s, err := m.OpenService(name) 79 | if err != nil { 80 | return fmt.Errorf("service %s is not installed", name) 81 | } 82 | defer s.Close() 83 | err = s.Delete() 84 | if err != nil { 85 | return err 86 | } 87 | err = eventlog.Remove(name) 88 | if err != nil { 89 | return fmt.Errorf("RemoveEventLogSource() failed: %s", err) 90 | } 91 | return nil 92 | } 93 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/example/main.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 | // Example service program that beeps. 8 | // 9 | // The program demonstrates how to create Windows service and 10 | // install / remove it on a computer. It also shows how to 11 | // stop / start / pause / continue any service, and how to 12 | // write to event log. It also shows how to use debug 13 | // facilities available in debug package. 14 | // 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | "log" 20 | "os" 21 | "strings" 22 | 23 | "golang.org/x/sys/windows/svc" 24 | ) 25 | 26 | func usage(errmsg string) { 27 | fmt.Fprintf(os.Stderr, 28 | "%s\n\n"+ 29 | "usage: %s \n"+ 30 | " where is one of\n"+ 31 | " install, remove, debug, start, stop, pause or continue.\n", 32 | errmsg, os.Args[0]) 33 | os.Exit(2) 34 | } 35 | 36 | func main() { 37 | const svcName = "myservice" 38 | 39 | isIntSess, err := svc.IsAnInteractiveSession() 40 | if err != nil { 41 | log.Fatalf("failed to determine if we are running in an interactive session: %v", err) 42 | } 43 | if !isIntSess { 44 | runService(svcName, false) 45 | return 46 | } 47 | 48 | if len(os.Args) < 2 { 49 | usage("no command specified") 50 | } 51 | 52 | cmd := strings.ToLower(os.Args[1]) 53 | switch cmd { 54 | case "debug": 55 | runService(svcName, true) 56 | return 57 | case "install": 58 | err = installService(svcName, "my service") 59 | case "remove": 60 | err = removeService(svcName) 61 | case "start": 62 | err = startService(svcName) 63 | case "stop": 64 | err = controlService(svcName, svc.Stop, svc.Stopped) 65 | case "pause": 66 | err = controlService(svcName, svc.Pause, svc.Paused) 67 | case "continue": 68 | err = controlService(svcName, svc.Continue, svc.Running) 69 | default: 70 | usage(fmt.Sprintf("invalid command %s", cmd)) 71 | } 72 | if err != nil { 73 | log.Fatalf("failed to %s %s: %v", cmd, svcName, err) 74 | } 75 | return 76 | } 77 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/example/manage.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 main 8 | 9 | import ( 10 | "fmt" 11 | "time" 12 | 13 | "golang.org/x/sys/windows/svc" 14 | "golang.org/x/sys/windows/svc/mgr" 15 | ) 16 | 17 | func startService(name string) error { 18 | m, err := mgr.Connect() 19 | if err != nil { 20 | return err 21 | } 22 | defer m.Disconnect() 23 | s, err := m.OpenService(name) 24 | if err != nil { 25 | return fmt.Errorf("could not access service: %v", err) 26 | } 27 | defer s.Close() 28 | err = s.Start("is", "manual-started") 29 | if err != nil { 30 | return fmt.Errorf("could not start service: %v", err) 31 | } 32 | return nil 33 | } 34 | 35 | func controlService(name string, c svc.Cmd, to svc.State) error { 36 | m, err := mgr.Connect() 37 | if err != nil { 38 | return err 39 | } 40 | defer m.Disconnect() 41 | s, err := m.OpenService(name) 42 | if err != nil { 43 | return fmt.Errorf("could not access service: %v", err) 44 | } 45 | defer s.Close() 46 | status, err := s.Control(c) 47 | if err != nil { 48 | return fmt.Errorf("could not send control=%d: %v", c, err) 49 | } 50 | timeout := time.Now().Add(10 * time.Second) 51 | for status.State != to { 52 | if timeout.Before(time.Now()) { 53 | return fmt.Errorf("timeout waiting for service to go to state=%d", to) 54 | } 55 | time.Sleep(300 * time.Millisecond) 56 | status, err = s.Query() 57 | if err != nil { 58 | return fmt.Errorf("could not retrieve service status: %v", err) 59 | } 60 | } 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/example/service.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 main 8 | 9 | import ( 10 | "fmt" 11 | "time" 12 | 13 | "golang.org/x/sys/windows/svc" 14 | "golang.org/x/sys/windows/svc/debug" 15 | "golang.org/x/sys/windows/svc/eventlog" 16 | ) 17 | 18 | var elog debug.Log 19 | 20 | type myservice struct{} 21 | 22 | func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) { 23 | const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue 24 | changes <- svc.Status{State: svc.StartPending} 25 | fasttick := time.Tick(500 * time.Millisecond) 26 | slowtick := time.Tick(2 * time.Second) 27 | tick := fasttick 28 | changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} 29 | loop: 30 | for { 31 | select { 32 | case <-tick: 33 | beep() 34 | elog.Info(1, "beep") 35 | case c := <-r: 36 | switch c.Cmd { 37 | case svc.Interrogate: 38 | changes <- c.CurrentStatus 39 | // Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4 40 | time.Sleep(100 * time.Millisecond) 41 | changes <- c.CurrentStatus 42 | case svc.Stop, svc.Shutdown: 43 | break loop 44 | case svc.Pause: 45 | changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted} 46 | tick = slowtick 47 | case svc.Continue: 48 | changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} 49 | tick = fasttick 50 | default: 51 | elog.Error(1, fmt.Sprintf("unexpected control request #%d", c)) 52 | } 53 | } 54 | } 55 | changes <- svc.Status{State: svc.StopPending} 56 | return 57 | } 58 | 59 | func runService(name string, isDebug bool) { 60 | var err error 61 | if isDebug { 62 | elog = debug.New(name) 63 | } else { 64 | elog, err = eventlog.Open(name) 65 | if err != nil { 66 | return 67 | } 68 | } 69 | defer elog.Close() 70 | 71 | elog.Info(1, fmt.Sprintf("starting %s service", name)) 72 | run := svc.Run 73 | if isDebug { 74 | run = debug.Run 75 | } 76 | err = run(name, &myservice{}) 77 | if err != nil { 78 | elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err)) 79 | return 80 | } 81 | elog.Info(1, fmt.Sprintf("%s service stopped", name)) 82 | } 83 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/go12.c: -------------------------------------------------------------------------------- 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 | // +build !go1.3 7 | 8 | // copied from pkg/runtime 9 | typedef unsigned int uint32; 10 | typedef unsigned long long int uint64; 11 | #ifdef _64BIT 12 | typedef uint64 uintptr; 13 | #else 14 | typedef uint32 uintptr; 15 | #endif 16 | 17 | // from sys_386.s or sys_amd64.s 18 | void ·servicemain(void); 19 | 20 | void 21 | ·getServiceMain(uintptr *r) 22 | { 23 | *r = (uintptr)·servicemain; 24 | } 25 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/go12.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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.3 7 | 8 | package svc 9 | 10 | // from go12.c 11 | func getServiceMain(r *uintptr) 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/go13.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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.3 7 | 8 | package svc 9 | 10 | import "unsafe" 11 | 12 | const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const 13 | 14 | // Should be a built-in for unsafe.Pointer? 15 | func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { 16 | return unsafe.Pointer(uintptr(p) + x) 17 | } 18 | 19 | // funcPC returns the entry PC of the function f. 20 | // It assumes that f is a func value. Otherwise the behavior is undefined. 21 | func funcPC(f interface{}) uintptr { 22 | return **(**uintptr)(add(unsafe.Pointer(&f), ptrSize)) 23 | } 24 | 25 | // from sys_386.s and sys_amd64.s 26 | func servicectlhandler(ctl uint32) uintptr 27 | func servicemain(argc uint32, argv **uint16) 28 | 29 | func getServiceMain(r *uintptr) { 30 | *r = funcPC(servicemain) 31 | } 32 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/mgr/service.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 mgr 8 | 9 | import ( 10 | "syscall" 11 | 12 | "golang.org/x/sys/windows" 13 | "golang.org/x/sys/windows/svc" 14 | ) 15 | 16 | // TODO(brainman): Use EnumDependentServices to enumerate dependent services. 17 | 18 | // TODO(brainman): Use EnumServicesStatus to enumerate services in the specified service control manager database. 19 | 20 | // Service is used to access Windows service. 21 | type Service struct { 22 | Name string 23 | Handle windows.Handle 24 | } 25 | 26 | // Delete marks service s for deletion from the service control manager database. 27 | func (s *Service) Delete() error { 28 | return windows.DeleteService(s.Handle) 29 | } 30 | 31 | // Close relinquish access to the service s. 32 | func (s *Service) Close() error { 33 | return windows.CloseServiceHandle(s.Handle) 34 | } 35 | 36 | // Start starts service s. 37 | // args will be passed to svc.Handler.Execute. 38 | func (s *Service) Start(args ...string) error { 39 | var p **uint16 40 | if len(args) > 0 { 41 | vs := make([]*uint16, len(args)) 42 | for i, _ := range vs { 43 | vs[i] = syscall.StringToUTF16Ptr(args[i]) 44 | } 45 | p = &vs[0] 46 | } 47 | return windows.StartService(s.Handle, uint32(len(args)), p) 48 | } 49 | 50 | // Control sends state change request c to the servce s. 51 | func (s *Service) Control(c svc.Cmd) (svc.Status, error) { 52 | var t windows.SERVICE_STATUS 53 | err := windows.ControlService(s.Handle, uint32(c), &t) 54 | if err != nil { 55 | return svc.Status{}, err 56 | } 57 | return svc.Status{ 58 | State: svc.State(t.CurrentState), 59 | Accepts: svc.Accepted(t.ControlsAccepted), 60 | }, nil 61 | } 62 | 63 | // Query returns current status of service s. 64 | func (s *Service) Query() (svc.Status, error) { 65 | var t windows.SERVICE_STATUS 66 | err := windows.QueryServiceStatus(s.Handle, &t) 67 | if err != nil { 68 | return svc.Status{}, err 69 | } 70 | return svc.Status{ 71 | State: svc.State(t.CurrentState), 72 | Accepts: svc.Accepted(t.ControlsAccepted), 73 | }, nil 74 | } 75 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/security.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 svc 8 | 9 | import ( 10 | "unsafe" 11 | 12 | "golang.org/x/sys/windows" 13 | ) 14 | 15 | func allocSid(subAuth0 uint32) (*windows.SID, error) { 16 | var sid *windows.SID 17 | err := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY, 18 | 1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid) 19 | if err != nil { 20 | return nil, err 21 | } 22 | return sid, nil 23 | } 24 | 25 | // IsAnInteractiveSession determines if calling process is running interactively. 26 | // It queries the process token for membership in the Interactive group. 27 | // http://stackoverflow.com/questions/2668851/how-do-i-detect-that-my-application-is-running-as-service-or-in-an-interactive-s 28 | func IsAnInteractiveSession() (bool, error) { 29 | interSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID) 30 | if err != nil { 31 | return false, err 32 | } 33 | defer windows.FreeSid(interSid) 34 | 35 | serviceSid, err := allocSid(windows.SECURITY_SERVICE_RID) 36 | if err != nil { 37 | return false, err 38 | } 39 | defer windows.FreeSid(serviceSid) 40 | 41 | t, err := windows.OpenCurrentProcessToken() 42 | if err != nil { 43 | return false, err 44 | } 45 | defer t.Close() 46 | 47 | gs, err := t.GetTokenGroups() 48 | if err != nil { 49 | return false, err 50 | } 51 | p := unsafe.Pointer(&gs.Groups[0]) 52 | groups := (*[2 << 20]windows.SIDAndAttributes)(p)[:gs.GroupCount] 53 | for _, g := range groups { 54 | if windows.EqualSid(g.Sid, interSid) { 55 | return true, nil 56 | } 57 | if windows.EqualSid(g.Sid, serviceSid) { 58 | return false, nil 59 | } 60 | } 61 | return false, nil 62 | } 63 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/sys_386.s: -------------------------------------------------------------------------------- 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 | // func servicemain(argc uint32, argv **uint16) 8 | TEXT ·servicemain(SB),7,$0 9 | MOVL argc+0(FP), AX 10 | MOVL AX, ·sArgc(SB) 11 | MOVL argv+4(FP), AX 12 | MOVL AX, ·sArgv(SB) 13 | 14 | PUSHL BP 15 | PUSHL BX 16 | PUSHL SI 17 | PUSHL DI 18 | 19 | SUBL $12, SP 20 | 21 | MOVL ·sName(SB), AX 22 | MOVL AX, (SP) 23 | MOVL $·servicectlhandler(SB), AX 24 | MOVL AX, 4(SP) 25 | MOVL ·cRegisterServiceCtrlHandlerW(SB), AX 26 | MOVL SP, BP 27 | CALL AX 28 | MOVL BP, SP 29 | CMPL AX, $0 30 | JE exit 31 | MOVL AX, ·ssHandle(SB) 32 | 33 | MOVL ·goWaitsH(SB), AX 34 | MOVL AX, (SP) 35 | MOVL ·cSetEvent(SB), AX 36 | MOVL SP, BP 37 | CALL AX 38 | MOVL BP, SP 39 | 40 | MOVL ·cWaitsH(SB), AX 41 | MOVL AX, (SP) 42 | MOVL $-1, AX 43 | MOVL AX, 4(SP) 44 | MOVL ·cWaitForSingleObject(SB), AX 45 | MOVL SP, BP 46 | CALL AX 47 | MOVL BP, SP 48 | 49 | exit: 50 | ADDL $12, SP 51 | 52 | POPL DI 53 | POPL SI 54 | POPL BX 55 | POPL BP 56 | 57 | MOVL 0(SP), CX 58 | ADDL $12, SP 59 | JMP CX 60 | 61 | // I do not know why, but this seems to be the only way to call 62 | // ctlHandlerProc on Windows 7. 63 | 64 | // func servicectlhandler(ctl uint32) uintptr 65 | TEXT ·servicectlhandler(SB),7,$0 66 | MOVL ·ctlHandlerProc(SB), CX 67 | JMP CX 68 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/sys_amd64.s: -------------------------------------------------------------------------------- 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 | // func servicemain(argc uint32, argv **uint16) 8 | TEXT ·servicemain(SB),7,$0 9 | MOVL CX, ·sArgc(SB) 10 | MOVL DX, ·sArgv(SB) 11 | 12 | SUBQ $32, SP // stack for the first 4 syscall params 13 | 14 | MOVQ ·sName(SB), CX 15 | MOVQ $·servicectlhandler(SB), DX 16 | MOVQ ·cRegisterServiceCtrlHandlerW(SB), AX 17 | CALL AX 18 | CMPQ AX, $0 19 | JE exit 20 | MOVQ AX, ·ssHandle(SB) 21 | 22 | MOVQ ·goWaitsH(SB), CX 23 | MOVQ ·cSetEvent(SB), AX 24 | CALL AX 25 | 26 | MOVQ ·cWaitsH(SB), CX 27 | MOVQ $4294967295, DX 28 | MOVQ ·cWaitForSingleObject(SB), AX 29 | CALL AX 30 | 31 | exit: 32 | ADDQ $32, SP 33 | RET 34 | 35 | // I do not know why, but this seems to be the only way to call 36 | // ctlHandlerProc on Windows 7. 37 | 38 | // func servicectlhandler(ctl uint32) uintptr 39 | TEXT ·servicectlhandler(SB),7,$0 40 | MOVQ ·ctlHandlerProc(SB), AX 41 | JMP AX 42 | -------------------------------------------------------------------------------- /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 | // The primary use of this package is inside other packages that provide a more 15 | // portable interface to the system, such as "os", "time" and "net". Use 16 | // those packages rather than this one if you can. 17 | // For details of the functions and data types in this package consult 18 | // the manuals for the appropriate operating system. 19 | // These calls return err == nil to indicate success; otherwise 20 | // err represents an operating system error describing the failure and 21 | // holds a value of type syscall.Errno. 22 | package windows // import "golang.org/x/sys/windows" 23 | 24 | import ( 25 | "syscall" 26 | ) 27 | 28 | // ByteSliceFromString returns a NUL-terminated slice of bytes 29 | // containing the text of s. If s contains a NUL byte at any 30 | // location, it returns (nil, syscall.EINVAL). 31 | func ByteSliceFromString(s string) ([]byte, error) { 32 | for i := 0; i < len(s); i++ { 33 | if s[i] == 0 { 34 | return nil, syscall.EINVAL 35 | } 36 | } 37 | a := make([]byte, len(s)+1) 38 | copy(a, s) 39 | return a, nil 40 | } 41 | 42 | // BytePtrFromString returns a pointer to a NUL-terminated array of 43 | // bytes containing the text of s. If s contains a NUL byte at any 44 | // location, it returns (nil, syscall.EINVAL). 45 | func BytePtrFromString(s string) (*byte, error) { 46 | a, err := ByteSliceFromString(s) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return &a[0], nil 51 | } 52 | 53 | // Single-word zero for use when we need a valid pointer to 0 bytes. 54 | // See mksyscall.pl. 55 | var _zero uintptr 56 | 57 | func (ts *Timespec) Unix() (sec int64, nsec int64) { 58 | return int64(ts.Sec), int64(ts.Nsec) 59 | } 60 | 61 | func (tv *Timeval) Unix() (sec int64, nsec int64) { 62 | return int64(tv.Sec), int64(tv.Usec) * 1000 63 | } 64 | 65 | func (ts *Timespec) Nano() int64 { 66 | return int64(ts.Sec)*1e9 + int64(ts.Nsec) 67 | } 68 | 69 | func (tv *Timeval) Nano() int64 { 70 | return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 71 | } 72 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/ztypes_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/ztypes_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/gopkg.in/gemnasium/logrus-airbrake-hook.v2/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Gemnasium 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/gopkg.in/gemnasium/logrus-airbrake-hook.v2/airbrake.go: -------------------------------------------------------------------------------- 1 | package airbrake // import "gopkg.in/gemnasium/logrus-airbrake-hook.v2" 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | 9 | "github.com/Sirupsen/logrus" 10 | "gopkg.in/airbrake/gobrake.v2" 11 | ) 12 | 13 | // AirbrakeHook to send exceptions to an exception-tracking service compatible 14 | // with the Airbrake API. 15 | type airbrakeHook struct { 16 | Airbrake *gobrake.Notifier 17 | } 18 | 19 | func NewHook(projectID int64, apiKey, env string) *airbrakeHook { 20 | airbrake := gobrake.NewNotifier(projectID, apiKey) 21 | airbrake.AddFilter(func(notice *gobrake.Notice) *gobrake.Notice { 22 | if env == "development" { 23 | return nil 24 | } 25 | notice.Context["environment"] = env 26 | return notice 27 | }) 28 | hook := &airbrakeHook{ 29 | Airbrake: airbrake, 30 | } 31 | return hook 32 | } 33 | 34 | func (hook *airbrakeHook) Fire(entry *logrus.Entry) error { 35 | var notifyErr error 36 | err, ok := entry.Data["error"].(error) 37 | if ok { 38 | notifyErr = err 39 | } else { 40 | notifyErr = errors.New(entry.Message) 41 | } 42 | var req *http.Request 43 | for k, v := range entry.Data { 44 | if r, ok := v.(*http.Request); ok { 45 | req = r 46 | delete(entry.Data, k) 47 | break 48 | } 49 | } 50 | notice := hook.Airbrake.Notice(notifyErr, req, 3) 51 | for k, v := range entry.Data { 52 | notice.Context[k] = fmt.Sprintf("%s", v) 53 | } 54 | 55 | hook.sendNotice(notice) 56 | return nil 57 | } 58 | 59 | func (hook *airbrakeHook) sendNotice(notice *gobrake.Notice) { 60 | if _, err := hook.Airbrake.SendNotice(notice); err != nil { 61 | fmt.Fprintf(os.Stderr, "Failed to send error to Airbrake: %v\n", err) 62 | } 63 | } 64 | 65 | func (hook *airbrakeHook) Levels() []logrus.Level { 66 | return []logrus.Level{ 67 | logrus.ErrorLevel, 68 | logrus.FatalLevel, 69 | logrus.PanicLevel, 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/LICENSE: -------------------------------------------------------------------------------- 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/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 | for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { 55 | an = an*10 + int64(ar[ai]-'0') 56 | } 57 | for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { 58 | bn = bn*10 + int64(br[bi]-'0') 59 | } 60 | if an != bn { 61 | return an < bn 62 | } 63 | if ai != bi { 64 | return ai < bi 65 | } 66 | return ar[i] < br[i] 67 | } 68 | return len(ar) < len(br) 69 | } 70 | 71 | // keyFloat returns a float value for v if it is a number/bool 72 | // and whether it is a number/bool or not. 73 | func keyFloat(v reflect.Value) (f float64, ok bool) { 74 | switch v.Kind() { 75 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 76 | return float64(v.Int()), true 77 | case reflect.Float32, reflect.Float64: 78 | return v.Float(), true 79 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 80 | return float64(v.Uint()), true 81 | case reflect.Bool: 82 | if v.Bool() { 83 | return 1, true 84 | } 85 | return 0, true 86 | } 87 | return 0, false 88 | } 89 | 90 | // numLess returns whether a < b. 91 | // a and b must necessarily have the same kind. 92 | func numLess(a, b reflect.Value) bool { 93 | switch a.Kind() { 94 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 95 | return a.Int() < b.Int() 96 | case reflect.Float32, reflect.Float64: 97 | return a.Float() < b.Float() 98 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 99 | return a.Uint() < b.Uint() 100 | case reflect.Bool: 101 | return !a.Bool() && b.Bool() 102 | } 103 | panic("not a number") 104 | } 105 | -------------------------------------------------------------------------------- /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 the output encoding is UTF-8, we don't need to recode the buffer. 22 | if emitter.encoding == yaml_UTF8_ENCODING { 23 | if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { 24 | return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) 25 | } 26 | emitter.buffer_pos = 0 27 | return true 28 | } 29 | 30 | // Recode the buffer into the raw buffer. 31 | var low, high int 32 | if emitter.encoding == yaml_UTF16LE_ENCODING { 33 | low, high = 0, 1 34 | } else { 35 | high, low = 1, 0 36 | } 37 | 38 | pos := 0 39 | for pos < emitter.buffer_pos { 40 | // See the "reader.c" code for more details on UTF-8 encoding. Note 41 | // that we assume that the buffer contains a valid UTF-8 sequence. 42 | 43 | // Read the next UTF-8 character. 44 | octet := emitter.buffer[pos] 45 | 46 | var w int 47 | var value rune 48 | switch { 49 | case octet&0x80 == 0x00: 50 | w, value = 1, rune(octet&0x7F) 51 | case octet&0xE0 == 0xC0: 52 | w, value = 2, rune(octet&0x1F) 53 | case octet&0xF0 == 0xE0: 54 | w, value = 3, rune(octet&0x0F) 55 | case octet&0xF8 == 0xF0: 56 | w, value = 4, rune(octet&0x07) 57 | } 58 | for k := 1; k < w; k++ { 59 | octet = emitter.buffer[pos+k] 60 | value = (value << 6) + (rune(octet) & 0x3F) 61 | } 62 | pos += w 63 | 64 | // Write the character. 65 | if value < 0x10000 { 66 | var b [2]byte 67 | b[high] = byte(value >> 8) 68 | b[low] = byte(value & 0xFF) 69 | emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1]) 70 | } else { 71 | // Write the character using a surrogate pair (check "reader.c"). 72 | var b [4]byte 73 | value -= 0x10000 74 | b[high] = byte(0xD8 + (value >> 18)) 75 | b[low] = byte((value >> 10) & 0xFF) 76 | b[high+2] = byte(0xDC + ((value >> 8) & 0xFF)) 77 | b[low+2] = byte(value & 0xFF) 78 | emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3]) 79 | } 80 | } 81 | 82 | // Write the raw buffer. 83 | if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil { 84 | return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) 85 | } 86 | emitter.buffer_pos = 0 87 | emitter.raw_buffer = emitter.raw_buffer[:0] 88 | return true 89 | } 90 | --------------------------------------------------------------------------------