From 2edcd3a913508e2d922776f729bfc4bcab031a8b Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Tue, 4 May 2021 18:00:39 +0300 Subject: [PATCH] feat: add initial version Code was copied from github.com/talos-systems/talos/internal/pkg/kmsg. Signed-off-by: Andrey Smirnov --- .codecov.yml | 18 ++ .conform.yaml | 34 +++ .dockerignore | 18 ++ .drone.yml | 194 ++++++++++++++++ .gitignore | 5 + .golangci.yml | 150 +++++++++++++ .markdownlint.json | 9 + Dockerfile | 77 +++++++ LICENSE | 373 +++++++++++++++++++++++++++++++ Makefile | 133 +++++++++++ go.mod | 8 + go.sum | 13 ++ hack/git-chglog/CHANGELOG.tpl.md | 26 +++ hack/git-chglog/config.yaml | 32 +++ hack/release.sh | 60 +++++ kmsg.go | 47 ++++ message.go | 120 ++++++++++ message_test.go | 60 +++++ reader.go | 200 +++++++++++++++++ reader_test.go | 109 +++++++++ utils.go | 23 ++ writer.go | 53 +++++ writer_test.go | 58 +++++ 23 files changed, 1820 insertions(+) create mode 100644 .codecov.yml create mode 100644 .conform.yaml create mode 100644 .dockerignore create mode 100644 .drone.yml create mode 100644 .gitignore create mode 100644 .golangci.yml create mode 100644 .markdownlint.json create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 go.mod create mode 100644 go.sum create mode 100644 hack/git-chglog/CHANGELOG.tpl.md create mode 100644 hack/git-chglog/config.yaml create mode 100755 hack/release.sh create mode 100644 kmsg.go create mode 100644 message.go create mode 100644 message_test.go create mode 100644 reader.go create mode 100644 reader_test.go create mode 100644 utils.go create mode 100644 writer.go create mode 100644 writer_test.go diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 0000000..647b731 --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,18 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:49:49Z by kres 1844a99-dirty. + +codecov: +require_ci_to_pass: false + +coverage: +status: + project: + default: + target: 50% + threshold: 0.5% + base: auto + if_ci_failed: success + patch: off + +comment: false diff --git a/.conform.yaml b/.conform.yaml new file mode 100644 index 0000000..e89abc7 --- /dev/null +++ b/.conform.yaml @@ -0,0 +1,34 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:49:49Z by kres 1844a99-dirty. + +policies: +- type: commit + spec: + dco: true + gpg: false + spellcheck: + locale: US + maximumOfOneCommit: true + header: + length: 89 + imperative: true + case: lower + invalidLastCharacters: . + body: + required: true + conventional: + types: ["chore","docs","perf","refactor","style","test","release"] + scopes: ["*"] +- type: license + spec: + skipPaths: + - .git/ + includeSuffixes: + - .go + excludeSuffixes: + - .pb.go + header: | + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this + // file, You can obtain one at http://mozilla.org/MPL/2.0/. diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ef2313e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,18 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:58:40Z by kres 1844a99-dirty. + +** +!kmsg.go +!message.go +!message_test.go +!reader.go +!reader_test.go +!utils.go +!writer.go +!writer_test.go +!go.mod +!go.sum +!.golangci.yml +!README.md +!.markdownlint.json diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..4d194b0 --- /dev/null +++ b/.drone.yml @@ -0,0 +1,194 @@ +--- +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:49:49Z by kres 1844a99-dirty. + +kind: pipeline +type: kubernetes +name: default + +platform: + os: linux + arch: amd64 + +steps: +- name: setup-ci + pull: always + image: autonomy/build-container:latest + commands: + - sleep 5 + - git fetch --tags + - install-ci-key + - docker buildx create --driver docker-container --platform linux/amd64 --name local --use unix:///var/outer-run/docker.sock + - docker buildx inspect --bootstrap + environment: + SSH_KEY: + from_secret: ssh_key + volumes: + - name: outer-docker-socket + path: /var/outer-run + - name: docker-socket + path: /var/run + - name: buildx + path: /root/.docker/buildx + - name: ssh + path: /root/.ssh + +- name: base + pull: always + image: autonomy/build-container:latest + commands: + - make base + volumes: + - name: outer-docker-socket + path: /var/outer-run + - name: docker-socket + path: /var/run + - name: buildx + path: /root/.docker/buildx + - name: ssh + path: /root/.ssh + depends_on: + - setup-ci + +- name: unit-tests + pull: always + image: autonomy/build-container:latest + commands: + - make unit-tests + volumes: + - name: outer-docker-socket + path: /var/outer-run + - name: docker-socket + path: /var/run + - name: buildx + path: /root/.docker/buildx + - name: ssh + path: /root/.ssh + depends_on: + - base + +- name: unit-tests-race + pull: always + image: autonomy/build-container:latest + commands: + - make unit-tests-race + volumes: + - name: outer-docker-socket + path: /var/outer-run + - name: docker-socket + path: /var/run + - name: buildx + path: /root/.docker/buildx + - name: ssh + path: /root/.ssh + depends_on: + - base + +- name: coverage + pull: always + image: autonomy/build-container:latest + commands: + - make coverage + environment: + CODECOV_TOKEN: + from_secret: CODECOV_TOKEN + volumes: + - name: outer-docker-socket + path: /var/outer-run + - name: docker-socket + path: /var/run + - name: buildx + path: /root/.docker/buildx + - name: ssh + path: /root/.ssh + depends_on: + - unit-tests + +- name: lint + pull: always + image: autonomy/build-container:latest + commands: + - make lint + volumes: + - name: outer-docker-socket + path: /var/outer-run + - name: docker-socket + path: /var/run + - name: buildx + path: /root/.docker/buildx + - name: ssh + path: /root/.ssh + depends_on: + - base + +services: +- name: docker + image: docker:19.03-dind + entrypoint: + - dockerd + commands: + - --dns=8.8.8.8 + - --dns=8.8.4.4 + - --mtu=1500 + - --log-level=error + privileged: true + volumes: + - name: outer-docker-socket + path: /var/outer-run + - name: docker-socket + path: /var/run + - name: buildx + path: /root/.docker/buildx + - name: ssh + path: /root/.ssh + +volumes: +- name: outer-docker-socket + host: + path: /var/ci-docker +- name: docker-socket + temp: + medium: memory +- name: buildx + temp: + medium: memory +- name: ssh + temp: + medium: memory + +--- +kind: pipeline +type: kubernetes +name: notify + +platform: + os: linux + arch: amd64 + +clone: + disable: true + +steps: +- name: slack + image: plugins/slack + settings: + channel: proj-talos-maintainers + link_names: true + template: "{{#if build.pull }}\n*{{#success build.status}}✓ Success{{else}}✕ Fail{{/success}}*: {{ repo.owner }}/{{ repo.name }} - \n{{else}}\n*{{#success build.status}}✓ Success{{else}}✕ Fail{{/success}}: {{ repo.owner }}/{{ repo.name }} - Build #{{ build.number }}* (type: `{{ build.event }}`)\n{{/if}}\nCommit: \nBranch: \nAuthor: {{ build.author }}\n<{{ build.link }}|Visit build page>" + webhook: + from_secret: slack_webhook + when: + status: + - success + - failure + +trigger: + status: + - success + - failure + +depends_on: +- default + +... diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c8b2dd --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:49:49Z by kres 1844a99-dirty. + +_out diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..8585c22 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,150 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:49:49Z by kres 1844a99-dirty. + + +# options for analysis running +run: + timeout: 10m + issues-exit-code: 1 + tests: true + build-tags: [] + skip-dirs: [] + skip-dirs-use-default: true + skip-files: [] + modules-download-mode: readonly + +# output configuration options +output: + format: colored-line-number + print-issued-lines: true + print-linter-name: true + uniq-by-line: true + path-prefix: "" + + +# all available settings of specific linters +linters-settings: + dogsled: + max-blank-identifiers: 2 + dupl: + threshold: 150 + errcheck: + check-type-assertions: true + check-blank: true + exhaustive: + default-signifies-exhaustive: false + funlen: + lines: 60 + statements: 40 + gci: + local-prefixes: github.com/talos-systems/go-kmsg + gocognit: + min-complexity: 30 + nestif: + min-complexity: 5 + goconst: + min-len: 3 + min-occurrences: 3 + gocritic: + disabled-checks: [] + gocyclo: + min-complexity: 20 + godot: + check-all: false + godox: + keywords: # default keywords are TODO, BUG, and FIXME, these can be overwritten by this setting + - NOTE + - OPTIMIZE # marks code that should be optimized before merging + - HACK # marks hack-arounds that should be removed before merging + gofmt: + simplify: true + goimports: + local-prefixes: github.com/talos-systems/go-kmsg + golint: + min-confidence: 0.8 + gomnd: + settings: {} + gomodguard: {} + govet: + check-shadowing: true + enable-all: true + depguard: + list-type: blacklist + include-go-root: false + lll: + line-length: 200 + tab-width: 4 + misspell: + locale: US + ignore-words: [] + nakedret: + max-func-lines: 30 + prealloc: + simple: true + range-loops: true # Report preallocation suggestions on range loops, true by default + for-loops: false # Report preallocation suggestions on for loops, false by default + nolintlint: + allow-unused: false + allow-leading-space: false + allow-no-explanation: [] + require-explanation: false + require-specific: true + rowserrcheck: {} + testpackage: + unparam: + check-exported: false + unused: + check-exported: false + whitespace: + multi-if: false # Enforces newlines (or comments) after every multi-line if statement + multi-func: false # Enforces newlines (or comments) after every multi-line function signature + wsl: + strict-append: true + allow-assign-and-call: true + allow-multiline-assign: true + allow-cuddle-declarations: false + allow-trailing-comment: false + force-case-trailing-whitespace: 0 + force-err-cuddling: false + allow-separated-leading-comment: false + gofumpt: + extra-rules: false + cyclop: + # the maximal code complexity to report + max-complexity: 20 + +linters: + enable-all: true + disable: + - gas + - typecheck + - gochecknoglobals + - gochecknoinits + - funlen + - godox + - gomnd + - goerr113 + - nestif + - wrapcheck + - paralleltest + - exhaustivestruct + - forbidigo + disable-all: false + fast: false + + +issues: + exclude: [] + exclude-rules: [] + exclude-use-default: false + exclude-case-sensitive: false + max-issues-per-linter: 10 + max-same-issues: 3 + + new: false + +severity: + default-severity: error + + case-sensitive: false diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 0000000..363aad8 --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,9 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:58:40Z by kres 1844a99-dirty. + +{ + "MD013": false, + "MD033": false, + "default": true + } diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..59d36a3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,77 @@ +# syntax = docker/dockerfile-upstream:1.2.0-labs + +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:58:40Z by kres 1844a99-dirty. + +ARG TOOLCHAIN + +# cleaned up specs and compiled versions +FROM scratch AS generate + +# runs markdownlint +FROM node:14.8.0-alpine AS lint-markdown +RUN npm i -g markdownlint-cli@0.23.2 +RUN npm i sentences-per-line@0.2.1 +WORKDIR /src +COPY .markdownlint.json . +COPY ./README.md ./README.md +RUN markdownlint --ignore "**/node_modules/**" --ignore '**/hack/chglog/**' --rules /node_modules/sentences-per-line/index.js . + +# base toolchain image +FROM ${TOOLCHAIN} AS toolchain +RUN apk --update --no-cache add bash curl build-base protoc protobuf-dev + +# build tools +FROM toolchain AS tools +ENV GO111MODULE on +ENV CGO_ENABLED 0 +ENV GOPATH /go +RUN curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b /bin v1.38.0 +ARG GOFUMPT_VERSION +RUN cd $(mktemp -d) \ + && go mod init tmp \ + && go get mvdan.cc/gofumpt/gofumports@${GOFUMPT_VERSION} \ + && mv /go/bin/gofumports /bin/gofumports + +# tools and sources +FROM tools AS base +WORKDIR /src +COPY ./go.mod . +COPY ./go.sum . +RUN --mount=type=cache,target=/go/pkg go mod download +RUN --mount=type=cache,target=/go/pkg go mod verify +COPY ./kmsg.go ./kmsg.go +COPY ./message.go ./message.go +COPY ./message_test.go ./message_test.go +COPY ./reader.go ./reader.go +COPY ./reader_test.go ./reader_test.go +COPY ./utils.go ./utils.go +COPY ./writer.go ./writer.go +COPY ./writer_test.go ./writer_test.go +RUN --mount=type=cache,target=/go/pkg go list -mod=readonly all >/dev/null + +# runs gofumpt +FROM base AS lint-gofumpt +RUN find . -name '*.pb.go' | xargs -r rm +RUN FILES="$(gofumports -l -local github.com/talos-systems/go-kmsg .)" && test -z "${FILES}" || (echo -e "Source code is not formatted with 'gofumports -w -local github.com/talos-systems/go-kmsg .':\n${FILES}"; exit 1) + +# runs golangci-lint +FROM base AS lint-golangci-lint +COPY .golangci.yml . +ENV GOGC 50 +RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/root/.cache/golangci-lint --mount=type=cache,target=/go/pkg golangci-lint run --config .golangci.yml + +# runs unit-tests with race detector +FROM base AS unit-tests-race +ARG TESTPKGS +RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/go/pkg --mount=type=cache,target=/tmp CGO_ENABLED=1 go test -v -race -count 1 ${TESTPKGS} + +# runs unit-tests +FROM base AS unit-tests-run +ARG TESTPKGS +RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/go/pkg --mount=type=cache,target=/tmp go test -v -covermode=atomic -coverprofile=coverage.txt -coverpkg=${TESTPKGS} -count 1 ${TESTPKGS} + +FROM scratch AS unit-tests +COPY --from=unit-tests-run /src/coverage.txt /coverage.txt + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4eb64b3 --- /dev/null +++ b/Makefile @@ -0,0 +1,133 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:58:40Z by kres 1844a99-dirty. + +# common variables + +SHA := $(shell git describe --match=none --always --abbrev=8 --dirty) +TAG := $(shell git describe --tag --always --dirty) +BRANCH := $(shell git rev-parse --abbrev-ref HEAD) +ARTIFACTS := _out +REGISTRY ?= ghcr.io +USERNAME ?= talos-systems +REGISTRY_AND_USERNAME ?= $(REGISTRY)/$(USERNAME) +GOFUMPT_VERSION ?= abc0db2c416aca0f60ea33c23c76665f6e7ba0b6 +GO_VERSION ?= 1.14 +PROTOBUF_GO_VERSION ?= 1.25.0 +GRPC_GO_VERSION ?= 1.1.0 +TESTPKGS ?= ./... +KRES_IMAGE ?= ghcr.io/talos-systems/kres:latest + +# docker build settings + +BUILD := docker buildx build +PLATFORM ?= linux/amd64 +PROGRESS ?= auto +PUSH ?= false +CI_ARGS ?= +COMMON_ARGS = --file=Dockerfile +COMMON_ARGS += --progress=$(PROGRESS) +COMMON_ARGS += --platform=$(PLATFORM) +COMMON_ARGS += --push=$(PUSH) +COMMON_ARGS += --build-arg=ARTIFACTS=$(ARTIFACTS) +COMMON_ARGS += --build-arg=SHA=$(SHA) +COMMON_ARGS += --build-arg=TAG=$(TAG) +COMMON_ARGS += --build-arg=USERNAME=$(USERNAME) +COMMON_ARGS += --build-arg=TOOLCHAIN=$(TOOLCHAIN) +COMMON_ARGS += --build-arg=GOFUMPT_VERSION=$(GOFUMPT_VERSION) +COMMON_ARGS += --build-arg=PROTOBUF_GO_VERSION=$(PROTOBUF_GO_VERSION) +COMMON_ARGS += --build-arg=GRPC_GO_VERSION=$(GRPC_GO_VERSION) +COMMON_ARGS += --build-arg=TESTPKGS=$(TESTPKGS) +TOOLCHAIN ?= docker.io/golang:1.16-alpine + +# help menu + +export define HELP_MENU_HEADER +# Getting Started + +To build this project, you must have the following installed: + +- git +- make +- docker (19.03 or higher) + +## Creating a Builder Instance + +The build process makes use of experimental Docker features (buildx). +To enable experimental features, add 'experimental: "true"' to '/etc/docker/daemon.json' on +Linux or enable experimental features in Docker GUI for Windows or Mac. + +To create a builder instance, run: + + docker buildx create --name local --use + + +If you already have a compatible builder instance, you may use that instead. + +## Artifacts + +All artifacts will be output to ./$(ARTIFACTS). Images will be tagged with the +registry "$(REGISTRY)", username "$(USERNAME)", and a dynamic tag (e.g. $(IMAGE):$(TAG)). +The registry and username can be overridden by exporting REGISTRY, and USERNAME +respectively. + +endef + +all: unit-tests lint + +.PHONY: clean +clean: ## Cleans up all artifacts. + @rm -rf $(ARTIFACTS) + +target-%: ## Builds the specified target defined in the Dockerfile. The build result will only remain in the build cache. + @$(BUILD) --target=$* $(COMMON_ARGS) $(TARGET_ARGS) $(CI_ARGS) . + +local-%: ## Builds the specified target defined in the Dockerfile using the local output type. The build result will be output to the specified local destination. + @$(MAKE) target-$* TARGET_ARGS="--output=type=local,dest=$(DEST) $(TARGET_ARGS)" + +lint-golangci-lint: ## Runs golangci-lint linter. + @$(MAKE) target-$@ + +lint-gofumpt: ## Runs gofumpt linter. + @$(MAKE) target-$@ + +.PHONY: fmt +fmt: ## Formats the source code + @docker run --rm -it -v $(PWD):/src -w /src golang:$(GO_VERSION) \ + bash -c "export GO111MODULE=on; export GOPROXY=https://proxy.golang.org; \ + cd /tmp && go mod init tmp && go get mvdan.cc/gofumpt/gofumports@$(GOFUMPT_VERSION) && \ + cd - && gofumports -w -local github.com/talos-systems/go-kmsg ." + +.PHONY: base +base: ## Prepare base toolchain + @$(MAKE) target-$@ + +.PHONY: unit-tests +unit-tests: ## Performs unit tests + @$(MAKE) local-$@ DEST=$(ARTIFACTS) + +.PHONY: unit-tests-race +unit-tests-race: ## Performs unit tests with race detection enabled. + @$(MAKE) target-$@ + +.PHONY: coverage +coverage: ## Upload coverage data to codecov.io. + bash -c "bash <(curl -s https://codecov.io/bash) -f $(ARTIFACTS)/coverage.txt -X fix" + +.PHONY: lint-markdown +lint-markdown: ## Runs markdownlint. + @$(MAKE) target-$@ + +.PHONY: lint +lint: lint-golangci-lint lint-gofumpt lint-markdown ## Run all linters for the project. + +.PHONY: rekres +rekres: + @docker pull $(KRES_IMAGE) + @docker run --rm -v $(PWD):/src -w /src -e GITHUB_TOKEN $(KRES_IMAGE) + +.PHONY: help +help: ## This help menu. + @echo "$$HELP_MENU_HEADER" + @grep -E '^[a-zA-Z%_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' + diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4643e5b --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module github.com/talos-systems/go-kmsg + +go 1.16 + +require ( + github.com/stretchr/testify v1.7.0 + golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..abd10f5 --- /dev/null +++ b/go.sum @@ -0,0 +1,13 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6 h1:cdsMqa2nXzqlgs183pHxtvoVwU7CyzaCTAUOg94af4c= +golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/hack/git-chglog/CHANGELOG.tpl.md b/hack/git-chglog/CHANGELOG.tpl.md new file mode 100644 index 0000000..8201507 --- /dev/null +++ b/hack/git-chglog/CHANGELOG.tpl.md @@ -0,0 +1,26 @@ + + + + +{{ range .Versions }} + +## {{ if .Tag.Previous }}[{{ .Tag.Name }}]({{ $.Info.RepositoryURL }}/compare/{{ .Tag.Previous.Name }}...{{ .Tag.Name }}){{ else }}{{ .Tag.Name }}{{ end }} ({{ datetime "2006-01-02" .Tag.Date }}) + +{{ range .CommitGroups -}} +### {{ .Title }} + +{{ range .Commits -}} +* {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }} +{{ end }} +{{ end -}} + +{{- if .NoteGroups -}} +{{ range .NoteGroups -}} +### {{ .Title }} + +{{ range .Notes }} +{{ .Body }} +{{ end }} +{{ end -}} +{{ end -}} +{{ end -}} diff --git a/hack/git-chglog/config.yaml b/hack/git-chglog/config.yaml new file mode 100644 index 0000000..455b397 --- /dev/null +++ b/hack/git-chglog/config.yaml @@ -0,0 +1,32 @@ +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:49:49Z by kres 1844a99-dirty. + +style: github +template: CHANGELOG.tpl.md +info: + title: CHANGELOG + repository_url: https://github.com/talos-systems/go-kmsg +options: + commits: + # filters: + # Type: + # - feat + # - fix + # - perf + # - refactor + commit_groups: + # title_maps: + # feat: Features + # fix: Bug Fixes + # perf: Performance Improvements + # refactor: Code Refactoring + header: + pattern: "^(\\w*)(?:\\(([\\w\\$\\.\\-\\*\\s]*)\\))?\\:\\s(.*)$" + pattern_maps: + - Type + - Scope + - Subject + notes: + keywords: + - BREAKING CHANGE diff --git a/hack/release.sh b/hack/release.sh new file mode 100755 index 0000000..6943be5 --- /dev/null +++ b/hack/release.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +# THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. +# +# Generated on 2021-05-04T14:49:49Z by kres 1844a99-dirty. + + +set -e + +function changelog { + if [ "$#" -eq 1 ]; then + git-chglog --output CHANGELOG.md -c ./hack/git-chglog/config.yaml --tag-filter-pattern "^${1}" "${1}.0-alpha.0.." + elif [ "$#" -eq 0 ]; then + git-chglog --output CHANGELOG.md -c ./hack/git-chglog/config.yaml + else + echo 1>&2 "Usage: $0 changelog [tag]" + exit 1 + fi +} + +function release-notes { + git-chglog --output ${1} -c ./hack/git-chglog/config.yaml "${2}" +} + +function cherry-pick { + if [ $# -ne 2 ]; then + echo 1>&2 "Usage: $0 cherry-pick " + exit 1 + fi + + git checkout $2 + git fetch + git rebase upstream/$2 + git cherry-pick -x $1 +} + +function commit { + if [ $# -ne 1 ]; then + echo 1>&2 "Usage: $0 commit " + exit 1 + fi + + git commit -s -m "release($1): prepare release" -m "This is the official $1 release." +} + +if declare -f "$1" > /dev/null +then + cmd="$1" + shift + $cmd "$@" +else + cat <. +const ( + Kern Facility = iota + User + Mail + Daemon + Auth + Syslog + Lpr + News + Uucp + Cron + AuthPriv + Local0 + Local1 + Local2 + Local3 + Local4 + Local5 + Local6 + Local7 +) + +func (f Facility) String() string { + return [...]string{ + "kern", "user", "mail", "daemon", + "auth", "syslog", "lpr", "news", "uucp", + "cron", "authpriv", + "local0", "local1", "local2", "local3", + "local4", "local5", "local6", "local7", + }[f] +} + +// Priority is an attribute of kernel log message. +type Priority int + +// Kernel log priorities. +const ( + Emerg Priority = iota + Alert + Crit + Err + Warning + Notice + Info + Debug +) + +func (p Priority) String() string { + return [...]string{"emerg", "alert", "crit", "err", "warning", "notice", "info", "debug"}[p] +} + +// Message is a parsed kernel log message. +type Message struct { + Timestamp time.Time + Message string + Facility Facility + Priority Priority + SequenceNumber int64 + Clock int64 +} + +// ParseMessage parses internal kernel log format. +// +// Reference: https://www.kernel.org/doc/Documentation/ABI/testing/dev-kmsg +func ParseMessage(input string, bootTime time.Time) (Message, error) { + parts := strings.SplitN(input, ";", 2) + if len(parts) != 2 { + return Message{}, fmt.Errorf("kernel message should contain a prefix") + } + + prefix, message := parts[0], parts[1] + + metadata := strings.Split(prefix, ",") + if len(metadata) < 3 { + return Message{}, fmt.Errorf("message metdata should have at least 3 parts, got %d", len(metadata)) + } + + syslogPrefix, err := strconv.ParseInt(metadata[0], 10, 64) + if err != nil { + return Message{}, fmt.Errorf("error parsing priority: %w", err) + } + + sequence, err := strconv.ParseInt(metadata[1], 10, 64) + if err != nil { + return Message{}, fmt.Errorf("error parsing sequence: %w", err) + } + + clock, err := strconv.ParseInt(metadata[2], 10, 64) + if err != nil { + return Message{}, fmt.Errorf("errors parsing clock from boot: %w", err) + } + + return Message{ + Priority: Priority(syslogPrefix & 7), + Facility: Facility(syslogPrefix >> 3), + SequenceNumber: sequence, + Clock: clock, + Timestamp: bootTime.Add(time.Duration(clock) * time.Microsecond), + Message: message, + }, nil +} diff --git a/message_test.go b/message_test.go new file mode 100644 index 0000000..ae46e1b --- /dev/null +++ b/message_test.go @@ -0,0 +1,60 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package kmsg_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/talos-systems/go-kmsg" +) + +func mustParse(tStr string) time.Time { + t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", tStr) + if err != nil { + panic(err) + } + + return t +} + +func TestParseMessage(t *testing.T) { + for _, testCase := range []struct { + input string + expected kmsg.Message + }{ + { + input: `7,160,424069,-;pci_root PNP0A03:00: host bridge window [io 0x0000-0x0cf7] (ignored) + SUBSYSTEM=acpi + DEVICE=+acpi:PNP0A03:00`, + expected: kmsg.Message{ + Facility: kmsg.Kern, + Priority: kmsg.Debug, + SequenceNumber: 160, + Clock: 424069, + Timestamp: mustParse("0001-01-01 00:00:00.424069 +0000 UTC"), + Message: "pci_root PNP0A03:00: host bridge window [io 0x0000-0x0cf7] (ignored)\n SUBSYSTEM=acpi\n DEVICE=+acpi:PNP0A03:00", + }, + }, + { + input: `6,339,5140900,-;NET: Registered protocol family 10`, + expected: kmsg.Message{ + Facility: kmsg.Kern, + Priority: kmsg.Info, + SequenceNumber: 339, + Clock: 5140900, + Timestamp: mustParse("0001-01-01 00:00:05.1409 +0000 UTC"), + Message: "NET: Registered protocol family 10", + }, + }, + } { + message, err := kmsg.ParseMessage(testCase.input, time.Time{}) + assert.NoError(t, err) + + assert.Equal(t, testCase.expected, message) + } +} diff --git a/reader.go b/reader.go new file mode 100644 index 0000000..5d27418 --- /dev/null +++ b/reader.go @@ -0,0 +1,200 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package kmsg + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "syscall" + "time" +) + +// Packet combines Message and error. +// +// Only one of the fields is set in Reader.Scan. +type Packet struct { + Err error + Message Message +} + +// Reader for /dev/kmsg messages. +type Reader interface { + // Scan and issue parsed messages. + // + // Scan stops when context is canceled or when EOF is reached + // in NoFollow mode. + Scan(ctx context.Context) <-chan Packet + + // Close releases resources associated with the Reader. + Close() error +} + +// Option configures Reader. +type Option func(*options) + +type options struct { + follow bool + tail bool +} + +// Follow the kmsg to stream live messages. +func Follow() Option { + return func(o *options) { + o.follow = true + } +} + +// FromTail starts reading kmsg from the tail (after last message). +func FromTail() Option { + return func(o *options) { + o.tail = true + } +} + +// NewReader initializes new /dev/kmsg reader. +func NewReader(options ...Option) (Reader, error) { + r := &reader{} + + for _, o := range options { + o(&r.options) + } + + var err error + + r.bootTime, err = getBootTime() + if err != nil { + return nil, err + } + + r.f, err = os.OpenFile("/dev/kmsg", os.O_RDONLY, 0) + if err != nil { + return nil, err + } + + if r.options.tail { + _, err = r.f.Seek(0, os.SEEK_END) + if err != nil { + r.f.Close() //nolint:errcheck + + return nil, fmt.Errorf("error seeking to the tail of kmsg: %w", err) + } + } + + return r, nil +} + +type reader struct { + f *os.File + bootTime time.Time + options options +} + +func (r *reader) Close() error { + return r.f.Close() +} + +func (r *reader) Scan(ctx context.Context) <-chan Packet { + ch := make(chan Packet) + + if r.options.follow { + go r.scanFollow(ctx, ch) + } else { + go r.scanNoFollow(ctx, ch) + } + + return ch +} + +func (r *reader) scanNoFollow(ctx context.Context, ch chan<- Packet) { + defer close(ch) + + fd := int(r.f.Fd()) + + if err := syscall.SetNonblock(fd, true); err != nil { + select { + case ch <- Packet{ + Err: fmt.Errorf("error switching to nonblock mode: %w", err), + }: + case <-ctx.Done(): + } + + return + } + + buf := make([]byte, 8192) + + for { + n, err := syscall.Read(fd, buf) + if err != nil { + if errors.Is(err, io.EOF) || errors.Is(err, syscall.EAGAIN) { + // end of file, done + return + } + + if errors.Is(err, syscall.EPIPE) { + // buffer overrun, retry + continue + } + + select { + case ch <- Packet{ + Err: fmt.Errorf("error reading from kmsg: %w", err), + }: + case <-ctx.Done(): + } + + return + } + + var packet Packet + packet.Message, packet.Err = ParseMessage(string(buf[:n]), r.bootTime) + + select { + case ch <- packet: + case <-ctx.Done(): + } + } +} + +func (r *reader) scanFollow(ctx context.Context, ch chan<- Packet) { + defer close(ch) + + buf := make([]byte, 8192) + + for { + n, err := r.f.Read(buf) + if err != nil { + if errors.Is(err, io.EOF) { + // end of file, done + return + } + + if errors.Is(err, syscall.EPIPE) { + // buffer overrun, retry + continue + } + + select { + case ch <- Packet{ + Err: fmt.Errorf("error reading from kmsg: %w", err), + }: + case <-ctx.Done(): + } + + return + } + + var packet Packet + packet.Message, packet.Err = ParseMessage(string(buf[:n]), r.bootTime) + + select { + case ch <- packet: + case <-ctx.Done(): + } + } +} diff --git a/reader_test.go b/reader_test.go new file mode 100644 index 0000000..489850d --- /dev/null +++ b/reader_test.go @@ -0,0 +1,109 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package kmsg_test + +import ( + "context" + "errors" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/talos-systems/go-kmsg" +) + +//nolint:thelper +func skipIfNoKmsg(t *testing.T) { + f, err := os.OpenFile("/dev/kmsg", os.O_RDONLY, 0) + if err != nil { + t.Skip("/dev/kmsg is not available", err.Error()) + } + + f.Close() //nolint:errcheck +} + +func TestReaderNoFollow(t *testing.T) { + skipIfNoKmsg(t) + + r, err := kmsg.NewReader() + assert.NoError(t, err) + + defer r.Close() //nolint:errcheck + + messageCount := 0 + + for packet := range r.Scan(context.Background()) { + assert.NoError(t, packet.Err) + + messageCount++ + } + + assert.Greater(t, messageCount, 0) + + assert.NoError(t, r.Close()) +} + +func TestReaderFollow(t *testing.T) { + testReaderFollow(t, true) +} + +func TestReaderFollowTail(t *testing.T) { + testReaderFollow(t, false, kmsg.FromTail()) +} + +//nolint:thelper +func testReaderFollow(t *testing.T, expectMessages bool, options ...kmsg.Option) { + skipIfNoKmsg(t) + + r, err := kmsg.NewReader(append([]kmsg.Option{kmsg.Follow()}, options...)...) + assert.NoError(t, err) + + defer r.Close() //nolint:errcheck + + messageCount := 0 //nolint:ifshort + + ctx, ctxCancel := context.WithCancel(context.Background()) + defer ctxCancel() + + ch := r.Scan(ctx) + + var closed bool + +LOOP: + for { + select { + case packet, ok := <-ch: + if !ok { + if !closed { + assert.Fail(t, "channel closed before cancel") + } + + break LOOP + } + + if closed && errors.Is(packet.Err, os.ErrClosed) { + // ignore 'file already closed' error as it might happen + // from the branch below depending on whether context cancel or + // read() finishes first + continue + } + + assert.NoError(t, packet.Err) + + messageCount++ + case <-time.After(100 * time.Millisecond): + // abort + closed = true + ctxCancel() + assert.NoError(t, r.Close()) + } + } + + if expectMessages { + assert.Greater(t, messageCount, 0) + } +} diff --git a/utils.go b/utils.go new file mode 100644 index 0000000..8c1aa3a --- /dev/null +++ b/utils.go @@ -0,0 +1,23 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package kmsg + +import ( + "fmt" + "syscall" + "time" +) + +func getBootTime() (time.Time, error) { + var sysinfo syscall.Sysinfo_t + + err := syscall.Sysinfo(&sysinfo) + if err != nil { + return time.Time{}, fmt.Errorf("could not get boot time: %w", err) + } + + // sysinfo only has seconds + return time.Now().Add(-1 * (time.Duration(sysinfo.Uptime) * time.Second)), nil +} diff --git a/writer.go b/writer.go new file mode 100644 index 0000000..68ef1c1 --- /dev/null +++ b/writer.go @@ -0,0 +1,53 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package kmsg + +import ( + "bytes" + "io" +) + +// MaxLineLength to be passed to kmsg, see https://github.com/torvalds/linux/blob/master/kernel/printk/printk.c#L450. +const MaxLineLength = 1024 - 48 + +// Writer ensures writes by line and limits each line to maxLineLength characters. +// +// This workarounds kmsg limits. +type Writer struct { + KmsgWriter io.Writer +} + +// Write implements io.Writer interface. +func (w *Writer) Write(p []byte) (n int, err error) { + // split writes by `\n`, and limit each line to MaxLineLength + for len(p) > 0 { + i := bytes.IndexByte(p, '\n') + if i == -1 { + i = len(p) - 1 + } + + line := p[:i+1] + if len(line) > MaxLineLength { + line = append(line[:MaxLineLength-4], []byte("...\n")...) + } + + var nn int + nn, err = w.KmsgWriter.Write(line) + + if nn == len(line) { + n += i + 1 + } else { + n += nn + } + + if err != nil { + return + } + + p = p[i+1:] + } + + return +} diff --git a/writer_test.go b/writer_test.go new file mode 100644 index 0000000..e61b884 --- /dev/null +++ b/writer_test.go @@ -0,0 +1,58 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package kmsg_test + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/talos-systems/go-kmsg" +) + +type fakeWriter struct { + lines [][]byte +} + +func (w *fakeWriter) Write(p []byte) (n int, err error) { + w.lines = append(w.lines, append([]byte(nil), p...)) + + return len(p), nil +} + +func TestWriter(t *testing.T) { + fakeW := &fakeWriter{} + kmsgW := &kmsg.Writer{KmsgWriter: fakeW} + + n, err := kmsgW.Write([]byte("foo")) + assert.Equal(t, 3, n) + assert.NoError(t, err) + + n, err = kmsgW.Write([]byte("bar\n")) + assert.Equal(t, 4, n) + assert.NoError(t, err) + + n, err = kmsgW.Write([]byte("foo\nbar\n")) + assert.Equal(t, 8, n) + assert.NoError(t, err) + + n, err = kmsgW.Write(append(bytes.Repeat([]byte{0xce}, kmsg.MaxLineLength-1), '\n')) + assert.Equal(t, kmsg.MaxLineLength, n) + assert.NoError(t, err) + + n, err = kmsgW.Write(append(bytes.Repeat([]byte{0xce}, kmsg.MaxLineLength), '\n', 'a', 'b', '\n')) + assert.Equal(t, kmsg.MaxLineLength+4, n) + assert.NoError(t, err) + + assert.Len(t, fakeW.lines, 7) + assert.Equal(t, fakeW.lines[0], []byte("foo")) + assert.Equal(t, fakeW.lines[1], []byte("bar\n")) + assert.Equal(t, fakeW.lines[2], []byte("foo\n")) + assert.Equal(t, fakeW.lines[3], []byte("bar\n")) + assert.Equal(t, fakeW.lines[4], append(bytes.Repeat([]byte{0xce}, kmsg.MaxLineLength-1), '\n')) + assert.Equal(t, fakeW.lines[5], append(bytes.Repeat([]byte{0xce}, kmsg.MaxLineLength-4), '.', '.', '.', '\n')) + assert.Equal(t, fakeW.lines[6], []byte("ab\n")) +}