diff --git a/.github/workflows/go-cross.yml b/.github/workflows/go-cross.yml new file mode 100644 index 0000000..57c0ec0 --- /dev/null +++ b/.github/workflows/go-cross.yml @@ -0,0 +1,41 @@ +name: Go Matrix +on: [push, pull_request] + +jobs: + + cross: + name: Go + runs-on: ${{ matrix.os }} + env: + CGO_ENABLED: 0 + + strategy: + matrix: + go-version: [ 1.15, 1.x ] + os: [ubuntu-latest, macos-latest, windows-latest] + + steps: + # https://github.com/marketplace/actions/setup-go-environment + - name: Set up Go ${{ matrix.go-version }} + uses: actions/setup-go@v2 + with: + go-version: ${{ matrix.go-version }} + + # https://github.com/marketplace/actions/checkout + - name: Checkout code + uses: actions/checkout@v2 + + # https://github.com/marketplace/actions/cache + - name: Cache Go modules + uses: actions/cache@v2 + with: + path: | + ~/go/pkg/mod # Module download cache + ~/.cache/go-build # Build cache (Linux) + ~/Library/Caches/go-build # Build cache (Mac) + '%LocalAppData%\go-build' # Build cache (Windows) + key: ${{ runner.os }}-${{ matrix.go-version }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-${{ matrix.go-version }}-go- + - name: Test + run: go test -v -cover ./... \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..6f220aa --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,67 @@ +name: Main + +on: + push: + branches: + - master + tags: + - v* + pull_request: + +jobs: + + main: + name: Main Process + runs-on: ubuntu-latest + env: + GO_VERSION: 1.15 + GOLANGCI_LINT_VERSION: v1.33.0 + YAEGI_VERSION: v0.9.8 + CGO_ENABLED: 0 + defaults: + run: + working-directory: ${{ github.workspace }}/go/src/github.com/${{ github.repository }} + + steps: + + # https://github.com/marketplace/actions/setup-go-environment + - name: Set up Go ${{ env.GO_VERSION }} + uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + + # https://github.com/marketplace/actions/checkout + - name: Check out code + uses: actions/checkout@v2 + with: + path: go/src/github.com/${{ github.repository }} + fetch-depth: 0 + + # https://github.com/marketplace/actions/cache + - name: Cache Go modules + uses: actions/cache@v2 + with: + path: ${{ github.workspace }}/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + # https://golangci-lint.run/usage/install#other-ci + - name: Install golangci-lint ${{ env.GOLANGCI_LINT_VERSION }} + run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} + + - name: Install Yaegi ${{ env.YAEGI_VERSION }} + run: curl -sfL https://raw.githubusercontent.com/traefik/yaegi/master/install.sh | bash -s -- -b $(go env GOPATH)/bin ${YAEGI_VERSION} + + - name: Setup GOPATH + run: go env -w GOPATH=${{ github.workspace }}/go + + - name: Check and get dependencies + run: | + go mod tidy + git diff --exit-code go.mod + # git diff --exit-code go.sum + go mod download + go mod vendor + # git diff --exit-code ./vendor/ + - name: Lint and Tests + run: make \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..68729d6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea/ +.DS_Store \ No newline at end of file diff --git a/.golangci.toml b/.golangci.toml new file mode 100644 index 0000000..675d7ed --- /dev/null +++ b/.golangci.toml @@ -0,0 +1,45 @@ +[run] + timeout = "3m" + skip-files = [] + skip-dirs = [] + +[linters-settings] + + [linters-settings.govet] + check-shadowing = false + + [linters-settings.golint] + min-confidence = 0.0 + + [linters-settings.gocyclo] + min-complexity = 12.0 + + [linters-settings.maligned] + suggest-new = true + + [linters-settings.goconst] + min-len = 3.0 + min-occurrences = 4.0 + + [linters-settings.misspell] + locale = "US" + + [linters-settings.funlen] + lines = 60 # default 60 + statements = 40 # default 40 + +[linters] + enable-all = true + disable = [ + "goerr113", + "nlreturn", + "testpackage", + "paralleltest", + "tparallel", + ] + +[issues] + exclude-use-default = false + max-per-linter = 0 + max-same-issues = 0 + exclude = [] \ No newline at end of file diff --git a/.traefik.yml b/.traefik.yml new file mode 100644 index 0000000..7396d9f --- /dev/null +++ b/.traefik.yml @@ -0,0 +1,12 @@ +displayName: Gelf Logger +summary: Logs HTTP requests, optionally appends trace id and request start time headers. +type: middleware +import: github.com/itninja04/plugin-gelflog +testData: + gelfEndpoint: "127.0.0.1" + gelfPort: 12202 + hostnameOverride: "" + emitTraceId: true + traceIdHeader: "X-TraceId-AV" + emitRequestStart: true + requestStartTimeHeader: "X-Request-Start" \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0c7560b --- /dev/null +++ b/Makefile @@ -0,0 +1,17 @@ +.PHONY: lint test vendor clean + +export GO111MODULE=on + +default: lint test + +lint: + golangci-lint run + +test: + go test -v -cover ./... + +vendor: + go mod vendor + +clean: + rm -rf ./vendor \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..1e967fa --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ +# GELF Log + +This [Traefik](https://github.com/traefik/traefik) plugin is as middleware to send request headers along with optional TraceId and Request Start Time to a GELF compatible ingest tool. + +docker-compose.yml: +```yaml +version: "3.3" + +services: + traefik: + image: traefik:v2.4 + command: + - --api.insecure=true + - --entrypoints.web.address=:80 + - --providers.docker=true + - --providers.docker.exposedbydefault=false + - --experimental.plugins.gelflog.modulename=github.com/itninja04/plugin-gelflog + - --experimental.plugins.gelflog.version=v0.1.6 + ports: + - 80:80 + - 8080:8080 + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + networks: + - test + whoami: + image: containous/whoami + labels: + traefik.enable: true + traefik.http.routers.whoami.rule: Host(`localhost`) + traefik.http.routers.whoami.entrypoints: web + traefik.http.middlewares.gelf-logger.plugin.gelflog.gelfEndpoint: "127.0.0.1" + traefik.http.middlewares.gelf-logger.plugin.gelflog.gelfPort: 12202 + traefik.http.middlewares.gelf-logger.plugin.gelflog.hostnameOverride: "" + traefik.http.middlewares.gelf-logger.plugin.gelflog.emitTraceId: true + traefik.http.middlewares.gelf-logger.plugin.gelflog.traceIdHeader: "X-TraceId-AV" + traefik.http.middlewares.gelf-logger.plugin.gelflog.emitRequestStart: true + traefik.http.middlewares.gelf-logger.plugin.gelflog.requestStartTimeHeader: "X-Request-Start" + traefik.http.routers.whoami.middlewares: gelf-logger + networks: + - test + +networks: + test: +``` +## Configuration + +To configure this plugin you should add its configuration to the Traefik dynamic configuration as explained [here](https://docs.traefik.io/getting-started/configuration-overview/#the-dynamic-configuration). +The following snippet shows how to configure this plugin with the File provider in TOML and YAML: + +```toml +# Log Requests and Responses +[http.middlewares] + [http.middlewares.gelf-logger.gelflog] + gelfEndpoint = "127.0.0.1" + gelfPort = 12202 + hostnameOverride = "" + emitTraceId = true + traceIdHeader = "X-TraceId-AV" + emitRequestStart = true + requestStartTimeHeader = "X-Request-Start" +``` + +```yaml +# Log Requests and Responses +http: + middlewares: + gelf-logger: + plugin: + gelflog: + gelfEndpoint: "127.0.0.1" + gelfPort: 12202 + hostnameOverride: "" + emitTraceId: true + traceIdHeader: "X-TraceId-AV" + emitRequestStart: true + requestStartTimeHeader: "X-Request-Start" +``` diff --git a/gelflog.go b/gelflog.go new file mode 100644 index 0000000..7174416 --- /dev/null +++ b/gelflog.go @@ -0,0 +1,116 @@ +package plugin_gelflog + +import ( + "context" + "fmt" + "github.com/kjk/betterguid" + "gopkg.in/Graylog2/go-gelf.v2/gelf" + "log" + "net/http" + "os" + "time" +) + +var GelfWriter *gelf.UDPWriter +var GelfHostname string +var MWConfig *Config +// Config holds the plugin configuration. +type Config struct { + GelfEndpoint string `json:"gelfEndpoint,omitempty"` + GelfPort int `json:"gelfPort,omitempty"` + HostnameOverride string `json:"hostnameOverride"` + EmitTraceId bool `json:"emitTraceId"` + TraceIdHeader string `json:"traceIdHeader"` + EmitRequestStart bool `json:"emitRequestStart"` + RequestStartTimeHeader string `json:"requestStartTimeHeader"` +} + +// CreateConfig creates and initializes the plugin configuration. +func CreateConfig() *Config { + return &Config{ + EmitTraceId: true, + TraceIdHeader: "X-TraceId-AV", + EmitRequestStart: true, + RequestStartTimeHeader: "X-Request-Start", + } +} + +type GelfLog struct { + Name string + Next http.Handler + Config *Config +} + +// New creates and returns a plugin instance. +func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { + tLog := &GelfLog{ + Name: name, + Next: next, + Config: config, + } + if config == nil { + //log.Fatal("config for Gelf Logger empty") + return nil, fmt.Errorf("config can not be empty") + } + MWConfig = config + if config.HostnameOverride == "" { + GelfHostname, _ = os.Hostname() + } + GelfWriter, _ = gelf.NewUDPWriter(fmt.Sprintf("%s:%d", config.GelfEndpoint, config.GelfPort)) + return tLog, nil +} + + +func (h *GelfLog) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + id := betterguid.New() + if MWConfig.EmitRequestStart { + req.Header.Set(MWConfig.RequestStartTimeHeader, fmt.Sprint(makeTimestampMilli())) + } + if MWConfig.EmitTraceId { + req.Header.Set(MWConfig.TraceIdHeader, fmt.Sprint(id)) + } + if GelfWriter != nil { + var headerMap = map[string]interface{}{} + for str, val := range req.Header { + headerMap[str] = val + } + headerMap["Host"] = req.Host + message := wrapMessage(fmt.Sprintf("Request to %s", req.Host), fmt.Sprintf("Request to %s", req.Host), 5, headerMap) + e := GelfWriter.WriteMessage(message) + + if e != nil { + log.Println("Received error when sending GELF message:", e.Error()) + } + } + h.Next.ServeHTTP(rw, req) +} + + +func wrapMessage(s string, f string, l int32, ex map[string]interface{}) *gelf.Message { + /* + Level is a stanard syslog level + Facility is deprecated + Line is deprecated + File is deprecated + */ + + m := &gelf.Message{ + Version: "1.1", + Host: GelfHostname, + Short: s, + Full: f, + TimeUnix: float64(time.Now().Unix()), + Level: l, + Extra: ex, + } + + return m +} + +func unixMilli(t time.Time) int64 { + return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond)) +} + +func makeTimestampMilli() int64 { + return unixMilli(time.Now()) +} \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..61e99ce --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module github.com/itninja04/plugin-gelflog + +go 1.14 + +require ( + github.com/kjk/betterguid v0.0.0-20170621091430-c442874ba63a + gopkg.in/Graylog2/go-gelf.v2 v2.0.0-20191017102106-1550ee647df0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..4fd633f --- /dev/null +++ b/go.sum @@ -0,0 +1,6 @@ +github.com/Graylog2/go-gelf v0.0.0-20170811154226-7ebf4f536d8f h1:xMWj7GzE4gCkm8e+661/GJHDXr4h7/jt4kM1Vvr9c5k= +github.com/Graylog2/go-gelf v0.0.0-20170811154226-7ebf4f536d8f/go.mod h1:fBaQWrftOD5CrVCUfoYGHs4X4VViTuGOXA8WloCjTY0= +github.com/kjk/betterguid v0.0.0-20170621091430-c442874ba63a h1:b+Gt8sQs//Sl5Dcem5zP9Qc2FgEUAygREa2AAa2Vmcw= +github.com/kjk/betterguid v0.0.0-20170621091430-c442874ba63a/go.mod h1:uxRAhHE1nl34DpWgfe0CYbNYbCnYplaB6rZH9ReWtUk= +gopkg.in/Graylog2/go-gelf.v2 v2.0.0-20191017102106-1550ee647df0 h1:Xg23ydYYJLmb9AK3XdcEpplHZd1MpN3X2ZeeMoBClmY= +gopkg.in/Graylog2/go-gelf.v2 v2.0.0-20191017102106-1550ee647df0/go.mod h1:CeDeqW4tj9FrgZXF/dQCWZrBdcZWWBenhJtxLH4On2g= diff --git a/vendor/github.com/kjk/betterguid/LICENSE b/vendor/github.com/kjk/betterguid/LICENSE new file mode 100644 index 0000000..e19cd27 --- /dev/null +++ b/vendor/github.com/kjk/betterguid/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Krzysztof Kowalczyk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/github.com/kjk/betterguid/README.md b/vendor/github.com/kjk/betterguid/README.md new file mode 100644 index 0000000..fabbdbd --- /dev/null +++ b/vendor/github.com/kjk/betterguid/README.md @@ -0,0 +1,28 @@ +This is Go package to generate guid (globally unique id) with good properties. + +Usage: +```go +import "github.com/kjk/betterguid" + +id := betterguid.New() +fmt.Printf("guid: '%s'\n", id) +``` + +Generated guids have good properties: +* they're 20 character strings, safe for inclusion in urls (don't require escaping) +* they're based on timestamp; they sort **after** any existing ids +* they contain 72-bits of random data after the timestamp so that IDs won't + collide with other IDs +* they sort **lexicographically** (the timestamp is converted to a string + that will sort correctly) +* they're monotonically increasing. Even if you generate more than one in the + same timestamp, the latter ones will sort after the former ones. We do this + by using the previous random bits but "incrementing" them by 1 (only in the + case of a timestamp collision). + +Read https://www.firebase.com/blog/2015-02-11-firebase-unique-identifiers.html +for more info. + +Based on https://gist.github.com/mikelehen/3596a30bd69384624c11 + +You can read [Generating good, random and unique ids in Go](https://blog.kowalczyk.info/article/JyRZ/generating-good-random-and-unique-ids-in-go.html) to see how it compares to other similar libraries. diff --git a/vendor/github.com/kjk/betterguid/betterguid.go b/vendor/github.com/kjk/betterguid/betterguid.go new file mode 100644 index 0000000..896b570 --- /dev/null +++ b/vendor/github.com/kjk/betterguid/betterguid.go @@ -0,0 +1,69 @@ +package betterguid + +import ( + "math/rand" + "sync" + "time" +) + +const ( + // Modeled after base64 web-safe chars, but ordered by ASCII. + pushChars = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" +) + +var ( + // Timestamp of last push, used to prevent local collisions if you push twice in one ms. + lastPushTimeMs int64 + // We generate 72-bits of randomness which get turned into 12 characters and appended to the + // timestamp to prevent collisions with other clients. We store the last characters we + // generated because in the event of a collision, we'll use those same characters except + // "incremented" by one. + lastRandChars [12]int + mu sync.Mutex + rnd *rand.Rand +) + +func init() { + // seed to get randomness + rnd = rand.New(rand.NewSource(time.Now().UnixNano())) +} + +func genRandPart() { + for i := 0; i < len(lastRandChars); i++ { + lastRandChars[i] = rnd.Intn(64) + } +} + +// New creates a new random, unique id +func New() string { + var id [8 + 12]byte + mu.Lock() + timeMs := time.Now().UTC().UnixNano() / 1e6 + if timeMs == lastPushTimeMs { + // increment lastRandChars + for i := 0; i < 12; i++ { + lastRandChars[i]++ + if lastRandChars[i] < 64 { + break + } + // increment the next byte + lastRandChars[i] = 0 + } + } else { + genRandPart() + } + lastPushTimeMs = timeMs + // put random as the second part + for i := 0; i < 12; i++ { + id[19-i] = pushChars[lastRandChars[i]] + } + mu.Unlock() + + // put current time at the beginning + for i := 7; i >= 0; i-- { + n := int(timeMs % 64) + id[i] = pushChars[n] + timeMs = timeMs / 64 + } + return string(id[:]) +} diff --git a/vendor/github.com/kjk/betterguid/doc.go b/vendor/github.com/kjk/betterguid/doc.go new file mode 100644 index 0000000..f3c3415 --- /dev/null +++ b/vendor/github.com/kjk/betterguid/doc.go @@ -0,0 +1,22 @@ +/* + +Package betterguid generates 20-character guid (globally unique id) strings +with good properties: + +They're 20 character strings, safe for inclusion in urls (don't require escaping) + +They're based on timestamp so that they sort **after** any existing ids + +They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs + +They sort **lexicographically** (so the timestamp is converted to characters that will sort properly) + +They're monotonically increasing. Even if you generate more than one in the same timestamp, thelatter ones will sort after the former ones. We do this by using the previous random bits but "incrementing" them by 1 (only in the case of a timestamp collision). + +Read https://www.firebase.com/blog/2015-02-11-firebase-unique-identifiers.html +for more info. + +Based on https://gist.github.com/mikelehen/3596a30bd69384624c11 + +*/ +package betterguid diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/LICENSE b/vendor/gopkg.in/Graylog2/go-gelf.v2/LICENSE new file mode 100644 index 0000000..bc756ae --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/LICENSE @@ -0,0 +1,21 @@ +Copyright 2012 SocialCode + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/message.go b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/message.go new file mode 100644 index 0000000..fcb182f --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/message.go @@ -0,0 +1,154 @@ +package gelf + +import ( + "bytes" + "encoding/json" + "fmt" + "time" +) + +// Message represents the contents of the GELF message. It is gzipped +// before sending. +type Message struct { + Version string `json:"version"` + Host string `json:"host"` + Short string `json:"short_message"` + Full string `json:"full_message,omitempty"` + TimeUnix float64 `json:"timestamp"` + Level int32 `json:"level,omitempty"` + Facility string `json:"facility,omitempty"` + Extra map[string]interface{} `json:"-"` + RawExtra json.RawMessage `json:"-"` +} + +// Syslog severity levels +const ( + LOG_EMERG = 0 + LOG_ALERT = 1 + LOG_CRIT = 2 + LOG_ERR = 3 + LOG_WARNING = 4 + LOG_NOTICE = 5 + LOG_INFO = 6 + LOG_DEBUG = 7 +) + +func (m *Message) MarshalJSONBuf(buf *bytes.Buffer) error { + b, err := json.Marshal(m) + if err != nil { + return err + } + // write up until the final } + if _, err = buf.Write(b[:len(b)-1]); err != nil { + return err + } + if len(m.Extra) > 0 { + eb, err := json.Marshal(m.Extra) + if err != nil { + return err + } + // merge serialized message + serialized extra map + if err = buf.WriteByte(','); err != nil { + return err + } + // write serialized extra bytes, without enclosing quotes + if _, err = buf.Write(eb[1 : len(eb)-1]); err != nil { + return err + } + } + + if len(m.RawExtra) > 0 { + if err := buf.WriteByte(','); err != nil { + return err + } + + // write serialized extra bytes, without enclosing quotes + if _, err = buf.Write(m.RawExtra[1 : len(m.RawExtra)-1]); err != nil { + return err + } + } + + // write final closing quotes + return buf.WriteByte('}') +} + +func (m *Message) UnmarshalJSON(data []byte) error { + i := make(map[string]interface{}, 16) + if err := json.Unmarshal(data, &i); err != nil { + return err + } + for k, v := range i { + if k[0] == '_' { + if m.Extra == nil { + m.Extra = make(map[string]interface{}, 1) + } + m.Extra[k] = v + continue + } + + ok := true + switch k { + case "version": + m.Version, ok = v.(string) + case "host": + m.Host, ok = v.(string) + case "short_message": + m.Short, ok = v.(string) + case "full_message": + m.Full, ok = v.(string) + case "timestamp": + m.TimeUnix, ok = v.(float64) + case "level": + var level float64 + level, ok = v.(float64) + m.Level = int32(level) + case "facility": + m.Facility, ok = v.(string) + } + + if !ok { + return fmt.Errorf("invalid type for field %s", k) + } + } + return nil +} + +func (m *Message) toBytes(buf *bytes.Buffer) (messageBytes []byte, err error) { + if err = m.MarshalJSONBuf(buf); err != nil { + return nil, err + } + messageBytes = buf.Bytes() + return messageBytes, nil +} + +func constructMessage(p []byte, hostname string, facility string, file string, line int) (m *Message) { + // remove trailing and leading whitespace + p = bytes.TrimSpace(p) + + // If there are newlines in the message, use the first line + // for the short message and set the full message to the + // original input. If the input has no newlines, stick the + // whole thing in Short. + short := p + full := []byte("") + if i := bytes.IndexRune(p, '\n'); i > 0 { + short = p[:i] + full = p + } + + m = &Message{ + Version: "1.1", + Host: hostname, + Short: string(short), + Full: string(full), + TimeUnix: float64(time.Now().UnixNano()) / float64(time.Second), + Level: 6, // info + Facility: facility, + Extra: map[string]interface{}{ + "_file": file, + "_line": line, + }, + } + + return m +} diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/reader.go b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/reader.go new file mode 100644 index 0000000..ff719fc --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/reader.go @@ -0,0 +1,140 @@ +// Copyright 2012 SocialCode. All rights reserved. +// Use of this source code is governed by the MIT +// license that can be found in the LICENSE file. + +package gelf + +import ( + "bytes" + "compress/gzip" + "compress/zlib" + "encoding/json" + "fmt" + "io" + "net" + "strings" + "sync" +) + +type Reader struct { + mu sync.Mutex + conn net.Conn +} + +func NewReader(addr string) (*Reader, error) { + var err error + udpAddr, err := net.ResolveUDPAddr("udp", addr) + if err != nil { + return nil, fmt.Errorf("ResolveUDPAddr('%s'): %s", addr, err) + } + + conn, err := net.ListenUDP("udp", udpAddr) + if err != nil { + return nil, fmt.Errorf("ListenUDP: %s", err) + } + + r := new(Reader) + r.conn = conn + return r, nil +} + +func (r *Reader) Addr() string { + return r.conn.LocalAddr().String() +} + +// FIXME: this will discard data if p isn't big enough to hold the +// full message. +func (r *Reader) Read(p []byte) (int, error) { + msg, err := r.ReadMessage() + if err != nil { + return -1, err + } + + var data string + + if msg.Full == "" { + data = msg.Short + } else { + data = msg.Full + } + + return strings.NewReader(data).Read(p) +} + +func (r *Reader) ReadMessage() (*Message, error) { + cBuf := make([]byte, ChunkSize) + var ( + err error + n, length int + cid, ocid []byte + seq, total uint8 + cHead []byte + cReader io.Reader + chunks [][]byte + ) + + for got := 0; got < 128 && (total == 0 || got < int(total)); got++ { + if n, err = r.conn.Read(cBuf); err != nil { + return nil, fmt.Errorf("Read: %s", err) + } + cHead, cBuf = cBuf[:2], cBuf[:n] + + if bytes.Equal(cHead, magicChunked) { + //fmt.Printf("chunked %v\n", cBuf[:14]) + cid, seq, total = cBuf[2:2+8], cBuf[2+8], cBuf[2+8+1] + if ocid != nil && !bytes.Equal(cid, ocid) { + return nil, fmt.Errorf("out-of-band message %v (awaited %v)", cid, ocid) + } else if ocid == nil { + ocid = cid + chunks = make([][]byte, total) + } + n = len(cBuf) - chunkedHeaderLen + //fmt.Printf("setting chunks[%d]: %d\n", seq, n) + chunks[seq] = append(make([]byte, 0, n), cBuf[chunkedHeaderLen:]...) + length += n + } else { //not chunked + if total > 0 { + return nil, fmt.Errorf("out-of-band message (not chunked)") + } + break + } + } + //fmt.Printf("\nchunks: %v\n", chunks) + + if length > 0 { + if cap(cBuf) < length { + cBuf = append(cBuf, make([]byte, 0, length-cap(cBuf))...) + } + cBuf = cBuf[:0] + for i := range chunks { + //fmt.Printf("appending %d %v\n", i, chunks[i]) + cBuf = append(cBuf, chunks[i]...) + } + cHead = cBuf[:2] + } + + // the data we get from the wire is compressed + if bytes.Equal(cHead, magicGzip) { + cReader, err = gzip.NewReader(bytes.NewReader(cBuf)) + } else if cHead[0] == magicZlib[0] && + (int(cHead[0])*256+int(cHead[1]))%31 == 0 { + // zlib is slightly more complicated, but correct + cReader, err = zlib.NewReader(bytes.NewReader(cBuf)) + } else { + // compliance with https://github.com/Graylog2/graylog2-server + // treating all messages as uncompressed if they are not gzip, zlib or + // chunked + cReader = bytes.NewReader(cBuf) + } + + if err != nil { + return nil, fmt.Errorf("NewReader: %s", err) + } + + msg := new(Message) + if err := json.NewDecoder(cReader).Decode(&msg); err != nil { + return nil, fmt.Errorf("json.Unmarshal: %s", err) + } + + return msg, nil +} diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/tcpreader.go b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/tcpreader.go new file mode 100644 index 0000000..74255ec --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/tcpreader.go @@ -0,0 +1,156 @@ +package gelf + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "time" +) + +type TCPReader struct { + listener *net.TCPListener + conn net.Conn + messages chan []byte +} + +type connChannels struct { + drop chan string + confirm chan string +} + +func newTCPReader(addr string) (*TCPReader, chan string, chan string, error) { + var err error + tcpAddr, err := net.ResolveTCPAddr("tcp", addr) + if err != nil { + return nil, nil, nil, fmt.Errorf("ResolveTCPAddr('%s'): %s", addr, err) + } + + listener, err := net.ListenTCP("tcp", tcpAddr) + if err != nil { + return nil, nil, nil, fmt.Errorf("ListenTCP: %s", err) + } + + r := &TCPReader{ + listener: listener, + messages: make(chan []byte, 100), // Make a buffered channel with at most 100 messages + } + + closeSignal := make(chan string, 1) + doneSignal := make(chan string, 1) + + go r.listenUntilCloseSignal(closeSignal, doneSignal) + + return r, closeSignal, doneSignal, nil +} + +func (r *TCPReader) accepter(connections chan net.Conn) { + for { + conn, err := r.listener.Accept() + if err != nil { + break + } + connections <- conn + } +} + +func (r *TCPReader) listenUntilCloseSignal(closeSignal chan string, doneSignal chan string) { + defer func() { doneSignal <- "done" }() + defer r.listener.Close() + var conns []connChannels + connectionsChannel := make(chan net.Conn, 1) + go r.accepter(connectionsChannel) + for { + select { + case conn := <-connectionsChannel: + dropSignal := make(chan string, 1) + dropConfirm := make(chan string, 1) + channels := connChannels{drop: dropSignal, confirm: dropConfirm} + go handleConnection(conn, r.messages, dropSignal, dropConfirm) + conns = append(conns, channels) + default: + } + + select { + case sig := <-closeSignal: + if sig == "stop" || sig == "drop" { + if len(conns) >= 1 { + for _, s := range conns { + if s.drop != nil { + s.drop <- "drop" + <-s.confirm + conns = append(conns[:0], conns[1:]...) + } + } + if sig == "stop" { + return + } + } else if sig == "stop" { + closeSignal <- "stop" + } + if sig == "drop" { + doneSignal <- "done" + } + } + default: + } + } +} + +func (r *TCPReader) addr() string { + return r.listener.Addr().String() +} + +func handleConnection(conn net.Conn, messages chan<- []byte, dropSignal chan string, dropConfirm chan string) { + defer func() { dropConfirm <- "done" }() + defer conn.Close() + reader := bufio.NewReader(conn) + + var b []byte + var err error + drop := false + canDrop := false + + for { + conn.SetDeadline(time.Now().Add(2 * time.Second)) + if b, err = reader.ReadBytes(0); err != nil { + if drop { + return + } + } else if len(b) > 0 { + messages <- b + canDrop = true + if drop { + return + } + } else if drop { + return + } + select { + case sig := <-dropSignal: + if sig == "drop" { + drop = true + time.Sleep(1 * time.Second) + if canDrop { + return + } + } + default: + } + } +} + +func (r *TCPReader) readMessage() (*Message, error) { + b := <-r.messages + + var msg Message + if err := json.Unmarshal(b[:len(b)-1], &msg); err != nil { + return nil, fmt.Errorf("json.Unmarshal: %s", err) + } + + return &msg, nil +} + +func (r *TCPReader) Close() { + r.listener.Close() +} diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/tcpwriter.go b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/tcpwriter.go new file mode 100644 index 0000000..5a637ff --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/tcpwriter.go @@ -0,0 +1,107 @@ +package gelf + +import ( + "fmt" + "net" + "os" + "sync" + "time" +) + +const ( + DefaultMaxReconnect = 3 + DefaultReconnectDelay = 1 +) + +type TCPWriter struct { + GelfWriter + mu sync.Mutex + MaxReconnect int + ReconnectDelay time.Duration +} + +func NewTCPWriter(addr string) (*TCPWriter, error) { + var err error + w := new(TCPWriter) + w.MaxReconnect = DefaultMaxReconnect + w.ReconnectDelay = DefaultReconnectDelay + w.proto = "tcp" + w.addr = addr + + if w.conn, err = net.Dial("tcp", addr); err != nil { + return nil, err + } + if w.hostname, err = os.Hostname(); err != nil { + return nil, err + } + + return w, nil +} + +// WriteMessage sends the specified message to the GELF server +// specified in the call to New(). It assumes all the fields are +// filled out appropriately. In general, clients will want to use +// Write, rather than WriteMessage. +func (w *TCPWriter) WriteMessage(m *Message) (err error) { + buf := newBuffer() + defer bufPool.Put(buf) + messageBytes, err := m.toBytes(buf) + if err != nil { + return err + } + + messageBytes = append(messageBytes, 0) + + n, err := w.writeToSocketWithReconnectAttempts(messageBytes) + if err != nil { + return err + } + if n != len(messageBytes) { + return fmt.Errorf("bad write (%d/%d)", n, len(messageBytes)) + } + + return nil +} + +func (w *TCPWriter) Write(p []byte) (n int, err error) { + file, line := getCallerIgnoringLogMulti(1) + + m := constructMessage(p, w.hostname, w.Facility, file, line) + + if err = w.WriteMessage(m); err != nil { + return 0, err + } + + return len(p), nil +} + +func (w *TCPWriter) writeToSocketWithReconnectAttempts(zBytes []byte) (n int, err error) { + var errConn error + var i int + + w.mu.Lock() + for i = 0; i <= w.MaxReconnect; i++ { + errConn = nil + + if w.conn != nil { + n, err = w.conn.Write(zBytes) + } else { + err = fmt.Errorf("Connection was nil, will attempt reconnect") + } + if err != nil { + time.Sleep(w.ReconnectDelay * time.Second) + w.conn, errConn = net.Dial("tcp", w.addr) + } else { + break + } + } + w.mu.Unlock() + + if i > w.MaxReconnect { + return 0, fmt.Errorf("Maximum reconnection attempts was reached; giving up") + } + if errConn != nil { + return 0, fmt.Errorf("Write Failed: %s\nReconnection failed: %s", err, errConn) + } + return n, nil +} diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/udpwriter.go b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/udpwriter.go new file mode 100644 index 0000000..23bbd5e --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/udpwriter.go @@ -0,0 +1,231 @@ +// Copyright 2012 SocialCode. All rights reserved. +// Use of this source code is governed by the MIT +// license that can be found in the LICENSE file. + +package gelf + +import ( + "bytes" + "compress/flate" + "compress/gzip" + "compress/zlib" + "crypto/rand" + "fmt" + "io" + "net" + "os" + "path" + "sync" +) + +type UDPWriter struct { + GelfWriter + CompressionLevel int // one of the consts from compress/flate + CompressionType CompressType +} + +// What compression type the writer should use when sending messages +// to the graylog2 server +type CompressType int + +const ( + CompressGzip CompressType = iota + CompressZlib + CompressNone +) + +// Used to control GELF chunking. Should be less than (MTU - len(UDP +// header)). +// +// TODO: generate dynamically using Path MTU Discovery? +const ( + ChunkSize = 1420 + chunkedHeaderLen = 12 + chunkedDataLen = ChunkSize - chunkedHeaderLen +) + +var ( + magicChunked = []byte{0x1e, 0x0f} + magicZlib = []byte{0x78} + magicGzip = []byte{0x1f, 0x8b} +) + +// numChunks returns the number of GELF chunks necessary to transmit +// the given compressed buffer. +func numChunks(b []byte) int { + lenB := len(b) + if lenB <= ChunkSize { + return 1 + } + return len(b)/chunkedDataLen + 1 +} + +// New returns a new GELF Writer. This writer can be used to send the +// output of the standard Go log functions to a central GELF server by +// passing it to log.SetOutput() +func NewUDPWriter(addr string) (*UDPWriter, error) { + var err error + w := new(UDPWriter) + w.CompressionLevel = flate.BestSpeed + + if w.conn, err = net.Dial("udp", addr); err != nil { + return nil, err + } + if w.hostname, err = os.Hostname(); err != nil { + return nil, err + } + + w.Facility = path.Base(os.Args[0]) + + return w, nil +} + +// writes the gzip compressed byte array to the connection as a series +// of GELF chunked messages. The format is documented at +// http://docs.graylog.org/en/2.1/pages/gelf.html as: +// +// 2-byte magic (0x1e 0x0f), 8 byte id, 1 byte sequence id, 1 byte +// total, chunk-data +func (w *GelfWriter) writeChunked(zBytes []byte) (err error) { + b := make([]byte, 0, ChunkSize) + buf := bytes.NewBuffer(b) + nChunksI := numChunks(zBytes) + if nChunksI > 128 { + return fmt.Errorf("msg too large, would need %d chunks", nChunksI) + } + nChunks := uint8(nChunksI) + // use urandom to get a unique message id + msgId := make([]byte, 8) + n, err := io.ReadFull(rand.Reader, msgId) + if err != nil || n != 8 { + return fmt.Errorf("rand.Reader: %d/%s", n, err) + } + + bytesLeft := len(zBytes) + for i := uint8(0); i < nChunks; i++ { + buf.Reset() + // manually write header. Don't care about + // host/network byte order, because the spec only + // deals in individual bytes. + buf.Write(magicChunked) //magic + buf.Write(msgId) + buf.WriteByte(i) + buf.WriteByte(nChunks) + // slice out our chunk from zBytes + chunkLen := chunkedDataLen + if chunkLen > bytesLeft { + chunkLen = bytesLeft + } + off := int(i) * chunkedDataLen + chunk := zBytes[off : off+chunkLen] + buf.Write(chunk) + + // write this chunk, and make sure the write was good + n, err := w.conn.Write(buf.Bytes()) + if err != nil { + return fmt.Errorf("Write (chunk %d/%d): %s", i, + nChunks, err) + } + if n != len(buf.Bytes()) { + return fmt.Errorf("Write len: (chunk %d/%d) (%d/%d)", + i, nChunks, n, len(buf.Bytes())) + } + + bytesLeft -= chunkLen + } + + if bytesLeft != 0 { + return fmt.Errorf("error: %d bytes left after sending", bytesLeft) + } + return nil +} + +// 1k bytes buffer by default +var bufPool = sync.Pool{ + New: func() interface{} { + return bytes.NewBuffer(make([]byte, 0, 1024)) + }, +} + +func newBuffer() *bytes.Buffer { + b := bufPool.Get().(*bytes.Buffer) + if b != nil { + b.Reset() + return b + } + return bytes.NewBuffer(nil) +} + +// WriteMessage sends the specified message to the GELF server +// specified in the call to New(). It assumes all the fields are +// filled out appropriately. In general, clients will want to use +// Write, rather than WriteMessage. +func (w *UDPWriter) WriteMessage(m *Message) (err error) { + mBuf := newBuffer() + defer bufPool.Put(mBuf) + if err = m.MarshalJSONBuf(mBuf); err != nil { + return err + } + mBytes := mBuf.Bytes() + + var ( + zBuf *bytes.Buffer + zBytes []byte + ) + + var zw io.WriteCloser + switch w.CompressionType { + case CompressGzip: + zBuf = newBuffer() + defer bufPool.Put(zBuf) + zw, err = gzip.NewWriterLevel(zBuf, w.CompressionLevel) + case CompressZlib: + zBuf = newBuffer() + defer bufPool.Put(zBuf) + zw, err = zlib.NewWriterLevel(zBuf, w.CompressionLevel) + case CompressNone: + zBytes = mBytes + default: + panic(fmt.Sprintf("unknown compression type %d", + w.CompressionType)) + } + if zw != nil { + if err != nil { + return + } + if _, err = zw.Write(mBytes); err != nil { + zw.Close() + return + } + zw.Close() + zBytes = zBuf.Bytes() + } + + if numChunks(zBytes) > 1 { + return w.writeChunked(zBytes) + } + n, err := w.conn.Write(zBytes) + if err != nil { + return + } + if n != len(zBytes) { + return fmt.Errorf("bad write (%d/%d)", n, len(zBytes)) + } + + return nil +} + +// Write encodes the given string in a GELF message and sends it to +// the server specified in New(). +func (w *UDPWriter) Write(p []byte) (n int, err error) { + // 1 for the function that called us. + file, line := getCallerIgnoringLogMulti(1) + + m := constructMessage(p, w.hostname, w.Facility, file, line) + + if err = w.WriteMessage(m); err != nil { + return 0, err + } + + return len(p), nil +} diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/utils.go b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/utils.go new file mode 100644 index 0000000..6f1c9f7 --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/utils.go @@ -0,0 +1,41 @@ +package gelf + +import ( + "runtime" + "strings" +) + +// getCaller returns the filename and the line info of a function +// further down in the call stack. Passing 0 in as callDepth would +// return info on the function calling getCallerIgnoringLog, 1 the +// parent function, and so on. Any suffixes passed to getCaller are +// path fragments like "/pkg/log/log.go", and functions in the call +// stack from that file are ignored. +func getCaller(callDepth int, suffixesToIgnore ...string) (file string, line int) { + // bump by 1 to ignore the getCaller (this) stackframe + callDepth++ +outer: + for { + var ok bool + _, file, line, ok = runtime.Caller(callDepth) + if !ok { + file = "???" + line = 0 + break + } + + for _, s := range suffixesToIgnore { + if strings.HasSuffix(file, s) { + callDepth++ + continue outer + } + } + break + } + return +} + +func getCallerIgnoringLogMulti(callDepth int) (string, int) { + // the +1 is to ignore this (getCallerIgnoringLogMulti) frame + return getCaller(callDepth+1, "/pkg/log/log.go", "/pkg/io/multi.go") +} diff --git a/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/writer.go b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/writer.go new file mode 100644 index 0000000..153be2c --- /dev/null +++ b/vendor/gopkg.in/Graylog2/go-gelf.v2/gelf/writer.go @@ -0,0 +1,34 @@ +// Copyright 2012 SocialCode. All rights reserved. +// Use of this source code is governed by the MIT +// license that can be found in the LICENSE file. + +package gelf + +import ( + "net" +) + +type Writer interface { + Close() error + Write([]byte) (int, error) + WriteMessage(*Message) error +} + +// Writer implements io.Writer and is used to send both discrete +// messages to a graylog2 server, or data from a stream-oriented +// interface (like the functions in log). +type GelfWriter struct { + addr string + conn net.Conn + hostname string + Facility string // defaults to current process name + proto string +} + +// Close connection and interrupt blocked Read or Write operations +func (w *GelfWriter) Close() error { + if w.conn == nil { + return nil + } + return w.conn.Close() +} diff --git a/vendor/modules.txt b/vendor/modules.txt new file mode 100644 index 0000000..97af476 --- /dev/null +++ b/vendor/modules.txt @@ -0,0 +1,8 @@ +# github.com/Graylog2/go-gelf v0.0.0-20170811154226-7ebf4f536d8f +## explicit +# github.com/kjk/betterguid v0.0.0-20170621091430-c442874ba63a +## explicit +github.com/kjk/betterguid +# gopkg.in/Graylog2/go-gelf.v2 v2.0.0-20191017102106-1550ee647df0 +## explicit +gopkg.in/Graylog2/go-gelf.v2/gelf