├── .github ├── dependabot.yml └── workflows │ ├── build-and-push.yml │ ├── checks.yml │ └── dependabot-reviewer.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── acceptance ├── config │ └── cortex.yaml ├── suite_test.go └── write_proxy_test.go ├── ci ├── cmd │ └── coverage │ │ └── main.go ├── go.mod └── go.sum ├── cmd └── influx2cortex │ └── main.go ├── go.mod ├── go.sum ├── pkg ├── README.md ├── influx │ ├── api.go │ ├── api_test.go │ ├── auth_test.go │ ├── errors.go │ ├── errors_test.go │ ├── mock_recorder_test.go │ ├── parser.go │ ├── parser_test.go │ ├── proxy.go │ ├── recorder.go │ └── recorder_test.go └── internalserver │ └── service.go └── scripts ├── build-local-images.sh ├── compile_commands.sh ├── generate-tags.sh └── genprotobuf.sh /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "gomod" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | open-pull-requests-limit: 10 8 | commit-message: 9 | prefix: "build(deps): " 10 | -------------------------------------------------------------------------------- /.github/workflows/build-and-push.yml: -------------------------------------------------------------------------------- 1 | name: "build-and-push" 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | permissions: 10 | contents: read 11 | id-token: write 12 | 13 | jobs: 14 | build-and-push: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout Code 18 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 19 | with: 20 | persist-credentials: false 21 | 22 | - name: Generate Tags 23 | run: | 24 | bash scripts/generate-tags.sh > .tag 25 | echo "DOCKER_TAG=$(cat .tag)" >> $GITHUB_ENV 26 | 27 | - name: Build And Push 28 | uses: grafana/shared-workflows/actions/push-to-gar-docker@fa48192dac470ae356b3f7007229f3ac28c48a25 # main 29 | with: 30 | # Don't push from forks 31 | push: ${{ github.ref_name == 'main' || github.event.pull_request.head.repo.full_name == github.repository }} 32 | # If we are building main, push to prod and add the 'latest' tag. 33 | tags: |- 34 | ${{ env.DOCKER_TAG }} 35 | type=raw,value=latest,enable=${{ github.ref_name == 'main' }} 36 | context: "." 37 | image_name: "influx2cortex" 38 | environment: "${{ github.ref_name == 'main' && 'prod' || 'dev' }}" 39 | -------------------------------------------------------------------------------- /.github/workflows/checks.yml: -------------------------------------------------------------------------------- 1 | name: "checks" 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | env: 10 | GO_VERSION: "1.23" 11 | 12 | permissions: {} 13 | 14 | jobs: 15 | # shellcheck should be a dependency for jobs that run any scripts, 16 | # as wrong shell scripts can be harmful. 17 | shellcheck: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 21 | with: 22 | persist-credentials: false 23 | - name: Run ShellCheck 24 | uses: ludeeus/action-shellcheck@00b27aa7cb85167568cb48a3838b75f4265f2bca # master 25 | with: 26 | severity: warning 27 | 28 | go-lint: 29 | permissions: 30 | contents: read # for actions/checkout to fetch code 31 | pull-requests: read # for golangci/golangci-lint-action to fetch pull requests 32 | runs-on: ubuntu-latest 33 | steps: 34 | - name: Checkout code 35 | uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 36 | with: 37 | persist-credentials: false 38 | - name: Install Go 39 | uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5 40 | with: 41 | go-version: ${{ env.GO_VERSION }} 42 | - name: golangci-lint 43 | uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7 44 | with: 45 | args: --verbose --timeout=3m 46 | version: v2.0.2 47 | 48 | go-mod-tidy: 49 | runs-on: ubuntu-latest 50 | steps: 51 | - name: Checkout code 52 | uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 53 | with: 54 | persist-credentials: false 55 | - name: Install Go 56 | uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5 57 | with: 58 | go-version: ${{ env.GO_VERSION }} 59 | - name: Check go mod tidy 60 | run: | 61 | go mod tidy 62 | make assert-no-changed-files 63 | 64 | test: 65 | runs-on: ubuntu-latest 66 | permissions: 67 | pull-requests: write 68 | steps: 69 | - name: Checkout code 70 | uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 71 | with: 72 | persist-credentials: false 73 | - name: Install Go 74 | uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5 75 | with: 76 | go-version: ${{ env.GO_VERSION }} 77 | - name: Run Tests 78 | run: go test -coverprofile coverage.out ./... 79 | - name: Save Coverage Report 80 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 81 | with: 82 | name: coverage-report 83 | path: coverage.out 84 | comment-coverage: 85 | runs-on: ubuntu-latest 86 | needs: test 87 | permissions: 88 | pull-requests: write 89 | steps: 90 | - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 91 | with: 92 | persist-credentials: false 93 | - uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5 94 | with: 95 | go-version: ${{ env.GO_VERSION }} 96 | - name: Download Coverage Report 97 | uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 98 | with: 99 | name: coverage-report 100 | - name: Generate Coverage Summary 101 | run: go run ci/cmd/coverage/main.go -f coverage.out > comment.txt 102 | - name: Comment Coverage Summary 103 | # This will update the comment in place on successive runs 104 | uses: mshick/add-pr-comment@b8f338c590a895d50bcbfa6c5859251edc8952fc # v2 105 | with: 106 | message-path: comment.txt 107 | acceptance: 108 | runs-on: ubuntu-latest 109 | steps: 110 | - name: Checkout code 111 | uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 112 | with: 113 | persist-credentials: false 114 | - name: Install Go 115 | uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5 116 | with: 117 | go-version: ${{ env.GO_VERSION }} 118 | - name: Build Local Images 119 | run: | 120 | make build-local 121 | - name: Run Acceptance Tests 122 | run: | 123 | make acceptance-tests 124 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-reviewer.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot reviewer 2 | on: pull_request 3 | permissions: 4 | pull-requests: write 5 | contents: write 6 | jobs: 7 | call-workflow-passing-data: 8 | uses: grafana/security-github-actions/.github/workflows/dependabot-automerge.yaml@main 9 | with: 10 | repository-merge-method: squash 11 | packages-minor-autoupdate: '["github.com/ahmetalpbalkan/dlog","github.com/colega/envconfig","github.com/go-kit/log","github.com/gorilla/mux","github.com/grafana/dskit","github.com/grafana/mimir","github.com/grafana/mimir-graphite","github.com/influxdata/influxdb-client-go/v2","github.com/influxdata/influxdb/v2","github.com/ory/dockertest/v3","github.com/pkg/errors","github.com/prometheus/client_golang","github.com/prometheus/common","github.com/prometheus/prometheus","github.com/stretchr/testify","github.com/weaveworks/common","google.golang.org/grpc"]' 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /influx2cortex 2 | jsonnet/influx2cortex/vendor 3 | .idea/ 4 | cmd/influx2cortex/influx2cortex 5 | vendor/ 6 | .tag 7 | .tags 8 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.24-alpine AS build 2 | RUN apk add --update --no-cache git coreutils 3 | 4 | WORKDIR /go/src/github.com/grafana/influx2cortex 5 | COPY . . 6 | 7 | RUN GIT_COMMIT="${DRONE_COMMIT:-${GITHUB_SHA:-$(git rev-list -1 HEAD)}}"; \ 8 | COMMIT_UNIX_TIMESTAMP="$(git --no-pager show -s --format=%ct "${GIT_COMMIT}")"; \ 9 | DOCKER_TAG="$(cat .tag)"; \ 10 | GOPRIVATE="github.com/grafana/*"; \ 11 | CGO_ENABLED=0; \ 12 | go build -o /bin/influx2cortex \ 13 | --ldflags " \ 14 | -w -extldflags \ 15 | '-static' \ 16 | -X 'github.com/grafana/influx2cortex/pkg/influx.CommitUnixTimestamp=${COMMIT_UNIX_TIMESTAMP}' \ 17 | -X 'github.com/grafana/influx2cortex/pkg/influx.DockerTag=${DOCKER_TAG}'\ 18 | " \ 19 | github.com/grafana/influx2cortex/cmd/influx2cortex 20 | 21 | 22 | RUN addgroup -g 1000 app && \ 23 | adduser -u 1000 -h /app -G app -S app 24 | 25 | FROM gcr.io/distroless/static-debian12 26 | 27 | COPY --from=build /etc/passwd /etc/passwd 28 | COPY --from=build /etc/group /etc/group 29 | 30 | WORKDIR /app 31 | USER app 32 | 33 | COPY --from=build /bin/influx2cortex /bin/influx2cortex 34 | ENTRYPOINT [ "/bin/influx2cortex" ] 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: help 2 | 3 | help: 4 | @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' 5 | 6 | build: ## Build local binaries 7 | bash ./scripts/compile_commands.sh 8 | 9 | build-local: ## Builds local versions of images 10 | bash ./scripts/build-local-images.sh 11 | 12 | acceptance-tests: ## Runs the acceptance tests, expecting the images to be already built 13 | go test -count 1 -v -race -tags=acceptance ./acceptance/... 14 | 15 | test: ## Run golang tests 16 | go test -race ./... 17 | 18 | coverage-output: 19 | go test ./... -coverprofile=cover.out 20 | 21 | coverage-show-func: 22 | go tool cover -func cover.out 23 | 24 | packages-minor-autoupdate: 25 | go mod edit -json \ 26 | | jq ".Require \ 27 | | map(select(.Indirect | not).Path) \ 28 | | map(select( \ 29 | . != \"github.com/thanos-io/thanos\" \ 30 | ))" \ 31 | | tr -d '\n' | tr -d ' ' 32 | 33 | .PHONY: assert-no-changed-files 34 | assert-no-changed-files: 35 | @git update-index --refresh 36 | @git diff-index --quiet HEAD -- -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Build And Push 2 | 3 | Go Report Card 4 | 5 | # influx2cortex: An Influx Proxy for Cortex 6 | 7 | influx2cortex is a proxy that accepts Influx Line protocol and writes it to Cortex. 8 | While today it only accepts writes, I have plans to add Flux read support too! 9 | 10 | ## Influx Line Protocol ingestion and translation 11 | 12 | The Influx write proxy accepts the ingest requests and then translates the incoming Influx metrics into Prometheus metrics. The name mapping scheme for the looks as follows: 13 | 14 | Influx metric: cpu_load_short,host=server01,region=us-west value=0.64 1658139550000000000 15 | 16 | Prometheus metric: cpu_load_short{__proxy_source__="influx",host="server01",region="us-west"} 17 | 18 | ## Building 19 | 20 | To build the proxy: 21 | 22 | ($ indicates the command line prompt) 23 | 24 | ``` 25 | $ go mod tidy 26 | $ make build 27 | $ make test 28 | ``` 29 | 30 | This should place a build of `influx2cortex` in the `dist` subdirectory. 31 | 32 | ## Running 33 | 34 | Here we show how to configure and run the Influx write proxy to talk to an existing Mimir installation running on port 9090 on localhost. If no existing Mimir installation is available, or you would like to quickly install a test installation then follow the [getting-started](https://grafana.com/docs/mimir/latest/operators-guide/getting-started/) instructions. 35 | 36 | ### Gathering required information 37 | 38 | In order to configure a write proxy we need to know the following pieces of information at a minimum: 39 | * The TCP port that the write proxy should listen on 40 | * The endpoint for remote writes within Mimir 41 | 42 | The default TCP port for the write proxy is 8000 however it is best to choose a unique non-default port, especially if you are going to be running multiple write proxies (Graphite, Datadog, Influx, etc) on the same host. 43 | 44 | If Mimir is configured to listen on port 9009 on localhost then the remote write endpoint will be http://localhost:9009/api/v1/push 45 | 46 | ### An example invocation 47 | 48 | (Pre-built binaries/docker images are on our list of things to do.) 49 | 50 | To run the proxy: 51 | 52 | ``` 53 | $ dist/influx2cortex \ 54 | -auth.enable=false \ 55 | -server.http-listen-address 127.0.0.1 \ 56 | -server.http-listen-port 8007 \ 57 | -write-endpoint http://localhost:9009/api/v1/push 58 | ``` 59 | 60 | Details of configurable options are available in the `-help` output. 61 | 62 | ### Example metric send 63 | 64 | ``` 65 | $ NOW=`date +%s000000000` ; curl -H "Content-Type: application/json" "http://localhost:8007/api/v1/push/influx/write" -d 'cpu_load_short,host=server01,region=us-west value=0.64 $NOW' 66 | ``` 67 | 68 | The data can now be queried from Mimir via the HTTP API or via Grafana. To find the above series via the HTTP API we can issue: 69 | 70 | ``` 71 | $ curl -G http://localhost:9009/prometheus/api/v1/series -d 'match[]=cpu_load_short' 72 | {"status":"success","data":[{"__name__":"cpu_load_short","__proxy_source__":"influx","host":"server01","region":"us-west"}]} 73 | ``` 74 | 75 | ## Grafana Cloud as a destination 76 | 77 | If the destination Mimir installation is part of a Grafana cloud instance the `-write-endpoint` argument should be of the form: 78 | `-write-endpoint https://_username_:_password_@_grafana_net_instance_/api/v1/push` 79 | where the exact server details can be found on Prometheus instance details page for the stack on grafana.com 80 | 81 | The `_username_` is the numeric `Username / Instance ID` 82 | The `_password_` is a Grafana Cloud API Key with the `MetricsPublisher` role. 83 | The `_grafana_net_instance_` is server part of the URL to push Prometheus metrics. 84 | 85 | ## Configuring telegraf 86 | 87 | Telegraf can be configured in two ways to send data to the Influx proxy. 88 | - Using the `http` plugin 89 | - Using the `influxdb` plugin 90 | 91 | If connecting to a local influx proxy running on `localhost:8000` the two configs would look something like this: 92 | 93 | ### outputs.influxdb 94 | 95 | Note: The url has a path of `/api/v1/push/influx`. The trailing `/write` is not required as this is appended by the `telegraf` agent when using the `outputs.influxdb` output plugin. 96 | 97 | ``` 98 | [[outputs.influxdb]] 99 | urls = ["https://localhost:8000/api/v1/push/influx"] 100 | data_format = "influx" 101 | skip_database_creation = true 102 | ``` 103 | 104 | The `skip_database_creation = true` option is to prevent errors such as: 105 | 106 | ``` 107 | 022-09-27T16:20:20Z W! [outputs.influxdb] When writing to [https://localhost:8000/api/v1/push/influx]: database "telegraf" creation failed: 500 Internal Server Error 108 | ``` 109 | 110 | ### outputs.http 111 | 112 | Note: The url has a path of `/api/v1/push/influx/write`. The trailing `/write` is required as the `outputs.http` output plugin uses the URL without modification (unlike the `outputs.influxdb` output plugin above). 113 | 114 | ``` 115 | [[outputs.http]] 116 | url = "http://localhost:8000/api/v1/push/influx/write" 117 | data_format = "influx" 118 | timeout = "10s" 119 | method = "POST" 120 | interval = "300s" 121 | flush_interval = "150s" 122 | ``` 123 | 124 | ## Configuring telegraf for Grafana Cloud 125 | 126 | If you are a Grafana Cloud customer and wish to use telegraf to write to an Influx Proxy running inside Grafana Cloud you can use a config similar to this: 127 | 128 | ``` 129 | [[outputs.influxdb]] 130 | urls = ["https://_grafana_net_instance_/api/v1/push/influx/write"] 131 | username = "_username_" 132 | password = "_password_" 133 | data_format = "influx" 134 | skip_database_creation = true 135 | ``` 136 | 137 | As above, the `_username_`, `_password_` and `_grafana_net_instance_` are adapted from the Prometheus instance details for the stack information page on [grafana.com](https://grafana.com/). 138 | 139 | For example, if your username was `123456789` and the Prometheus write endpoint was listed as `https://prometheus-prod-26-prod-ap-south-0.grafana.net/api/prom/push` then the corresponding config to send to Grafana Cloud would look something like: 140 | 141 | ``` 142 | [[outputs.influxdb]] 143 | urls = ["https://influx-prod-26-prod-ap-south-0.grafana.net/api/v1/push/influx/write"] 144 | username = "123456789" 145 | password = "_ELIDED_" 146 | data_format = "influx" 147 | skip_database_creation = true 148 | ``` 149 | 150 | Note: The hostname in the URL has `influx` instead of `prometheus`. 151 | 152 | ## More information 153 | 154 | More information, including example `python`, `ruby` and `Node.js` snippets to push to the influx2cortex proxy can be found in the [Push metrics from Influx Telegraf to Prometheus](https://grafana.com/docs/grafana-cloud/data-configuration/metrics/metrics-influxdb/push-from-telegraf/#pushing-from-applications-directly) blog post. 155 | 156 | ## Internal metrics 157 | 158 | The influx2cortex binary exposes internal metrics on a `/metrics` endpoint on a separate port which can be scraped by a local prometheus installation. This is configurable with the `internalserver` command line options. 159 | 160 | ## TODO - package consolidation 161 | * Consolidate `pkg/internalserver' into mimir-graphite 162 | -------------------------------------------------------------------------------- /acceptance/config/cortex.yaml: -------------------------------------------------------------------------------- 1 | # Configuration for running Cortex in single-process mode. 2 | # This should not be used in production. It is only for getting started 3 | # and development. 4 | 5 | # Disable the requirement that every request to Cortex has a 6 | # X-Scope-OrgID header. `fake` will be substituted in instead. 7 | auth_enabled: false 8 | 9 | server: 10 | http_listen_port: 9009 11 | 12 | # Configure the server to allow messages up to 100MB. 13 | grpc_server_max_recv_msg_size: 104857600 14 | grpc_server_max_send_msg_size: 104857600 15 | grpc_server_max_concurrent_streams: 1000 16 | log_level: debug 17 | 18 | distributor: 19 | shard_by_all_labels: true 20 | pool: 21 | health_check_ingesters: true 22 | 23 | ingester_client: 24 | grpc_client_config: 25 | # Configure the client to allow messages up to 100MB. 26 | max_recv_msg_size: 104857600 27 | max_send_msg_size: 104857600 28 | 29 | ingester: 30 | # We want our ingesters to flush chunks at the same time to optimise 31 | # deduplication opportunities. 32 | spread_flushes: true 33 | chunk_age_jitter: 0 34 | 35 | walconfig: 36 | wal_enabled: true 37 | recover_from_wal: true 38 | wal_dir: /tmp/cortex/wal 39 | 40 | lifecycler: 41 | # The address to advertise for this ingester. Will be autodiscovered by 42 | # looking up address on eth0 or en0; can be specified if this fails. 43 | # address: 127.0.0.1 44 | 45 | # We want to start immediately and flush on shutdown. 46 | join_after: 0 47 | min_ready_duration: 0s 48 | final_sleep: 0s 49 | num_tokens: 512 50 | tokens_file_path: /tmp/cortex/wal/tokens 51 | 52 | # Use an in memory ring store, so we don't need to launch a Consul. 53 | ring: 54 | kvstore: 55 | store: inmemory 56 | replication_factor: 1 57 | 58 | storage: 59 | engine: blocks 60 | 61 | blocks_storage: 62 | backend: filesystem 63 | 64 | filesystem: 65 | dir: /tmp/cortex/blocks 66 | 67 | ruler: 68 | enable_api: false 69 | 70 | purger: 71 | object_store_type: filesystem 72 | 73 | querier: 74 | query_store_for_labels_enabled: true 75 | -------------------------------------------------------------------------------- /acceptance/suite_test.go: -------------------------------------------------------------------------------- 1 | //go:build acceptance 2 | // +build acceptance 3 | 4 | package influxtest 5 | 6 | import ( 7 | "bufio" 8 | "bytes" 9 | "context" 10 | "fmt" 11 | "net/http" 12 | "runtime" 13 | "strings" 14 | "testing" 15 | "time" 16 | 17 | "github.com/ahmetalpbalkan/dlog" 18 | "github.com/colega/envconfig" 19 | influxdb "github.com/influxdata/influxdb-client-go/v2" 20 | influxdb_api "github.com/influxdata/influxdb-client-go/v2/api" 21 | "github.com/ory/dockertest/v3" 22 | "github.com/ory/dockertest/v3/docker" 23 | promapi "github.com/prometheus/client_golang/api" 24 | promv1 "github.com/prometheus/client_golang/api/prometheus/v1" 25 | "github.com/stretchr/testify/suite" 26 | ) 27 | 28 | var ( 29 | suiteContainerLabels = map[string]string{"acceptance-suite": "influx-proxy"} 30 | ) 31 | 32 | // These tests verify that the Influx proxy is able to take in InfluxDB line protocol, 33 | // correctly parse it and convert it into a timeseries, and write the timeseries to 34 | // Cortex. Several services are run to execute the tests. The InfluxDB client is used to 35 | // send line protocol to the proxy. The proxy service accepts the line protocol, parses it, 36 | // and writes it to the Cortex service. The Prometheus client and API are used to query 37 | // Prometheus to verify that the line protocol was parsed and converted into the expected 38 | // timeseries, and that the timeseries was successfully written. 39 | 40 | func TestSuite(t *testing.T) { 41 | suite.Run(t, new(Suite)) 42 | } 43 | 44 | type Suite struct { 45 | suite.Suite 46 | 47 | // cfg is filled with env values starting with ACCEPTANCE_ prefix, 48 | // for example, ACCEPTANCE_DOCKER_HOST for cfg.Docker.Host 49 | cfg struct { 50 | // CI should be set to true in CI env 51 | CI bool 52 | Docker struct { 53 | // Host defines where docker containers run 54 | // This is `localhost` for local env, but in CI containers run in a dind service that runs on `docker` host. 55 | Host string `default:"localhost"` 56 | // Tag defines which version of our apps has to be tested. In local, these are built using `make build-local`, 57 | // while in CI those are images pushed to gcr ready to be used in production. 58 | Tag string `default:"local"` 59 | // Auth is used in CI to be able to pull images from GCR. In local we expect the images to be already built. 60 | Auth docker.AuthConfiguration 61 | } 62 | } 63 | 64 | pool *dockertest.Pool 65 | network *dockertest.Network 66 | 67 | cortexResource *dockertest.Resource 68 | influxProxyResource *dockertest.Resource 69 | 70 | api struct { 71 | influx_client influxdb.Client 72 | writeAPI influxdb_api.WriteAPIBlocking 73 | promClient promapi.Client 74 | querierClient promv1.API 75 | } 76 | 77 | suiteReady time.Time 78 | } 79 | 80 | // This method sets up the services that are used for these tests: cortex, the influx proxy, 81 | // the InfluxDB client, and the Prometheus client and API. 82 | func (s *Suite) SetupSuite() { 83 | t0 := time.Now() 84 | s.Require().NoError(envconfig.Process("ACCEPTANCE", &s.cfg)) 85 | s.Require().NotEmpty(s.cfg.Docker.Tag, "ACCEPTANCE_DOCKER_TAG should not be empty as that would test the latest version. It should be a branch tag or `local` for local testing") 86 | 87 | pool, err := dockertest.NewPool("") 88 | s.Require().NoError(err) 89 | s.pool = pool 90 | s.Require().NoError(s.pool.Retry(s.pool.Client.Ping), "Docker daemon isn't ready") 91 | 92 | s.network = s.createNetwork() 93 | s.cortexResource = s.startCortex() 94 | s.influxProxyResource = s.startInfluxProxy() 95 | 96 | influx_write_endpoint := fmt.Sprintf("http://%s:%s/", s.cfg.Docker.Host, s.influxProxyResource.GetPort("8080/tcp")) 97 | influx_client := influxdb.NewClient(influx_write_endpoint, "my-token") 98 | write_api := influx_client.WriteAPIBlocking("my-org", "my-bucket") 99 | s.api.influx_client = influx_client 100 | s.api.writeAPI = write_api 101 | 102 | // Prometheus client and API for verifying that writes occurred as expected 103 | s.api.promClient, _ = promapi.NewClient(promapi.Config{ 104 | Address: fmt.Sprintf("http://%s:%s/api/prom", s.cfg.Docker.Host, s.cortexResource.GetPort("9009/tcp")), 105 | }) 106 | s.api.querierClient = promv1.NewAPI(s.api.promClient) 107 | 108 | s.suiteReady = time.Now() 109 | s.T().Logf("Setup complete, took %s", time.Since(t0)) 110 | } 111 | 112 | func (s *Suite) TearDownSuite() { 113 | if s.T().Failed() { 114 | if s.cfg.CI { 115 | s.printLogs(s.influxProxyResource) 116 | } else { 117 | s.T().Logf("Not stopping containers to allow logs inspection") 118 | s.T().Logf("Use the following command to stop them:") 119 | s.T().Logf(`docker ps --filter "label=acceptance-suite=influx-proxy" -q | xargs docker stop | xargs docker rm`) 120 | return 121 | } 122 | } 123 | 124 | s.NoError(s.cortexResource.Close()) 125 | s.NoError(s.influxProxyResource.Close()) 126 | s.NoError(s.network.Close()) 127 | } 128 | 129 | func (s *Suite) SetupTest() { 130 | s.T().Logf("Test started at %s", time.Now().Format(time.RFC3339Nano)) 131 | } 132 | 133 | func (s *Suite) TearDownTest() { 134 | s.T().Logf("Test ended at %s", time.Now().Format(time.RFC3339Nano)) 135 | } 136 | 137 | func (s *Suite) printLogs(res *dockertest.Resource) { 138 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) 139 | defer cancel() 140 | 141 | buf := &bytes.Buffer{} 142 | s.Assert().NoError(s.pool.Client.Logs(docker.LogsOptions{ 143 | Context: ctx, 144 | Container: res.Container.ID, 145 | OutputStream: buf, 146 | InactivityTimeout: 0, 147 | Stdout: true, 148 | Stderr: true, 149 | Timestamps: true, 150 | RawTerminal: true, // put everything on OutputStream 151 | })) 152 | 153 | scanner := bufio.NewScanner(dlog.NewReader(buf)) 154 | s.T().Logf("Logs from %s", res.Container.Name) 155 | for scanner.Scan() { 156 | s.T().Logf("%s | %s", res.Container.Name, scanner.Text()) 157 | } 158 | } 159 | 160 | func (s *Suite) createNetwork() *dockertest.Network { 161 | network, err := s.pool.CreateNetwork("acceptance-testing") 162 | s.Require().NoError(err) 163 | return network 164 | } 165 | 166 | func (s *Suite) startCortex() *dockertest.Resource { 167 | const ( 168 | name = "cortex" 169 | repo = "cortexproject/cortex" 170 | tag = "master-3018a54" 171 | ) 172 | 173 | container := s.startContainer(&dockertest.RunOptions{ 174 | Name: name, 175 | Repository: repo, 176 | Tag: tag, 177 | Env: nil, 178 | Cmd: []string{"cortex", "-config.file=/etc/config/cortex-config.yaml"}, 179 | Mounts: []string{s.testFilePath() + "/config/cortex.yaml:/etc/config/cortex-config.yaml"}, 180 | ExposedPorts: []string{"9009"}, 181 | PortBindings: map[docker.Port][]docker.PortBinding{"9009/tcp": {}}, 182 | Networks: []*dockertest.Network{s.network}, 183 | Labels: suiteContainerLabels, 184 | }, "ready", "9009/tcp") 185 | 186 | return container 187 | } 188 | 189 | func (s *Suite) startInfluxProxy() *dockertest.Resource { 190 | const ( 191 | name = "influx2cortex" 192 | repo = "us.gcr.io/kubernetes-dev/influx2cortex" 193 | ) 194 | 195 | return s.startContainer(&dockertest.RunOptions{ 196 | Name: name, 197 | Repository: repo, 198 | Tag: s.cfg.Docker.Tag, 199 | Cmd: []string{ 200 | "-server.http-listen-address=0.0.0.0", 201 | "-server.http-listen-port=8080", 202 | "-auth.enable=false", 203 | "-write-endpoint=http://cortex:9009/api/prom/push", 204 | }, 205 | ExposedPorts: []string{"8080", "8081", "9095"}, 206 | Networks: []*dockertest.Network{s.network}, 207 | PortBindings: map[docker.Port][]docker.PortBinding{"8080/tcp": {}, "8081/tcp": {}, "9095/tcp": {}}, 208 | Privileged: false, 209 | Auth: s.cfg.Docker.Auth, 210 | Labels: suiteContainerLabels, 211 | }, "healthz", "8081/tcp") 212 | } 213 | 214 | func (s *Suite) waitForReady(template string, args ...interface{}) { 215 | s.Require().NoError( 216 | s.pool.Retry( 217 | healthCheck(template, args...), 218 | ), 219 | ) 220 | } 221 | 222 | // testFilePath returns the path of this test file, without the trailing slash 223 | func (s *Suite) testFilePath() string { 224 | _, testFilename, _, _ := runtime.Caller(0) 225 | path := testFilename[:strings.LastIndex(testFilename, "/")] 226 | return path 227 | } 228 | 229 | // healthCheck creates a health check function that will succeed once the url returns a 200 OK status 230 | // the template provided will be formatted-f with the args 231 | func healthCheck(template string, args ...interface{}) func() error { 232 | url := fmt.Sprintf(template, args...) 233 | return func() error { 234 | resp, err := http.Get(url) 235 | if err != nil { 236 | return err 237 | } 238 | if resp.StatusCode != http.StatusOK { 239 | return fmt.Errorf("status code isn't 200 OK, is %s", resp.Status) 240 | } 241 | return nil 242 | } 243 | } 244 | 245 | // waitUntilElapsedAfterSuiteSetup waits until duration is elapsed after suite setup 246 | // this allows dynamic wait periods depending on the amount of tests running, 247 | // avoiding double waits when more than one test is running which in the end makes waiting period more deterministic. 248 | func (s *Suite) waitUntilElapsedAfterSuiteSetup(duration time.Duration) { 249 | wait := time.Until(s.suiteReady.Add(duration)) 250 | s.T().Logf("Waiting %s", wait) 251 | time.Sleep(wait) 252 | s.T().Log("Done waiting") 253 | } 254 | 255 | // startContainer will run a container with the given options, run a health check until the resource is available, 256 | // and then return. 257 | func (s *Suite) startContainer(runOptions *dockertest.RunOptions, healthEndpoint, healthPort string) *dockertest.Resource { 258 | // Make sure that there are no containers running from previous execution first 259 | s.Require().NoError(s.pool.RemoveContainerByName(runOptions.Name)) 260 | 261 | image := fmt.Sprintf("%s:%s", runOptions.Repository, runOptions.Tag) 262 | s.T().Logf("Starting %s from %s", runOptions.Name, image) 263 | 264 | if runOptions.Tag == "local" { 265 | _, err := s.pool.Client.InspectImage(image) 266 | s.Require().NoError(err, "Could not find %s, have you run `make build-local`?", image) 267 | } 268 | 269 | resource, err := s.pool.RunWithOptions(runOptions) 270 | s.Require().NoError(err) 271 | s.waitForReady("http://%s:%s/"+healthEndpoint, s.cfg.Docker.Host, resource.GetPort(healthPort)) 272 | return resource 273 | } 274 | -------------------------------------------------------------------------------- /acceptance/write_proxy_test.go: -------------------------------------------------------------------------------- 1 | //go:build acceptance 2 | // +build acceptance 3 | 4 | package influxtest 5 | 6 | import ( 7 | "context" 8 | "fmt" 9 | "time" 10 | 11 | v1 "github.com/prometheus/client_golang/api/prometheus/v1" 12 | "github.com/prometheus/common/model" 13 | ) 14 | 15 | func (s *Suite) Test_WriteLineProtocol_SingleMetric() { 16 | // Ensure that query results no result before line protocol is written 17 | result, _, err := s.api.querierClient.Query(context.Background(), "stat_avg", time.Now()) 18 | s.Require().NoError(err) 19 | s.Require().Empty(result) 20 | 21 | line := fmt.Sprintf("stat,unit=temperature,status=measured avg=%f", 23.5) 22 | err = s.api.writeAPI.WriteRecord(context.Background(), line) 23 | s.Require().NoError(err) 24 | 25 | expectedResult := model.Sample{ 26 | Metric: model.Metric{ 27 | model.MetricNameLabel: "stat_avg", 28 | model.LabelName("__proxy_source__"): "influx", 29 | model.LabelName("unit"): "temperature", 30 | model.LabelName("status"): "measured", 31 | }, 32 | Value: 23.5, 33 | } 34 | 35 | result, _, err = s.api.querierClient.Query(context.Background(), "stat_avg", time.Now()) 36 | s.Require().NoError(err) 37 | 38 | resultVector := result.(model.Vector) 39 | s.Require().Len(resultVector, 1) 40 | 41 | s.Require().Equal(expectedResult.Metric, resultVector[0].Metric) 42 | s.Require().Equal(expectedResult.Value, resultVector[0].Value) 43 | } 44 | 45 | func (s *Suite) Test_WriteLineProtocol_MultipleFields() { 46 | // Ensure that query results no result before line protocol is written 47 | result, _, err := s.api.querierClient.Query(context.Background(), "{__name__=~\"measurement_.+\",__proxy_source__=\"influx\"}", time.Now()) 48 | s.Require().NoError(err) 49 | s.Require().Empty(result) 50 | 51 | err = s.api.writeAPI.WriteRecord(context.Background(), "measurement,t1=v1 f1=2,f2=3") 52 | s.Require().NoError(err) 53 | 54 | expectedResult1 := model.Sample{ 55 | Metric: model.Metric{ 56 | model.MetricNameLabel: "measurement_f1", 57 | model.LabelName("__proxy_source__"): "influx", 58 | model.LabelName("t1"): "v1", 59 | }, 60 | Value: 2, 61 | } 62 | expectedResult2 := model.Sample{ 63 | Metric: model.Metric{ 64 | model.MetricNameLabel: "measurement_f2", 65 | model.LabelName("__proxy_source__"): "influx", 66 | model.LabelName("t1"): "v1", 67 | }, 68 | Value: 3, 69 | } 70 | 71 | result, _, err = s.api.querierClient.Query(context.Background(), "{__name__=~\"measurement_.+\",__proxy_source__=\"influx\"}", time.Now()) 72 | s.Require().NoError(err) 73 | resultVector := result.(model.Vector) 74 | s.Require().Len(resultVector, 2) 75 | 76 | s.Require().Equal(expectedResult1.Metric, resultVector[0].Metric) 77 | s.Require().Equal(expectedResult1.Value, resultVector[0].Value) 78 | s.Require().Equal(expectedResult2.Metric, resultVector[1].Metric) 79 | s.Require().Equal(expectedResult2.Value, resultVector[1].Value) 80 | 81 | } 82 | 83 | func (s *Suite) Test_WriteLineProtocol_MetricWithDifferentTags() { 84 | // Ensure that query results no result before line protocol is written 85 | result, _, err := s.api.querierClient.Query(context.Background(), "sample_metric", time.Now()) 86 | s.Require().NoError(err) 87 | s.Require().Empty(result) 88 | 89 | lines := []string{ 90 | "sample,tag1=val1 metric=3", 91 | "sample,tag2=val2 metric=4", 92 | "sample,tag3=val3 metric=5", 93 | } 94 | for _, line := range lines { 95 | err = s.api.writeAPI.WriteRecord(context.Background(), line) 96 | s.Require().NoError(err) 97 | } 98 | 99 | expectedResult1 := model.Sample{ 100 | Metric: model.Metric{ 101 | model.MetricNameLabel: "sample_metric", 102 | model.LabelName("__proxy_source__"): "influx", 103 | model.LabelName("tag1"): "val1", 104 | }, 105 | Value: 3, 106 | } 107 | expectedResult2 := model.Sample{ 108 | Metric: model.Metric{ 109 | model.MetricNameLabel: "sample_metric", 110 | model.LabelName("__proxy_source__"): "influx", 111 | model.LabelName("tag2"): "val2", 112 | }, 113 | Value: 4, 114 | } 115 | expectedResult3 := model.Sample{ 116 | Metric: model.Metric{ 117 | model.MetricNameLabel: "sample_metric", 118 | model.LabelName("__proxy_source__"): "influx", 119 | model.LabelName("tag3"): "val3", 120 | }, 121 | Value: 5, 122 | } 123 | 124 | result, _, err = s.api.querierClient.Query(context.Background(), "sample_metric", time.Now()) 125 | s.Require().NoError(err) 126 | 127 | resultVector := result.(model.Vector) 128 | s.Require().Len(resultVector, 3) 129 | 130 | s.Require().Equal(expectedResult1.Metric, resultVector[0].Metric) 131 | s.Require().Equal(expectedResult1.Value, resultVector[0].Value) 132 | s.Require().Equal(expectedResult2.Metric, resultVector[1].Metric) 133 | s.Require().Equal(expectedResult2.Value, resultVector[1].Value) 134 | s.Require().Equal(expectedResult3.Metric, resultVector[2].Metric) 135 | s.Require().Equal(expectedResult3.Value, resultVector[2].Value) 136 | } 137 | 138 | func (s *Suite) Test_WriteLineProtocol_MultipleMetrics() { 139 | // Ensure that query results no result before line protocol is written 140 | result, _, err := s.api.querierClient.QueryRange(context.Background(), 141 | "{__name__=~\"test_metric_.+\",__proxy_source__=\"influx\"}", 142 | v1.Range{ 143 | Start: time.Now().Add(-time.Hour), 144 | End: time.Now(), 145 | Step: 15 * time.Second, 146 | }) 147 | s.Require().NoError(err) 148 | s.Require().Empty(result) 149 | 150 | lines := []string{ 151 | "test_metric,test=1,tag=2 foo=1", 152 | "test_metric_time,test=1,tag=4 sample=3.14", 153 | "test_metric_duration,test=2 total=0.5", 154 | } 155 | for _, line := range lines { 156 | err := s.api.writeAPI.WriteRecord(context.Background(), line) 157 | s.Require().NoError(err) 158 | } 159 | 160 | expectedResult1 := model.Sample{ 161 | Metric: model.Metric{ 162 | model.MetricNameLabel: "test_metric_duration_total", 163 | model.LabelName("__proxy_source__"): "influx", 164 | model.LabelName("test"): "2", 165 | }, 166 | Value: 0.5, 167 | } 168 | expectedResult2 := model.Sample{ 169 | Metric: model.Metric{ 170 | model.MetricNameLabel: "test_metric_foo", 171 | model.LabelName("__proxy_source__"): "influx", 172 | model.LabelName("test"): "1", 173 | model.LabelName("tag"): "2", 174 | }, 175 | Value: 1, 176 | } 177 | expectedResult3 := model.Sample{ 178 | Metric: model.Metric{ 179 | model.MetricNameLabel: "test_metric_time_sample", 180 | model.LabelName("__proxy_source__"): "influx", 181 | model.LabelName("test"): "1", 182 | model.LabelName("tag"): "4", 183 | }, 184 | Value: 3.14, 185 | } 186 | 187 | result, _, err = s.api.querierClient.QueryRange(context.Background(), 188 | "{__name__=~\"test_metric_.+\",__proxy_source__=\"influx\"}", 189 | v1.Range{ 190 | Start: time.Now().Add(-time.Hour), 191 | End: time.Now(), 192 | Step: 15 * time.Second, 193 | }) 194 | s.Require().NoError(err) 195 | 196 | resultMatrix := result.(model.Matrix) 197 | s.Require().Len(resultMatrix, 3) 198 | 199 | s.Require().Equal(expectedResult1.Metric, resultMatrix[0].Metric) 200 | s.Require().Equal(expectedResult1.Value, resultMatrix[0].Values[0].Value) 201 | s.Require().Equal(expectedResult2.Metric, resultMatrix[1].Metric) 202 | s.Require().Equal(expectedResult2.Value, resultMatrix[1].Values[0].Value) 203 | s.Require().Equal(expectedResult3.Metric, resultMatrix[2].Metric) 204 | s.Require().Equal(expectedResult3.Value, resultMatrix[2].Values[0].Value) 205 | } 206 | -------------------------------------------------------------------------------- /ci/cmd/coverage/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "flag" 6 | "fmt" 7 | "os" 8 | "sort" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | type aggregation struct { 14 | NumStmts int 15 | NumCoveredStmts int 16 | } 17 | 18 | func (a *aggregation) CoveragePct() string { 19 | pct := (float64(a.NumCoveredStmts) / float64(a.NumStmts)) * 100 20 | return fmt.Sprintf("%.1f%%", pct) 21 | } 22 | 23 | func main() { 24 | covFilename := flag.String("f", "coverage.out", "Output of `go test -coverprofile=coverage.out ./...`") 25 | flag.Parse() 26 | 27 | f, err := os.Open(*covFilename) 28 | if err != nil { 29 | panic(err) 30 | } 31 | 32 | agg := make(map[string]*aggregation) 33 | 34 | s := bufio.NewScanner(f) 35 | s.Split(bufio.ScanLines) 36 | 37 | s.Scan() // First line specifies the mode; it doesn't affect what we do so we can just skip it. 38 | 39 | for s.Scan() { 40 | line := s.Text() 41 | 42 | cols := strings.Fields(line) 43 | key := strings.Split(cols[0], ":")[0] 44 | 45 | numStmts, err := strconv.Atoi(cols[1]) 46 | if err != nil { 47 | panic(err) 48 | } 49 | numTimesCovered, err := strconv.Atoi(cols[2]) 50 | if err != nil { 51 | panic(err) 52 | } 53 | 54 | if val, ok := agg[key]; ok { 55 | val.NumStmts += numStmts 56 | if numTimesCovered > 0 { 57 | val.NumCoveredStmts += numStmts 58 | } 59 | } else { 60 | numCoveredStmts := 0 61 | if numTimesCovered > 0 { 62 | numCoveredStmts = numStmts 63 | } 64 | 65 | agg[key] = &aggregation{ 66 | NumStmts: numStmts, 67 | NumCoveredStmts: numCoveredStmts, 68 | } 69 | } 70 | } 71 | 72 | keys := make([]string, 0, len(agg)) 73 | for k := range agg { 74 | keys = append(keys, k) 75 | } 76 | sort.Strings(keys) 77 | 78 | fmt.Println("
") 79 | fmt.Println("Go coverage report (click to expand)") 80 | fmt.Println("") 81 | fmt.Println("| File | % |") 82 | fmt.Println("| ---- | - |") 83 | 84 | totalStmts := 0 85 | totalCoveredStmts := 0 86 | 87 | for _, k := range keys { 88 | a := agg[k] 89 | fmt.Printf("| %s | %s |\n", k, a.CoveragePct()) 90 | 91 | totalStmts += a.NumStmts 92 | totalCoveredStmts += a.NumCoveredStmts 93 | } 94 | 95 | fmt.Printf("| total | %.1f%% |\n", (float64(totalCoveredStmts)/float64(totalStmts))*100) 96 | fmt.Println("
") 97 | } 98 | -------------------------------------------------------------------------------- /ci/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/grafana/influx2cortex/ci 2 | 3 | go 1.23 4 | -------------------------------------------------------------------------------- /ci/go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grafana/influx2cortex/9cf22857b59dd15f2b6752b45b9f598d508dd595/ci/go.sum -------------------------------------------------------------------------------- /cmd/influx2cortex/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "flag" 7 | "os" 8 | "time" 9 | 10 | "github.com/go-kit/log" 11 | "github.com/go-kit/log/level" 12 | "github.com/grafana/dskit/flagext" 13 | "github.com/grafana/dskit/services" 14 | "github.com/grafana/dskit/signals" 15 | "github.com/grafana/influx2cortex/pkg/influx" 16 | "github.com/grafana/influx2cortex/pkg/internalserver" 17 | "github.com/prometheus/client_golang/prometheus" 18 | ) 19 | 20 | func main() { 21 | logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) 22 | // Add caller information by skipping 3 stack frames 23 | logger = log.With(logger, "caller", log.Caller(3)) 24 | logger = log.WithPrefix(logger, "ts", log.DefaultTimestampUTC) 25 | 26 | promRegisterer := prometheus.DefaultRegisterer 27 | 28 | proxyConfig := influx.ProxyConfig{ 29 | Logger: logger, 30 | Registerer: promRegisterer, 31 | } 32 | internalServerConfig := internalserver.ServiceConfig{} 33 | var shutdownDelay time.Duration 34 | 35 | flagext.RegisterFlags( 36 | &proxyConfig, 37 | &internalServerConfig, 38 | ) 39 | flag.DurationVar( 40 | &shutdownDelay, 41 | "shutdown-delay", 42 | 0, 43 | "How long to wait between SIGTERM and shutdown. After receiving SIGTERM, a non-ready status will be reported via readiness handler.", 44 | ) 45 | flag.Parse() 46 | 47 | appServices := make([]services.Service, 0) 48 | 49 | proxyService, err := influx.NewProxy(proxyConfig) 50 | if err != nil { 51 | _ = level.Error(logger).Log("msg", "error instantiating influx write proxy", "error", err) 52 | os.Exit(1) 53 | } 54 | appServices = append(appServices, proxyService) 55 | 56 | internalService, err := internalserver.NewService(internalServerConfig, logger) 57 | if err != nil { 58 | _ = level.Error(logger).Log("msg", "error instantiating internal server", "error", err) 59 | os.Exit(1) 60 | } 61 | appServices = append(appServices, internalService) 62 | 63 | ctx, cancelFn := context.WithCancel(context.Background()) 64 | defer cancelFn() 65 | 66 | for _, service := range appServices { 67 | err = services.StartAndAwaitRunning(ctx, service) 68 | if err != nil { 69 | _ = level.Error(logger).Log( 70 | "msg", "error starting service", 71 | "service", services.DescribeService(service), 72 | "error", err) 73 | os.Exit(1) 74 | } 75 | } 76 | 77 | // Look for SIGTERM and stop the server if we get it 78 | handler := signals.NewHandler(logger) 79 | go func() { 80 | handler.Loop() 81 | internalService.SetReady(false) 82 | if shutdownDelay > 0 { 83 | _ = level.Info(logger).Log("msg", "waiting for shutdown delay", "delay", shutdownDelay) 84 | time.Sleep(shutdownDelay) 85 | } 86 | for _, service := range appServices { 87 | service.StopAsync() 88 | } 89 | }() 90 | 91 | for _, service := range appServices { 92 | err = service.AwaitTerminated(context.Background()) 93 | if err != nil && !errors.Is(err, context.Canceled) { 94 | _ = level.Error(logger).Log("msg", "error in service", "error", err) 95 | os.Exit(1) 96 | } 97 | } 98 | 99 | os.Exit(0) 100 | } 101 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/grafana/influx2cortex 2 | 3 | go 1.24.1 4 | 5 | require ( 6 | github.com/ahmetalpbalkan/dlog v0.0.0-20170105205344-4fb5f8204f26 7 | github.com/colega/envconfig v0.1.0 8 | github.com/go-kit/log v0.2.1 9 | github.com/gorilla/mux v1.8.1 10 | github.com/grafana/dskit v0.0.0-20250422145853-90fa6b9a2b76 11 | github.com/grafana/mimir v0.0.0-20250501105506-4584085047c0 12 | github.com/grafana/mimir-graphite/v2 v2.1.0 13 | github.com/influxdata/influxdb-client-go/v2 v2.14.0 14 | github.com/influxdata/influxdb/v2 v2.7.11 15 | github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b 16 | github.com/ory/dockertest/v3 v3.12.0 17 | github.com/pkg/errors v0.9.1 18 | github.com/prometheus/client_golang v1.22.0 19 | github.com/prometheus/common v0.64.0 20 | github.com/prometheus/prometheus v1.99.0 21 | github.com/stretchr/testify v1.10.0 22 | google.golang.org/grpc v1.72.2 23 | ) 24 | 25 | require ( 26 | cloud.google.com/go v0.116.0 // indirect 27 | cloud.google.com/go/auth v0.16.0 // indirect 28 | cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect 29 | cloud.google.com/go/compute/metadata v0.6.0 // indirect 30 | cloud.google.com/go/iam v1.2.2 // indirect 31 | cloud.google.com/go/storage v1.43.0 // indirect 32 | dario.cat/mergo v1.0.0 // indirect 33 | github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 // indirect 34 | github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.2 // indirect 35 | github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect 36 | github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.0 // indirect 37 | github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect 38 | github.com/AzureAD/microsoft-authentication-library-for-go v1.3.3 // indirect 39 | github.com/DmitriyVTitov/size v1.5.0 // indirect 40 | github.com/Microsoft/go-winio v0.6.2 // indirect 41 | github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect 42 | github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect 43 | github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect 44 | github.com/armon/go-metrics v0.4.1 // indirect 45 | github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect 46 | github.com/aws/aws-sdk-go v1.55.6 // indirect 47 | github.com/aws/aws-sdk-go-v2 v1.36.3 // indirect 48 | github.com/aws/aws-sdk-go-v2/config v1.29.9 // indirect 49 | github.com/aws/aws-sdk-go-v2/credentials v1.17.62 // indirect 50 | github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.30 // indirect 51 | github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.34 // indirect 52 | github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.34 // indirect 53 | github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect 54 | github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3 // indirect 55 | github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15 // indirect 56 | github.com/aws/aws-sdk-go-v2/service/s3 v1.79.2 // indirect 57 | github.com/aws/aws-sdk-go-v2/service/sso v1.25.1 // indirect 58 | github.com/aws/aws-sdk-go-v2/service/ssooidc v1.29.1 // indirect 59 | github.com/aws/aws-sdk-go-v2/service/sts v1.33.17 // indirect 60 | github.com/aws/smithy-go v1.22.3 // indirect 61 | github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3 // indirect 62 | github.com/beorn7/perks v1.0.1 // indirect 63 | github.com/cenkalti/backoff/v4 v4.3.0 // indirect 64 | github.com/cespare/xxhash/v2 v2.3.0 // indirect 65 | github.com/containerd/continuity v0.4.5 // indirect 66 | github.com/coreos/go-semver v0.3.0 // indirect 67 | github.com/coreos/go-systemd/v22 v22.5.0 // indirect 68 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect 69 | github.com/dennwc/varint v1.0.0 // indirect 70 | github.com/dgraph-io/ristretto v0.1.1 // indirect 71 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect 72 | github.com/docker/cli v27.4.1+incompatible // indirect 73 | github.com/docker/docker v28.0.4+incompatible // indirect 74 | github.com/docker/go-connections v0.5.0 // indirect 75 | github.com/docker/go-units v0.5.0 // indirect 76 | github.com/dustin/go-humanize v1.0.1 // indirect 77 | github.com/edsrzf/mmap-go v1.2.0 // indirect 78 | github.com/efficientgo/core v1.0.0-rc.3 // indirect 79 | github.com/emicklei/go-restful/v3 v3.12.1 // indirect 80 | github.com/facette/natsort v0.0.0-20181210072756-2cd4dd1e2dcb // indirect 81 | github.com/fatih/color v1.16.0 // indirect 82 | github.com/felixge/httpsnoop v1.0.4 // indirect 83 | github.com/fsnotify/fsnotify v1.8.0 // indirect 84 | github.com/go-ini/ini v1.67.0 // indirect 85 | github.com/go-logfmt/logfmt v0.6.0 // indirect 86 | github.com/go-logr/logr v1.4.2 // indirect 87 | github.com/go-logr/stdr v1.2.2 // indirect 88 | github.com/go-openapi/analysis v0.23.0 // indirect 89 | github.com/go-openapi/errors v0.22.0 // indirect 90 | github.com/go-openapi/jsonpointer v0.21.0 // indirect 91 | github.com/go-openapi/jsonreference v0.21.0 // indirect 92 | github.com/go-openapi/loads v0.22.0 // indirect 93 | github.com/go-openapi/spec v0.21.0 // indirect 94 | github.com/go-openapi/strfmt v0.23.0 // indirect 95 | github.com/go-openapi/swag v0.23.1 // indirect 96 | github.com/go-openapi/validate v0.24.0 // indirect 97 | github.com/go-redis/redis/v8 v8.11.5 // indirect 98 | github.com/go-viper/mapstructure/v2 v2.2.1 // indirect 99 | github.com/goccy/go-json v0.10.5 // indirect 100 | github.com/gogo/googleapis v1.4.1 // indirect 101 | github.com/gogo/protobuf v1.3.2 // indirect 102 | github.com/gogo/status v1.1.1 // indirect 103 | github.com/golang-jwt/jwt/v5 v5.2.2 // indirect 104 | github.com/golang/glog v1.2.4 // indirect 105 | github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect 106 | github.com/golang/protobuf v1.5.4 // indirect 107 | github.com/golang/snappy v1.0.0 // indirect 108 | github.com/google/btree v1.1.2 // indirect 109 | github.com/google/go-cmp v0.7.0 // indirect 110 | github.com/google/s2a-go v0.1.9 // indirect 111 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect 112 | github.com/google/uuid v1.6.0 // indirect 113 | github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect 114 | github.com/googleapis/gax-go/v2 v2.14.1 // indirect 115 | github.com/grafana/gomemcache v0.0.0-20250318131618-74242eea118d // indirect 116 | github.com/grafana/regexp v0.0.0-20240607082908-2cb410fa05da // indirect 117 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect 118 | github.com/hashicorp/consul/api v1.32.0 // indirect 119 | github.com/hashicorp/errwrap v1.1.0 // indirect 120 | github.com/hashicorp/go-cleanhttp v0.5.2 // indirect 121 | github.com/hashicorp/go-hclog v1.6.3 // indirect 122 | github.com/hashicorp/go-immutable-radix v1.3.1 // indirect 123 | github.com/hashicorp/go-msgpack/v2 v2.1.1 // indirect 124 | github.com/hashicorp/go-multierror v1.1.1 // indirect 125 | github.com/hashicorp/go-rootcerts v1.0.2 // indirect 126 | github.com/hashicorp/go-sockaddr v1.0.7 // indirect 127 | github.com/hashicorp/go-version v1.7.0 // indirect 128 | github.com/hashicorp/golang-lru v1.0.2 // indirect 129 | github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect 130 | github.com/hashicorp/memberlist v0.5.1 // indirect 131 | github.com/hashicorp/serf v0.10.1 // indirect 132 | github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 // indirect 133 | github.com/jmespath/go-jmespath v0.4.0 // indirect 134 | github.com/josharian/intern v1.0.0 // indirect 135 | github.com/jpillora/backoff v1.0.0 // indirect 136 | github.com/json-iterator/go v1.1.12 // indirect 137 | github.com/julienschmidt/httprouter v1.3.0 // indirect 138 | github.com/klauspost/compress v1.18.0 // indirect 139 | github.com/klauspost/cpuid/v2 v2.2.10 // indirect 140 | github.com/knadh/koanf/maps v0.1.2 // indirect 141 | github.com/knadh/koanf/providers/confmap v0.1.0 // indirect 142 | github.com/knadh/koanf/v2 v2.1.2 // indirect 143 | github.com/kylelemons/godebug v1.1.0 // indirect 144 | github.com/mailru/easyjson v0.9.0 // indirect 145 | github.com/mattn/go-colorable v0.1.13 // indirect 146 | github.com/mattn/go-isatty v0.0.20 // indirect 147 | github.com/miekg/dns v1.1.64 // indirect 148 | github.com/minio/crc64nvme v1.0.1 // indirect 149 | github.com/minio/md5-simd v1.1.2 // indirect 150 | github.com/minio/minio-go/v7 v7.0.90 // indirect 151 | github.com/mitchellh/copystructure v1.2.0 // indirect 152 | github.com/mitchellh/go-homedir v1.1.0 // indirect 153 | github.com/mitchellh/mapstructure v1.5.0 // indirect 154 | github.com/mitchellh/reflectwalk v1.0.2 // indirect 155 | github.com/moby/docker-image-spec v1.3.1 // indirect 156 | github.com/moby/sys/user v0.3.0 // indirect 157 | github.com/moby/term v0.5.0 // indirect 158 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 159 | github.com/modern-go/reflect2 v1.0.2 // indirect 160 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect 161 | github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect 162 | github.com/ncw/swift v1.0.53 // indirect 163 | github.com/oapi-codegen/runtime v1.0.0 // indirect 164 | github.com/oklog/run v1.1.0 // indirect 165 | github.com/oklog/ulid v1.3.1 // indirect 166 | github.com/oklog/ulid/v2 v2.1.1 // indirect 167 | github.com/open-telemetry/opentelemetry-collector-contrib/internal/exp/metrics v0.124.1 // indirect 168 | github.com/open-telemetry/opentelemetry-collector-contrib/pkg/pdatautil v0.124.1 // indirect 169 | github.com/open-telemetry/opentelemetry-collector-contrib/processor/deltatocumulativeprocessor v0.124.1 // indirect 170 | github.com/opencontainers/go-digest v1.0.0 // indirect 171 | github.com/opencontainers/image-spec v1.1.0 // indirect 172 | github.com/opencontainers/runc v1.2.3 // indirect 173 | github.com/opentracing-contrib/go-grpc v0.1.2 // indirect 174 | github.com/opentracing-contrib/go-stdlib v1.1.0 // indirect 175 | github.com/pierrec/lz4/v4 v4.1.22 // indirect 176 | github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect 177 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect 178 | github.com/prometheus/alertmanager v0.28.1 // indirect 179 | github.com/prometheus/client_model v0.6.2 // indirect 180 | github.com/prometheus/otlptranslator v0.0.0-20250417063547-0a6a352a36dc // indirect 181 | github.com/prometheus/procfs v0.15.1 // indirect 182 | github.com/prometheus/sigv4 v0.1.2 // indirect 183 | github.com/puzpuzpuz/xsync/v3 v3.5.1 // indirect 184 | github.com/rs/xid v1.6.0 // indirect 185 | github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect 186 | github.com/sercand/kuberesolver/v6 v6.0.0 // indirect 187 | github.com/sirupsen/logrus v1.9.3 // indirect 188 | github.com/stretchr/objx v0.5.2 // indirect 189 | github.com/thanos-io/objstore v0.0.0-20250129163715-ec72e5a88a79 // indirect 190 | github.com/tjhop/slog-gokit v0.1.4 // indirect 191 | github.com/twmb/franz-go v1.18.2-0.20250428225424-f2ead607417d // indirect 192 | github.com/twmb/franz-go/pkg/kadm v1.14.0 // indirect 193 | github.com/twmb/franz-go/pkg/kmsg v1.11.2 // indirect 194 | github.com/twmb/franz-go/plugin/kotel v1.5.0 // indirect 195 | github.com/twmb/franz-go/plugin/kprom v1.1.0 // indirect 196 | github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect 197 | github.com/uber/jaeger-lib v2.4.1+incompatible // indirect 198 | github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect 199 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect 200 | github.com/xeipuuv/gojsonschema v1.2.0 // indirect 201 | github.com/xlab/treeprint v1.2.0 // indirect 202 | go.etcd.io/etcd/api/v3 v3.5.5 // indirect 203 | go.etcd.io/etcd/client/pkg/v3 v3.5.5 // indirect 204 | go.etcd.io/etcd/client/v3 v3.5.5 // indirect 205 | go.mongodb.org/mongo-driver v1.14.0 // indirect 206 | go.opencensus.io v0.24.0 // indirect 207 | go.opentelemetry.io/auto/sdk v1.1.0 // indirect 208 | go.opentelemetry.io/collector/component v1.30.0 // indirect 209 | go.opentelemetry.io/collector/confmap v1.30.0 // indirect 210 | go.opentelemetry.io/collector/confmap/xconfmap v0.124.0 // indirect 211 | go.opentelemetry.io/collector/consumer v1.30.0 // indirect 212 | go.opentelemetry.io/collector/featuregate v1.30.0 // indirect 213 | go.opentelemetry.io/collector/internal/telemetry v0.124.0 // indirect 214 | go.opentelemetry.io/collector/pdata v1.30.0 // indirect 215 | go.opentelemetry.io/collector/pipeline v0.124.0 // indirect 216 | go.opentelemetry.io/collector/processor v1.30.0 // indirect 217 | go.opentelemetry.io/collector/semconv v0.124.0 // indirect 218 | go.opentelemetry.io/contrib/bridges/otelzap v0.10.0 // indirect 219 | go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.60.0 // indirect 220 | go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.60.0 // indirect 221 | go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect 222 | go.opentelemetry.io/otel v1.36.0 // indirect 223 | go.opentelemetry.io/otel/log v0.11.0 // indirect 224 | go.opentelemetry.io/otel/metric v1.36.0 // indirect 225 | go.opentelemetry.io/otel/sdk v1.35.0 // indirect 226 | go.opentelemetry.io/otel/trace v1.36.0 // indirect 227 | go.opentelemetry.io/proto/otlp v1.5.0 // indirect 228 | go.uber.org/atomic v1.11.0 // indirect 229 | go.uber.org/goleak v1.3.0 // indirect 230 | go.uber.org/multierr v1.11.0 // indirect 231 | go.uber.org/zap v1.27.0 // indirect 232 | golang.org/x/crypto v0.38.0 // indirect 233 | golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 // indirect 234 | golang.org/x/mod v0.24.0 // indirect 235 | golang.org/x/net v0.40.0 // indirect 236 | golang.org/x/oauth2 v0.30.0 // indirect 237 | golang.org/x/sync v0.14.0 // indirect 238 | golang.org/x/sys v0.33.0 // indirect 239 | golang.org/x/text v0.25.0 // indirect 240 | golang.org/x/time v0.11.0 // indirect 241 | golang.org/x/tools v0.32.0 // indirect 242 | google.golang.org/api v0.229.0 // indirect 243 | google.golang.org/genproto v0.0.0-20241113202542-65e8d215514f // indirect 244 | google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb // indirect 245 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250414145226-207652e42e2e // indirect 246 | google.golang.org/protobuf v1.36.6 // indirect 247 | gopkg.in/yaml.v2 v2.4.0 // indirect 248 | gopkg.in/yaml.v3 v3.0.1 // indirect 249 | k8s.io/apimachinery v0.32.3 // indirect 250 | k8s.io/client-go v0.32.3 // indirect 251 | k8s.io/klog/v2 v2.130.1 // indirect 252 | k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect 253 | ) 254 | 255 | replace ( 256 | // Copied from Mimir. 257 | github.com/prometheus/prometheus => github.com/grafana/mimir-prometheus v1.8.2-0.20250423083340-007de9b763aa 258 | gopkg.in/yaml.v3 => github.com/colega/go-yaml-yaml v0.0.0-20220720105220-255a8d16d094 259 | ) 260 | 261 | exclude ( 262 | // Exclude pre-go-mod kubernetes tags, as they are older 263 | // than v0.x releases but are picked when we update the dependencies. 264 | k8s.io/client-go v1.4.0 265 | k8s.io/client-go v1.4.0+incompatible 266 | k8s.io/client-go v1.5.0 267 | k8s.io/client-go v1.5.0+incompatible 268 | k8s.io/client-go v1.5.1 269 | k8s.io/client-go v1.5.1+incompatible 270 | k8s.io/client-go v2.0.0-alpha.1+incompatible 271 | k8s.io/client-go v2.0.0+incompatible 272 | k8s.io/client-go v3.0.0-beta.0+incompatible 273 | k8s.io/client-go v3.0.0+incompatible 274 | k8s.io/client-go v4.0.0-beta.0+incompatible 275 | k8s.io/client-go v4.0.0+incompatible 276 | k8s.io/client-go v5.0.0+incompatible 277 | k8s.io/client-go v5.0.1+incompatible 278 | k8s.io/client-go v6.0.0+incompatible 279 | k8s.io/client-go v7.0.0+incompatible 280 | k8s.io/client-go v8.0.0+incompatible 281 | k8s.io/client-go v9.0.0-invalid+incompatible 282 | k8s.io/client-go v9.0.0+incompatible 283 | k8s.io/client-go v10.0.0+incompatible 284 | k8s.io/client-go v11.0.0+incompatible 285 | k8s.io/client-go v12.0.0+incompatible 286 | ) 287 | -------------------------------------------------------------------------------- /pkg/README.md: -------------------------------------------------------------------------------- 1 | Where did the most of the packages go? 2 | 3 | Some shared packages have been moved to the [mimir-graphite](https://github.com/grafana/mimir-graphite) repository. Please check for them there. 4 | -------------------------------------------------------------------------------- /pkg/influx/api.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "net/http" 5 | "time" 6 | 7 | "github.com/go-kit/log" 8 | "github.com/go-kit/log/level" 9 | "github.com/gorilla/mux" 10 | "github.com/grafana/dskit/user" 11 | "github.com/grafana/mimir-graphite/v2/pkg/remotewrite" 12 | "github.com/grafana/mimir-graphite/v2/pkg/route" 13 | "github.com/grafana/mimir-graphite/v2/pkg/server/middleware" 14 | "github.com/grafana/mimir/pkg/mimirpb" 15 | "github.com/opentracing/opentracing-go" 16 | "github.com/opentracing/opentracing-go/ext" 17 | ) 18 | 19 | type API struct { 20 | logger log.Logger 21 | client remotewrite.Client 22 | recorder Recorder 23 | maxRequestSizeBytes int 24 | } 25 | 26 | func (a *API) Register(router *mux.Router) { 27 | registerer := route.NewMuxRegisterer(router) 28 | 29 | // Registering two write endpoints; the second is necessary to allow for compatibility with clients that hard-code the endpoint 30 | registerer.RegisterRoute("/api/v1/push/influx/write", http.HandlerFunc(a.handleSeriesPush), http.MethodPost) 31 | registerer.RegisterRoute("/api/v2/write", http.HandlerFunc(a.handleSeriesPush), http.MethodPost) 32 | registerer.RegisterRoute("/healthz", http.HandlerFunc(a.handleHealth), http.MethodGet) 33 | } 34 | 35 | func NewAPI(conf ProxyConfig, client remotewrite.Client, recorder Recorder) (*API, error) { 36 | return &API{ 37 | logger: conf.Logger, 38 | client: client, 39 | recorder: recorder, 40 | maxRequestSizeBytes: conf.MaxRequestSizeBytes, 41 | }, nil 42 | } 43 | 44 | func (a *API) handleHealth(w http.ResponseWriter, r *http.Request) { 45 | span, _ := opentracing.StartSpanFromContext(r.Context(), "handleHealth") 46 | defer span.Finish() 47 | 48 | logger := withRequestInfo(a.logger, r) 49 | _, err := w.Write([]byte("OK")) 50 | 51 | if err != nil { 52 | ext.LogError(span, err) 53 | a.handleError(w, r, err, logger) 54 | return 55 | } 56 | 57 | w.WriteHeader(http.StatusOK) 58 | } 59 | 60 | // HandlerForInfluxLine is a http.Handler which accepts Influx Line protocol and converts it to WriteRequests. 61 | func (a *API) handleSeriesPush(w http.ResponseWriter, r *http.Request) { 62 | span, ctx := opentracing.StartSpanFromContext(r.Context(), "handleSeriesPush") 63 | defer span.Finish() 64 | 65 | logger := withRequestInfo(a.logger, r) 66 | beforeConversion := time.Now() 67 | 68 | ts, bytesRead, err := parseInfluxLineReader(ctx, r, a.maxRequestSizeBytes) 69 | span.LogKV("bytesRead", bytesRead) 70 | logger = log.With(logger, "bytesRead", bytesRead) 71 | if err != nil { 72 | ext.LogError(span, err) 73 | a.handleError(w, r, err, logger) 74 | return 75 | } 76 | 77 | nosMetrics := len(ts) 78 | logger = log.With(logger, "nosMetrics", nosMetrics) 79 | span.LogKV("nosMetrics", nosMetrics) 80 | 81 | a.recorder.measureMetricsParsed(nosMetrics) 82 | a.recorder.measureConversionDuration(time.Since(beforeConversion)) 83 | 84 | // Sigh, a write API optimisation needs me to jump through hoops. 85 | pts := make([]mimirpb.PreallocTimeseries, 0, nosMetrics) 86 | for i := range ts { 87 | pts = append(pts, mimirpb.PreallocTimeseries{ 88 | TimeSeries: &ts[i], 89 | }) 90 | } 91 | rwReq := &mimirpb.WriteRequest{ 92 | Timeseries: pts, 93 | } 94 | 95 | if err := a.client.Write(ctx, rwReq); err != nil { 96 | ext.LogError(span, err) 97 | a.handleError(w, r, err, logger) 98 | return 99 | } 100 | a.recorder.measureMetricsWritten(len(rwReq.Timeseries)) 101 | span.LogKV("nosMetricsWritten", len(rwReq.Timeseries)) 102 | statusCode := http.StatusNoContent 103 | _ = level.Info(logger).Log("response_code", statusCode) 104 | w.WriteHeader(statusCode) // Needed for Telegraf, otherwise it tries to marshal JSON and considers the write a failure. 105 | } 106 | 107 | func withRequestInfo(logger log.Logger, r *http.Request) log.Logger { 108 | ctx := r.Context() 109 | if traceID, ok := middleware.ExtractSampledTraceID(ctx); ok { 110 | logger = log.With(logger, "traceID", traceID) 111 | } 112 | if orgID, err := user.ExtractOrgID(ctx); err == nil { 113 | logger = log.With(logger, "orgID", orgID) 114 | } 115 | if userID, err := user.ExtractUserID(ctx); err == nil { 116 | logger = log.With(logger, "userID", userID) 117 | } 118 | return log.With(logger, "path", r.URL.EscapedPath()) 119 | } 120 | -------------------------------------------------------------------------------- /pkg/influx/api_test.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "bytes" 5 | "net/http" 6 | "net/http/httptest" 7 | "testing" 8 | "time" 9 | 10 | "github.com/go-kit/log" 11 | "github.com/grafana/mimir-graphite/v2/pkg/errorx" 12 | "github.com/grafana/mimir-graphite/v2/pkg/remotewrite/remotewritemock" 13 | "github.com/grafana/mimir/pkg/mimirpb" 14 | "github.com/stretchr/testify/assert" 15 | mock "github.com/stretchr/testify/mock" 16 | "github.com/stretchr/testify/require" 17 | ) 18 | 19 | func TestHandleSeriesPush(t *testing.T) { 20 | tests := []struct { 21 | name string 22 | url string 23 | data string 24 | expectedCode int 25 | expectJsonBody string 26 | remoteWriteMock func() *remotewritemock.Client 27 | recorderMock func() *MockRecorder 28 | maxRequestSizeBytes int 29 | }{ 30 | { 31 | name: "POST", 32 | url: "/write", 33 | data: "measurement,t1=v1 f1=2 1465839830100400200", 34 | expectedCode: http.StatusNoContent, 35 | remoteWriteMock: func() *remotewritemock.Client { 36 | remoteWriteMock := &remotewritemock.Client{} 37 | remoteWriteMock.On("Write", mock.Anything, &mimirpb.WriteRequest{ 38 | Timeseries: []mimirpb.PreallocTimeseries{ 39 | { 40 | TimeSeries: &mimirpb.TimeSeries{ 41 | Labels: []mimirpb.LabelAdapter{ 42 | {Name: "__name__", Value: "measurement_f1"}, 43 | {Name: "__proxy_source__", Value: "influx"}, 44 | {Name: "t1", Value: "v1"}, 45 | }, 46 | Samples: []mimirpb.Sample{ 47 | {Value: 2, TimestampMs: 1465839830100}, 48 | }, 49 | }, 50 | }, 51 | }, 52 | }).Return(nil) 53 | return remoteWriteMock 54 | }, 55 | recorderMock: func() *MockRecorder { 56 | recorderMock := &MockRecorder{} 57 | recorderMock.On("measureMetricsParsed", 1).Return(nil) 58 | recorderMock.On("measureMetricsWritten", 1).Return(nil) 59 | recorderMock.On("measureConversionDuration", mock.MatchedBy(func(duration time.Duration) bool { return duration > 0 })).Return(nil) 60 | return recorderMock 61 | }, 62 | maxRequestSizeBytes: DefaultMaxRequestSizeBytes, 63 | }, 64 | { 65 | name: "POST with precision", 66 | url: "/write?precision=ns", 67 | data: "measurement,t1=v1 f1=2 1465839830100400200", 68 | expectedCode: http.StatusNoContent, 69 | remoteWriteMock: func() *remotewritemock.Client { 70 | remoteWriteMock := &remotewritemock.Client{} 71 | remoteWriteMock.On("Write", mock.Anything, &mimirpb.WriteRequest{ 72 | Timeseries: []mimirpb.PreallocTimeseries{ 73 | { 74 | TimeSeries: &mimirpb.TimeSeries{ 75 | Labels: []mimirpb.LabelAdapter{ 76 | {Name: "__name__", Value: "measurement_f1"}, 77 | {Name: "__proxy_source__", Value: "influx"}, 78 | {Name: "t1", Value: "v1"}, 79 | }, 80 | Samples: []mimirpb.Sample{ 81 | {Value: 2, TimestampMs: 1465839830100}, 82 | }, 83 | }, 84 | }, 85 | }, 86 | }).Return(nil) 87 | return remoteWriteMock 88 | }, 89 | recorderMock: func() *MockRecorder { 90 | recorderMock := &MockRecorder{} 91 | recorderMock.On("measureMetricsParsed", 1).Return(nil) 92 | recorderMock.On("measureMetricsWritten", 1).Return(nil) 93 | recorderMock.On("measureConversionDuration", mock.MatchedBy(func(duration time.Duration) bool { return duration > 0 })).Return(nil) 94 | return recorderMock 95 | }, 96 | maxRequestSizeBytes: DefaultMaxRequestSizeBytes, 97 | }, 98 | { 99 | name: "invalid parsing error handling", 100 | url: "/write", 101 | data: "measurement,t1=v1 f1= 1465839830100400200", 102 | expectedCode: http.StatusBadRequest, 103 | expectJsonBody: `{ 104 | "code": "invalid", 105 | "message": "error parsing points" 106 | }`, 107 | remoteWriteMock: func() *remotewritemock.Client { 108 | remoteWriteMock := &remotewritemock.Client{} 109 | remoteWriteMock.On("Write", mock.Anything, mock.Anything). 110 | Return(errorx.BadRequest{}) 111 | return remoteWriteMock 112 | }, 113 | recorderMock: func() *MockRecorder { 114 | recorderMock := &MockRecorder{} 115 | recorderMock.On("measureMetricsParsed", 0).Return(nil) 116 | recorderMock.On("measureMetricsWritten", 0).Return(nil) 117 | recorderMock.On("measureProxyErrors", "errorx.BadRequest").Return(nil) 118 | recorderMock.On("measureConversionDuration", 0).Return(nil) 119 | return recorderMock 120 | }, 121 | maxRequestSizeBytes: DefaultMaxRequestSizeBytes, 122 | }, 123 | { 124 | name: "invalid query params", 125 | url: "/write?precision=?", 126 | data: "measurement,t1=v1 f1=2 1465839830100400200", 127 | expectedCode: http.StatusBadRequest, 128 | expectJsonBody: `{ 129 | "code": "invalid", 130 | "message": "precision supplied is not valid: ?" 131 | }`, 132 | remoteWriteMock: func() *remotewritemock.Client { 133 | remoteWriteMock := &remotewritemock.Client{} 134 | remoteWriteMock.On("Write", mock.Anything, mock.Anything). 135 | Return(errorx.BadRequest{}) 136 | return remoteWriteMock 137 | }, 138 | recorderMock: func() *MockRecorder { 139 | recorderMock := &MockRecorder{} 140 | recorderMock.On("measureMetricsParsed", 0).Return(nil) 141 | recorderMock.On("measureMetricsWritten", 0).Return(nil) 142 | recorderMock.On("measureProxyErrors", "errorx.BadRequest").Return(nil) 143 | recorderMock.On("measureConversionDuration", 0).Return(nil) 144 | return recorderMock 145 | }, 146 | maxRequestSizeBytes: DefaultMaxRequestSizeBytes, 147 | }, 148 | { 149 | name: "internal server error", 150 | url: "/write", 151 | data: "measurement,t1=v1 f1=2 1465839830100400200", 152 | expectedCode: http.StatusInternalServerError, 153 | expectJsonBody: `{ 154 | "code": "internal error", 155 | "message": "some error message" 156 | }`, 157 | remoteWriteMock: func() *remotewritemock.Client { 158 | remoteWriteMock := &remotewritemock.Client{} 159 | remoteWriteMock.On("Write", mock.Anything, mock.Anything). 160 | Return(errorx.Internal{Msg: "some error message"}) 161 | return remoteWriteMock 162 | }, 163 | recorderMock: func() *MockRecorder { 164 | recorderMock := &MockRecorder{} 165 | recorderMock.On("measureMetricsParsed", 1).Return(nil) 166 | recorderMock.On("measureMetricsWritten", 0).Return(nil) 167 | recorderMock.On("measureProxyErrors", "errorx.Internal").Return(nil) 168 | recorderMock.On("measureConversionDuration", mock.MatchedBy(func(duration time.Duration) bool { return duration > 0 })).Return(nil) 169 | return recorderMock 170 | }, 171 | maxRequestSizeBytes: DefaultMaxRequestSizeBytes, 172 | }, 173 | { 174 | name: "max batch size violated", 175 | url: "/write", 176 | data: "measurement,t1=v1 f1=2 0123456789", 177 | expectedCode: http.StatusBadRequest, 178 | expectJsonBody: `{ 179 | "code": "invalid", 180 | "message": "problem reading body" 181 | }`, 182 | remoteWriteMock: func() *remotewritemock.Client { 183 | return &remotewritemock.Client{} 184 | }, 185 | recorderMock: func() *MockRecorder { 186 | recorderMock := &MockRecorder{} 187 | recorderMock.On("measureMetricsParsed", 0).Return(nil) 188 | recorderMock.On("measureMetricsWritten", 0).Return(nil) 189 | recorderMock.On("measureProxyErrors", "errorx.BadRequest").Return(nil) 190 | recorderMock.On("measureConversionDuration", mock.MatchedBy(func(duration time.Duration) bool { return duration > 0 })).Return(nil) 191 | 192 | return recorderMock 193 | }, 194 | maxRequestSizeBytes: 8, 195 | }, 196 | } 197 | 198 | for _, tt := range tests { 199 | t.Run(tt.name, func(t *testing.T) { 200 | req := httptest.NewRequest("POST", tt.url, bytes.NewReader([]byte(tt.data))) 201 | rec := httptest.NewRecorder() 202 | logger := log.NewNopLogger() 203 | conf := ProxyConfig{ 204 | Logger: logger, 205 | MaxRequestSizeBytes: tt.maxRequestSizeBytes, 206 | } 207 | api, err := NewAPI(conf, tt.remoteWriteMock(), tt.recorderMock()) 208 | require.NoError(t, err) 209 | 210 | api.handleSeriesPush(rec, req) 211 | assert.Equal(t, tt.expectedCode, rec.Code) 212 | if tt.expectJsonBody != "" { 213 | assert.Equal(t, []string{"application/json; charset=utf-8"}, rec.Result().Header["Content-Type"]) 214 | assert.JSONEq(t, tt.expectJsonBody, rec.Body.String()) 215 | } else { 216 | assert.Empty(t, rec.Body.String()) 217 | } 218 | 219 | }) 220 | } 221 | } 222 | func TestHandleHealth(t *testing.T) { 223 | req := httptest.NewRequest("GET", "/healthz", nil) 224 | req.Header.Set("X-Scope-OrgID", "fake") 225 | rec := httptest.NewRecorder() 226 | logger := log.NewNopLogger() 227 | api := &API{ 228 | logger: logger, 229 | } 230 | 231 | api.handleHealth(rec, req) 232 | 233 | assert.Equal(t, http.StatusOK, rec.Code) 234 | assert.Equal(t, "OK", rec.Body.String()) 235 | } 236 | -------------------------------------------------------------------------------- /pkg/influx/auth_test.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "fmt" 7 | "net/http" 8 | "testing" 9 | 10 | "github.com/go-kit/log" 11 | "github.com/grafana/dskit/services" 12 | "github.com/grafana/dskit/user" 13 | "github.com/grafana/mimir-graphite/v2/pkg/errorx" 14 | "github.com/grafana/mimir-graphite/v2/pkg/remotewrite" 15 | "github.com/grafana/mimir-graphite/v2/pkg/remotewrite/remotewritemock" 16 | "github.com/grafana/mimir-graphite/v2/pkg/server" 17 | "github.com/prometheus/client_golang/prometheus" 18 | "github.com/stretchr/testify/mock" 19 | "github.com/stretchr/testify/require" 20 | ) 21 | 22 | func TestAuthentication(t *testing.T) { 23 | tests := []struct { 24 | name string 25 | data string 26 | enableAuth bool 27 | orgID string 28 | expectedOrgID string 29 | expectedCode int 30 | expectedErr error 31 | }{ 32 | { 33 | name: "test auth enabled valid org ID", 34 | data: "measurement,t1=v1 f1=2 1465839830100400200", 35 | enableAuth: true, 36 | orgID: "valid", 37 | expectedOrgID: "valid", 38 | expectedCode: http.StatusNoContent, 39 | expectedErr: nil, 40 | }, 41 | { 42 | name: "test auth enabled invalid org ID", 43 | data: "measurement,t1=v1 f1=2 1465839830100400200", 44 | enableAuth: true, 45 | orgID: "", 46 | expectedOrgID: "", 47 | expectedCode: http.StatusUnauthorized, 48 | expectedErr: errorx.BadRequest{}, 49 | }, 50 | { 51 | name: "test auth disabled", 52 | data: "measurement,t1=v1 f1=2 1465839830100400200", 53 | enableAuth: false, 54 | orgID: "", 55 | expectedOrgID: "fake", 56 | expectedCode: http.StatusNoContent, 57 | expectedErr: nil, 58 | }, 59 | } 60 | for _, tt := range tests { 61 | t.Run(tt.name, func(t *testing.T) { 62 | // A dependency is using the default registerer. We refresh it 63 | // on every run to avoid double registration panics. 64 | old := prometheus.DefaultRegisterer 65 | prometheus.DefaultRegisterer = prometheus.NewRegistry() 66 | t.Cleanup(func() { 67 | prometheus.DefaultRegisterer = old 68 | }) 69 | 70 | serverConfig := server.Config{ 71 | HTTPListenAddress: "127.0.0.1", 72 | HTTPListenPort: 0, // Request system available port 73 | } 74 | apiConfig := ProxyConfig{ 75 | HTTPConfig: serverConfig, 76 | EnableAuth: tt.enableAuth, 77 | RemoteWriteConfig: remotewrite.Config{}, 78 | Logger: log.NewNopLogger(), 79 | Registerer: prometheus.NewRegistry(), 80 | } 81 | 82 | remoteWriteMock := &remotewritemock.Client{} 83 | remoteWriteMock.On("Write", mock.Anything, mock.Anything). 84 | Return(tt.expectedErr).Run(func(args mock.Arguments) { 85 | ctx := args.Get(0).(context.Context) 86 | orgID, err := user.ExtractOrgID(ctx) 87 | require.NoError(t, err) 88 | require.Equal(t, orgID, tt.expectedOrgID) 89 | }) 90 | 91 | service, err := newProxyWithClient(apiConfig, remoteWriteMock) 92 | require.NoError(t, err) 93 | require.NoError(t, services.StartAndAwaitRunning(context.Background(), service)) 94 | defer service.StopAsync() 95 | 96 | url := fmt.Sprintf("http://%s/api/v2/write", service.Addr()) 97 | req, err := http.NewRequest("POST", url, bytes.NewReader([]byte("measurement,t1=v1 f1=2 1465839830100400200"))) 98 | require.NoError(t, err) 99 | req = req.WithContext(user.InjectOrgID(req.Context(), tt.orgID)) 100 | err = user.InjectOrgIDIntoHTTPRequest(req.Context(), req) 101 | require.NoError(t, err) 102 | 103 | resp, err := http.DefaultClient.Do(req) 104 | require.NoError(t, err) 105 | require.Equal(t, tt.expectedCode, resp.StatusCode) 106 | }) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /pkg/influx/errors.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "net" 8 | "net/http" 9 | 10 | "github.com/go-kit/log" 11 | "github.com/go-kit/log/level" 12 | "github.com/grafana/mimir-graphite/v2/pkg/errorx" 13 | "github.com/pkg/errors" 14 | "google.golang.org/grpc/codes" 15 | 16 | grpcstatus "google.golang.org/grpc/status" 17 | ) 18 | 19 | // Error codes copied from https://github.com/influxdata/influxdb/blob/569e84d4a73250f2928136e5b40452d058a149bd/kit/platform/errors/errors.go#L15-L29 20 | const ( 21 | EInternal = "internal error" 22 | ENotImplemented = "not implemented" 23 | ENotFound = "not found" 24 | EConflict = "conflict" // action cannot be performed 25 | EInvalid = "invalid" // validation failed 26 | EUnprocessableEntity = "unprocessable entity" // data type is correct, but out of range 27 | EEmptyValue = "empty value" 28 | EUnavailable = "unavailable" 29 | EForbidden = "forbidden" 30 | ETooManyRequests = "too many requests" 31 | EUnauthorized = "unauthorized" 32 | EMethodNotAllowed = "method not allowed" 33 | ETooLarge = "request too large" 34 | ) 35 | 36 | func errorxToInfluxErrorCode(err errorx.Error) string { 37 | switch { 38 | case errors.As(err, &errorx.BadRequest{}): 39 | return EInvalid 40 | case errors.As(err, &errorx.Internal{}): 41 | return EInternal 42 | case errors.As(err, &errorx.Conflict{}): 43 | return EConflict 44 | } 45 | return EInternal 46 | } 47 | 48 | func tryUnwrap(err error) error { 49 | if wrapped, ok := err.(interface{ Unwrap() error }); ok { 50 | return wrapped.Unwrap() 51 | } 52 | return err 53 | } 54 | 55 | // handleError tries to extract an errorx.Error from the given error, logging 56 | // and setting the http response code as needed. All non-errorx errors are 57 | // considered internal errors. Please do not try to fix error categorization in 58 | // this function. All client errors should be categorized as an errorx at the 59 | // site where they are thrown. 60 | func (a *API) handleError(w http.ResponseWriter, r *http.Request, err error, logger log.Logger) { 61 | var statusCode int 62 | var httpErrString string 63 | var errx errorx.Error 64 | errorCode := EInternal 65 | switch { 66 | case errors.As(err, &errx): 67 | errorCode = errorxToInfluxErrorCode(errx) 68 | httpErrString = errx.Message() 69 | statusCode = errx.HTTPStatusCode() 70 | err = errx 71 | case errors.Is(err, context.DeadlineExceeded) || isGRPCTimeout(err): 72 | httpErrString = "network timeout" 73 | statusCode = http.StatusGatewayTimeout 74 | errorCode = EUnavailable 75 | case errors.Is(err, context.Canceled): 76 | // Note: It seems unlikely this can happen other than as a timeout, so we 77 | // should call it an internal error. 78 | httpErrString = "request cancelled" 79 | statusCode = http.StatusInternalServerError 80 | case isNetworkTimeout(err): 81 | if r.Body != nil { 82 | // Try to read 1 byte from the request body. If it fails with the same error 83 | // it means the timeout occurred while reading the request body, so it's a 408. 84 | if _, readErr := r.Body.Read([]byte{0}); isNetworkTimeout(readErr) { 85 | httpErrString = "response timeout" 86 | statusCode = http.StatusRequestTimeout 87 | break 88 | } 89 | httpErrString = "network timeout" 90 | statusCode = http.StatusGatewayTimeout 91 | errorCode = EUnavailable 92 | } 93 | default: 94 | httpErrString = "uncategorized error" 95 | statusCode = http.StatusInternalServerError 96 | } 97 | if statusCode < 500 { 98 | _ = level.Info(logger).Log("msg", httpErrString, "response_code", statusCode, "err", tryUnwrap(err)) 99 | } else if statusCode >= 500 { 100 | _ = level.Warn(logger).Log("msg", httpErrString, "response_code", statusCode, "err", tryUnwrap(err)) 101 | } 102 | a.recorder.measureProxyErrors(fmt.Sprintf("%T", err)) 103 | 104 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 105 | w.WriteHeader(statusCode) 106 | e := struct { 107 | Code string `json:"code"` 108 | Message string `json:"message"` 109 | }{ 110 | Code: errorCode, 111 | Message: httpErrString, 112 | } 113 | b, err := json.Marshal(e) 114 | if err != nil { 115 | _ = level.Warn(logger).Log("msg", "failed to marshal error response", "err", err) 116 | return 117 | } 118 | _, err = w.Write(b) 119 | if err != nil { 120 | _ = level.Warn(logger).Log("msg", "failed to write error response", "err", err) 121 | return 122 | } 123 | } 124 | 125 | func isNetworkTimeout(err error) bool { 126 | if err == nil { 127 | return false 128 | } 129 | 130 | netErr, ok := errors.Cause(err).(net.Error) 131 | return ok && netErr.Timeout() 132 | } 133 | 134 | func isGRPCTimeout(err error) bool { 135 | s, ok := grpcstatus.FromError(errors.Cause(err)) 136 | return ok && s.Code() == codes.DeadlineExceeded 137 | } 138 | -------------------------------------------------------------------------------- /pkg/influx/errors_test.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "net/http/httptest" 8 | "strings" 9 | "testing" 10 | 11 | "github.com/go-kit/log" 12 | "github.com/grafana/mimir-graphite/v2/pkg/errorx" 13 | "github.com/grafana/mimir-graphite/v2/pkg/remotewrite/remotewritemock" 14 | "github.com/stretchr/testify/require" 15 | ) 16 | 17 | func TestHandleError(t *testing.T) { 18 | tests := map[string]struct { 19 | req *http.Request 20 | err error 21 | expectedStatus int 22 | recorderMock func() *MockRecorder 23 | }{ 24 | "bad request": { 25 | req: httptest.NewRequest("GET", "/write", strings.NewReader("")), 26 | err: errorx.BadRequest{Msg: "test", Err: fmt.Errorf("new test error")}, 27 | expectedStatus: http.StatusBadRequest, 28 | recorderMock: func() *MockRecorder { 29 | recorderMock := &MockRecorder{} 30 | recorderMock.On("measureProxyErrors", "errorx.BadRequest").Return(nil) 31 | return recorderMock 32 | }, 33 | }, 34 | "context canceled": { 35 | req: httptest.NewRequest("GET", "/write", strings.NewReader("")), 36 | err: context.Canceled, 37 | expectedStatus: http.StatusInternalServerError, 38 | recorderMock: func() *MockRecorder { 39 | recorderMock := &MockRecorder{} 40 | recorderMock.On("measureProxyErrors", "*errors.errorString").Return(nil) 41 | return recorderMock 42 | }, 43 | }, 44 | "deadline exceeded": { 45 | req: httptest.NewRequest("GET", "/write", strings.NewReader("")), 46 | err: context.DeadlineExceeded, 47 | expectedStatus: http.StatusGatewayTimeout, 48 | recorderMock: func() *MockRecorder { 49 | recorderMock := &MockRecorder{} 50 | recorderMock.On("measureProxyErrors", "context.deadlineExceededError").Return(nil) 51 | return recorderMock 52 | }, 53 | }, 54 | "network timeout": { 55 | req: httptest.NewRequest("GET", "/write", &mockReader{&mockNetworkError{}}), 56 | err: &mockNetworkError{}, 57 | expectedStatus: http.StatusRequestTimeout, 58 | recorderMock: func() *MockRecorder { 59 | recorderMock := &MockRecorder{} 60 | recorderMock.On("measureProxyErrors", "*influx.mockNetworkError").Return(nil) 61 | return recorderMock 62 | }, 63 | }, 64 | "network timeout with body": { 65 | req: httptest.NewRequest("GET", "/write", strings.NewReader("body")), 66 | err: &mockNetworkError{}, 67 | expectedStatus: http.StatusGatewayTimeout, 68 | recorderMock: func() *MockRecorder { 69 | recorderMock := &MockRecorder{} 70 | recorderMock.On("measureProxyErrors", "*influx.mockNetworkError").Return(nil) 71 | return recorderMock 72 | }, 73 | }, 74 | "default error": { 75 | req: httptest.NewRequest("GET", "/write", strings.NewReader("")), 76 | err: fmt.Errorf("default error"), 77 | expectedStatus: http.StatusInternalServerError, 78 | recorderMock: func() *MockRecorder { 79 | recorderMock := &MockRecorder{} 80 | recorderMock.On("measureProxyErrors", "*errors.errorString").Return(nil) 81 | return recorderMock 82 | }, 83 | }, 84 | } 85 | 86 | for name, tt := range tests { 87 | t.Run(name, func(t *testing.T) { 88 | recorder := httptest.NewRecorder() 89 | remoteWriteMock := &remotewritemock.Client{} 90 | conf := ProxyConfig{ 91 | Logger: log.NewNopLogger(), 92 | } 93 | api, err := NewAPI(conf, remoteWriteMock, tt.recorderMock()) 94 | require.NoError(t, err) 95 | 96 | api.handleError(recorder, tt.req, tt.err, api.logger) 97 | require.Equal(t, tt.expectedStatus, recorder.Code) 98 | }) 99 | } 100 | } 101 | 102 | func TestErrorxToInfluxErrorCode(t *testing.T) { 103 | tests := map[string]struct { 104 | err errorx.Error 105 | expectCode string 106 | }{ 107 | "bad request": { 108 | err: errorx.BadRequest{}, 109 | expectCode: EInvalid, 110 | }, 111 | "conflict": { 112 | err: errorx.Conflict{}, 113 | expectCode: EConflict, 114 | }, 115 | "internal": { 116 | err: errorx.Internal{}, 117 | expectCode: EInternal, 118 | }, 119 | "non-mapped error defaults to internal": { 120 | err: errorx.TooManyRequests{}, 121 | expectCode: EInternal, 122 | }, 123 | } 124 | 125 | for name, tt := range tests { 126 | t.Run(name, func(t *testing.T) { 127 | require.Equal(t, tt.expectCode, errorxToInfluxErrorCode(tt.err)) 128 | }) 129 | } 130 | } 131 | 132 | // Mock of Golang's internal poll.TimeoutError 133 | type mockNetworkError struct{} 134 | 135 | func (e *mockNetworkError) Error() string { return "network error" } 136 | func (e *mockNetworkError) Timeout() bool { return true } 137 | func (e *mockNetworkError) Temporary() bool { return true } 138 | 139 | type mockReader struct { 140 | err error 141 | } 142 | 143 | func (r *mockReader) Read(_ []byte) (int, error) { 144 | return 0, r.err 145 | } 146 | -------------------------------------------------------------------------------- /pkg/influx/mock_recorder_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v2.10.2. DO NOT EDIT. 2 | 3 | package influx 4 | 5 | import ( 6 | time "time" 7 | 8 | mock "github.com/stretchr/testify/mock" 9 | ) 10 | 11 | // MockRecorder is an autogenerated mock type for the Recorder type 12 | type MockRecorder struct { 13 | mock.Mock 14 | } 15 | 16 | // RegisterVersionBuildTimestamp provides a mock function with given fields: 17 | func (_m *MockRecorder) RegisterVersionBuildTimestamp() error { 18 | ret := _m.Called() 19 | 20 | var r0 error 21 | if rf, ok := ret.Get(0).(func() error); ok { 22 | r0 = rf() 23 | } else { 24 | r0 = ret.Error(0) 25 | } 26 | 27 | return r0 28 | } 29 | 30 | // measureConversionDuration provides a mock function with given fields: duration 31 | func (_m *MockRecorder) measureConversionDuration(duration time.Duration) { 32 | _m.Called(duration) 33 | } 34 | 35 | // measureMetricsParsed provides a mock function with given fields: count 36 | func (_m *MockRecorder) measureMetricsParsed(count int) { 37 | _m.Called(count) 38 | } 39 | 40 | // measureMetricsWritten provides a mock function with given fields: count 41 | func (_m *MockRecorder) measureMetricsWritten(count int) { 42 | _m.Called(count) 43 | } 44 | 45 | // measureProxyErrors provides a mock function with given fields: reason 46 | func (_m *MockRecorder) measureProxyErrors(reason string) { 47 | _m.Called(reason) 48 | } 49 | -------------------------------------------------------------------------------- /pkg/influx/parser.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "compress/gzip" 5 | "context" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "sort" 10 | "time" 11 | 12 | "github.com/grafana/mimir-graphite/v2/pkg/errorx" 13 | "github.com/grafana/mimir/pkg/mimirpb" 14 | "github.com/grafana/mimir/pkg/util" 15 | io2 "github.com/influxdata/influxdb/v2/kit/io" 16 | "github.com/influxdata/influxdb/v2/models" 17 | "github.com/prometheus/prometheus/model/labels" 18 | ) 19 | 20 | const internalLabel = "__proxy_source__" 21 | 22 | // parseInfluxLineReader parses a Influx Line Protocol request from an io.Reader. 23 | func parseInfluxLineReader(ctx context.Context, r *http.Request, maxSize int) ([]mimirpb.TimeSeries, int, error) { 24 | qp := r.URL.Query() 25 | precision := qp.Get("precision") 26 | if precision == "" { 27 | precision = "ns" 28 | } 29 | 30 | if !models.ValidPrecision(precision) { 31 | return nil, 0, errorx.BadRequest{Msg: fmt.Sprintf("precision supplied is not valid: %s", precision)} 32 | } 33 | 34 | encoding := r.Header.Get("Content-Encoding") 35 | reader, err := batchReadCloser(r.Body, encoding, int64(maxSize)) 36 | if err != nil { 37 | return nil, 0, errorx.BadRequest{Msg: "gzip compression error", Err: err} 38 | } 39 | data, err := io.ReadAll(reader) 40 | dataLen := len(data) // In case it something is read despite an error 41 | if err != nil { 42 | return nil, dataLen, errorx.BadRequest{Msg: "can't read body", Err: err} 43 | } 44 | 45 | err = reader.Close() 46 | if err != nil { 47 | return nil, dataLen, errorx.BadRequest{Msg: "problem reading body", Err: err} 48 | } 49 | 50 | points, err := models.ParsePointsWithPrecision(data, time.Now().UTC(), precision) 51 | if err != nil { 52 | return nil, dataLen, errorx.BadRequest{Msg: "error parsing points", Err: err} 53 | } 54 | a, b := writeRequestFromInfluxPoints(points) 55 | return a, dataLen, b 56 | } 57 | 58 | func writeRequestFromInfluxPoints(points []models.Point) ([]mimirpb.TimeSeries, error) { 59 | // Technically the same series should not be repeated. We should put all the samples for 60 | // a series in single client.Timeseries. Having said that doing it is not very optimal and the 61 | // occurrence of multiple timestamps for the same series is rare. Only reason I see it happening is 62 | // for backfilling and this is not the API for that. Keeping that in mind, we are going to create a new 63 | // client.Timeseries for each sample. 64 | 65 | returnTs := []mimirpb.TimeSeries{} 66 | for _, pt := range points { 67 | ts, err := influxPointToTimeseries(pt) 68 | if err != nil { 69 | return nil, err 70 | } 71 | returnTs = append(returnTs, ts...) 72 | } 73 | 74 | return returnTs, nil 75 | } 76 | 77 | // Points to Prometheus is heavily inspired from https://github.com/prometheus/influxdb_exporter/blob/a1dc16ad596a990d8854545ea39a57a99a3c7c43/main.go#L148-L211 78 | func influxPointToTimeseries(pt models.Point) ([]mimirpb.TimeSeries, error) { 79 | returnTs := []mimirpb.TimeSeries{} 80 | 81 | fields, err := pt.Fields() 82 | if err != nil { 83 | return nil, errorx.Internal{Msg: "error getting fields from point", Err: err} 84 | } 85 | for field, v := range fields { 86 | var value float64 87 | switch v := v.(type) { 88 | case float64: 89 | value = v 90 | case int64: 91 | value = float64(v) 92 | case bool: 93 | if v { 94 | value = 1 95 | } else { 96 | value = 0 97 | } 98 | default: 99 | continue 100 | } 101 | 102 | name := string(pt.Name()) + "_" + field 103 | if field == "value" { 104 | name = string(pt.Name()) 105 | } 106 | replaceInvalidChars(&name) 107 | 108 | tags := pt.Tags() 109 | lbls := make([]mimirpb.LabelAdapter, 0, len(tags)+2) // An additional one for __name__, and one for internal label 110 | lbls = append(lbls, mimirpb.LabelAdapter{ 111 | Name: labels.MetricName, 112 | Value: name, 113 | }) 114 | lbls = append(lbls, mimirpb.LabelAdapter{ 115 | Name: internalLabel, // An internal label for tracking active series 116 | Value: "influx", 117 | }) 118 | for _, tag := range tags { 119 | key := string(tag.Key) 120 | if key == "__name__" || key == internalLabel { 121 | continue 122 | } 123 | replaceInvalidChars(&key) 124 | lbls = append(lbls, mimirpb.LabelAdapter{ 125 | Name: key, 126 | Value: string(tag.Value), 127 | }) 128 | } 129 | sort.Slice(lbls, func(i, j int) bool { 130 | return lbls[i].Name < lbls[j].Name 131 | }) 132 | 133 | returnTs = append(returnTs, mimirpb.TimeSeries{ 134 | Labels: lbls, 135 | Samples: []mimirpb.Sample{{ 136 | TimestampMs: util.TimeToMillis(pt.Time()), 137 | Value: value, 138 | }}, 139 | }) 140 | } 141 | 142 | return returnTs, nil 143 | } 144 | 145 | // analog of invalidChars = regexp.MustCompile("[^a-zA-Z0-9_]") 146 | func replaceInvalidChars(in *string) { 147 | for charIndex, char := range *in { 148 | charInt := int(char) 149 | //nolint:staticcheck 150 | if !((charInt >= 'a' && charInt <= 'z') || // a-z 151 | (charInt >= 'A' && charInt <= 'Z') || // A-Z 152 | (charInt >= '0' && charInt <= '9') || // 0-9 153 | charInt == '_') { // _ 154 | 155 | *in = (*in)[:charIndex] + "_" + (*in)[charIndex+1:] 156 | } 157 | } 158 | // prefix with _ if first char is 0-9 159 | if len(*in) > 0 && int((*in)[0]) >= '0' && int((*in)[0]) <= '9' { 160 | *in = "_" + *in 161 | } 162 | } 163 | 164 | // batchReadCloser (potentially) wraps an io.ReadCloser in Gzip 165 | // decompression and limits the reading to a specific number of bytes. 166 | func batchReadCloser(rc io.ReadCloser, encoding string, maxBatchSizeBytes int64) (io.ReadCloser, error) { 167 | switch encoding { 168 | case "gzip", "x-gzip": 169 | var err error 170 | rc, err = gzip.NewReader(rc) 171 | if err != nil { 172 | return nil, err 173 | } 174 | } 175 | if maxBatchSizeBytes > 0 { 176 | rc = io2.NewLimitedReadCloser(rc, maxBatchSizeBytes) 177 | } 178 | return rc, nil 179 | } 180 | -------------------------------------------------------------------------------- /pkg/influx/parser_test.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "net/http/httptest" 7 | "sort" 8 | "testing" 9 | 10 | "github.com/grafana/mimir-graphite/v2/pkg/errorx" 11 | "github.com/grafana/mimir/pkg/mimirpb" 12 | "github.com/stretchr/testify/assert" 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | const maxSize = 100 << 10 17 | 18 | func TestParseInfluxLineReader(t *testing.T) { 19 | tests := []struct { 20 | name string 21 | url string 22 | data string 23 | expectedResult []mimirpb.TimeSeries 24 | }{ 25 | { 26 | name: "parse simple line single value called value", 27 | url: "/", 28 | data: "measurement,t1=v1 value=1.5 1465839830100400200", 29 | expectedResult: []mimirpb.TimeSeries{ 30 | { 31 | Labels: []mimirpb.LabelAdapter{ 32 | {Name: "__name__", Value: "measurement"}, 33 | {Name: "__proxy_source__", Value: "influx"}, 34 | {Name: "t1", Value: "v1"}, 35 | }, 36 | Samples: []mimirpb.Sample{{Value: 1.5, TimestampMs: 1465839830100}}, 37 | }, 38 | }, 39 | }, 40 | { 41 | name: "parse simple line single value", 42 | url: "/", 43 | data: "measurement,t1=v1 f1=2 1465839830100400200", 44 | expectedResult: []mimirpb.TimeSeries{ 45 | { 46 | Labels: []mimirpb.LabelAdapter{ 47 | {Name: "__name__", Value: "measurement_f1"}, 48 | {Name: "__proxy_source__", Value: "influx"}, 49 | {Name: "t1", Value: "v1"}, 50 | }, 51 | Samples: []mimirpb.Sample{{Value: 2, TimestampMs: 1465839830100}}, 52 | }, 53 | }, 54 | }, 55 | { 56 | name: "parse simple line single float value", 57 | url: "/", 58 | data: "measurement,t1=v1 f1=3.14159 1465839830100400200", 59 | expectedResult: []mimirpb.TimeSeries{ 60 | { 61 | Labels: []mimirpb.LabelAdapter{ 62 | {Name: "__name__", Value: "measurement_f1"}, 63 | {Name: "__proxy_source__", Value: "influx"}, 64 | {Name: "t1", Value: "v1"}, 65 | }, 66 | Samples: []mimirpb.Sample{{Value: 3.14159, TimestampMs: 1465839830100}}, 67 | }, 68 | }, 69 | }, 70 | { 71 | name: "parse simple line multiple int/float values", 72 | url: "/", 73 | data: "measurement,t1=v1 f1=2,f2=3i,f3=3.14159 1465839830100400200", 74 | expectedResult: []mimirpb.TimeSeries{ 75 | { 76 | Labels: []mimirpb.LabelAdapter{ 77 | {Name: "__name__", Value: "measurement_f1"}, 78 | {Name: "__proxy_source__", Value: "influx"}, 79 | {Name: "t1", Value: "v1"}, 80 | }, 81 | Samples: []mimirpb.Sample{{Value: 2, TimestampMs: 1465839830100}}, 82 | }, 83 | { 84 | Labels: []mimirpb.LabelAdapter{ 85 | {Name: "__name__", Value: "measurement_f2"}, 86 | {Name: "__proxy_source__", Value: "influx"}, 87 | {Name: "t1", Value: "v1"}, 88 | }, 89 | Samples: []mimirpb.Sample{{Value: 3, TimestampMs: 1465839830100}}, 90 | }, 91 | { 92 | Labels: []mimirpb.LabelAdapter{ 93 | {Name: "__name__", Value: "measurement_f3"}, 94 | {Name: "__proxy_source__", Value: "influx"}, 95 | {Name: "t1", Value: "v1"}, 96 | }, 97 | Samples: []mimirpb.Sample{{Value: 3.14159, TimestampMs: 1465839830100}}, 98 | }, 99 | }, 100 | }, 101 | { 102 | name: "parse simple line ignoring string value", 103 | url: "/", 104 | data: "measurement,t1=v1 f1=2,f2=\"val2\" 1465839830100400200", 105 | expectedResult: []mimirpb.TimeSeries{ 106 | { 107 | Labels: []mimirpb.LabelAdapter{ 108 | {Name: "__name__", Value: "measurement_f1"}, 109 | {Name: "__proxy_source__", Value: "influx"}, 110 | {Name: "t1", Value: "v1"}, 111 | }, 112 | Samples: []mimirpb.Sample{{Value: 2, TimestampMs: 1465839830100}}, 113 | }, 114 | // We don't produce a result for the f2="val2" field set 115 | }, 116 | }, 117 | { 118 | name: "parse multiple tags", 119 | url: "/", 120 | data: "measurement,t1=v1,t2=v2,t3=v3 f1=36 1465839830100400200", 121 | expectedResult: []mimirpb.TimeSeries{ 122 | { 123 | Labels: []mimirpb.LabelAdapter{ 124 | {Name: "__name__", Value: "measurement_f1"}, 125 | {Name: "__proxy_source__", Value: "influx"}, 126 | {Name: "t1", Value: "v1"}, 127 | {Name: "t2", Value: "v2"}, 128 | {Name: "t3", Value: "v3"}, 129 | }, 130 | Samples: []mimirpb.Sample{{Value: 36, TimestampMs: 1465839830100}}, 131 | }, 132 | }, 133 | }, 134 | { 135 | name: "parse multiple fields", 136 | url: "/", 137 | data: "measurement,t1=v1 f1=3.0,f2=365,f3=0 1465839830100400200", 138 | expectedResult: []mimirpb.TimeSeries{ 139 | { 140 | Labels: []mimirpb.LabelAdapter{ 141 | {Name: "__name__", Value: "measurement_f1"}, 142 | {Name: "__proxy_source__", Value: "influx"}, 143 | {Name: "t1", Value: "v1"}, 144 | }, 145 | Samples: []mimirpb.Sample{{Value: 3, TimestampMs: 1465839830100}}, 146 | }, 147 | { 148 | Labels: []mimirpb.LabelAdapter{ 149 | {Name: "__name__", Value: "measurement_f2"}, 150 | {Name: "__proxy_source__", Value: "influx"}, 151 | {Name: "t1", Value: "v1"}, 152 | }, 153 | Samples: []mimirpb.Sample{{Value: 365, TimestampMs: 1465839830100}}, 154 | }, 155 | { 156 | Labels: []mimirpb.LabelAdapter{ 157 | {Name: "__name__", Value: "measurement_f3"}, 158 | {Name: "__proxy_source__", Value: "influx"}, 159 | {Name: "t1", Value: "v1"}, 160 | }, 161 | Samples: []mimirpb.Sample{{Value: 0, TimestampMs: 1465839830100}}, 162 | }, 163 | }, 164 | }, 165 | { 166 | name: "parse invalid char conversion", 167 | url: "/", 168 | data: "*measurement,#t1?=v1 f#1=0 1465839830100400200", 169 | expectedResult: []mimirpb.TimeSeries{ 170 | { 171 | Labels: []mimirpb.LabelAdapter{ 172 | {Name: "__name__", Value: "_measurement_f_1"}, 173 | {Name: "__proxy_source__", Value: "influx"}, 174 | {Name: "_t1_", Value: "v1"}, 175 | }, 176 | Samples: []mimirpb.Sample{{Value: 0, TimestampMs: 1465839830100}}, 177 | }, 178 | }, 179 | }, 180 | { 181 | name: "parse invalid char conversion number prefix", 182 | url: "/", 183 | data: "0measurement,1t1=v1 f1=0 1465839830100400200", 184 | expectedResult: []mimirpb.TimeSeries{ 185 | { 186 | Labels: []mimirpb.LabelAdapter{ 187 | {Name: "_1t1", Value: "v1"}, 188 | {Name: "__name__", Value: "_0measurement_f1"}, 189 | {Name: "__proxy_source__", Value: "influx"}, 190 | }, 191 | Samples: []mimirpb.Sample{{Value: 0, TimestampMs: 1465839830100}}, 192 | }, 193 | }, 194 | }, 195 | } 196 | 197 | for _, tt := range tests { 198 | t.Run(tt.name, func(t *testing.T) { 199 | req := httptest.NewRequest("POST", tt.url, bytes.NewReader([]byte(tt.data))) 200 | 201 | timeSeries, _, err := parseInfluxLineReader(context.Background(), req, maxSize) 202 | require.NoError(t, err) 203 | 204 | if len(timeSeries) > 1 { 205 | // sort the returned timeSeries results in guarantee expected order for comparison 206 | sort.Slice(timeSeries, func(i, j int) bool { 207 | return timeSeries[i].String() < timeSeries[j].String() 208 | }) 209 | } 210 | 211 | // Ensure we are getting the expected number of results 212 | assert.Equal(t, len(timeSeries), len(tt.expectedResult)) 213 | 214 | // Compare them one by one 215 | for i := 0; i < len(timeSeries); i++ { 216 | assert.Equal(t, timeSeries[i].String(), tt.expectedResult[i].String()) 217 | } 218 | }) 219 | } 220 | } 221 | 222 | func TestInvalidInput(t *testing.T) { 223 | tests := []struct { 224 | name string 225 | url string 226 | data string 227 | errorType error 228 | }{ 229 | { 230 | name: "parse invalid precision", 231 | url: "/write?precision=ss", // precision must be of type "ns", "us", "ms", "s" 232 | data: "measurement,t1=v1 f1=2 1465839830100400200", 233 | errorType: &errorx.BadRequest{}, 234 | }, 235 | { 236 | name: "parse invalid field input", 237 | url: "/write", 238 | data: "measurement,t1=v1 f1= 1465839830100400200", // field value is missing 239 | errorType: &errorx.BadRequest{}, 240 | }, 241 | { 242 | name: "parse invalid tags", 243 | url: "/write", 244 | data: "measurement,t1=v1,t2 f1=2 1465839830100400200", // field value is missing 245 | errorType: &errorx.BadRequest{}, 246 | }, 247 | { 248 | name: "parse field value invalid quotes", 249 | url: "/write", 250 | data: "measurement,t1=v1 f1=v1 1465839830100400200", // string type field values require double quotes 251 | errorType: &errorx.BadRequest{}, 252 | }, 253 | { 254 | name: "parse missing field", 255 | url: "/write", 256 | data: "measurement,t1=v1 1465839830100400200", // missing field 257 | errorType: &errorx.BadRequest{}, 258 | }, 259 | } 260 | 261 | for _, tt := range tests { 262 | t.Run(tt.name, func(t *testing.T) { 263 | req := httptest.NewRequest("POST", tt.url, bytes.NewReader([]byte(tt.data))) 264 | 265 | _, _, err := parseInfluxLineReader(context.Background(), req, maxSize) 266 | require.Error(t, err) 267 | assert.ErrorAs(t, err, tt.errorType) 268 | }) 269 | } 270 | } 271 | 272 | func TestBatchReadCloser(t *testing.T) { 273 | req := httptest.NewRequest("POST", "/write", bytes.NewReader([]byte("m,t1=v1 f1=2 1465839830100400200"))) 274 | req.Header.Add("Content-Encoding", "gzip") 275 | 276 | _, err := batchReadCloser(req.Body, "gzip", int64(maxSize)) 277 | require.Error(t, err) 278 | } 279 | -------------------------------------------------------------------------------- /pkg/influx/proxy.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "context" 5 | "flag" 6 | "fmt" 7 | "net" 8 | "os" 9 | 10 | "github.com/go-kit/log" 11 | "github.com/gorilla/mux" 12 | "github.com/grafana/dskit/services" 13 | "github.com/grafana/mimir-graphite/v2/pkg/appcommon" 14 | "github.com/grafana/mimir-graphite/v2/pkg/remotewrite" 15 | "github.com/grafana/mimir-graphite/v2/pkg/server" 16 | "github.com/grafana/mimir-graphite/v2/pkg/server/middleware" 17 | "github.com/prometheus/client_golang/prometheus" 18 | ) 19 | 20 | const ( 21 | // Upped to 10MB based on empirical evidence of proxy receiving batches from telegraf agent 22 | DefaultMaxRequestSizeBytes = 10 << 20 // 10 MB 23 | serviceName = "influx-write-proxy" 24 | ) 25 | 26 | // ProxyConfig holds objects needed to start running an influx2cortex proxy 27 | // server. 28 | type ProxyConfig struct { 29 | // HTTPConfig is the configuration for the underlying http server. Usually 30 | // initialized by flag values via flagext.RegisterFlags. 31 | HTTPConfig server.Config 32 | // RemoteWriteConfig is the configuration for the underlying remote write client. Usually 33 | // initialized by flag values via flagext.RegisterFlags. 34 | RemoteWriteConfig remotewrite.Config 35 | // EnableAuth determines if the server will reject incoming requests that do 36 | // not have X-Scope-OrgID set. 37 | EnableAuth bool 38 | // Logger is the object that will do the logging for the server. If nil, will 39 | // use a LogfmtLogger on stdout. 40 | Logger log.Logger 41 | // Registerer registers metrics Collectors. If left nil, will use 42 | // prometheus.DefaultRegisterer. 43 | Registerer prometheus.Registerer 44 | // MaxRequestSizeBytes limits the size of an incoming request. Any value less than or equal to 0 means no limit. 45 | MaxRequestSizeBytes int 46 | } 47 | 48 | func (c *ProxyConfig) RegisterFlags(flags *flag.FlagSet) { 49 | c.HTTPConfig.RegisterFlags(flags) 50 | c.RemoteWriteConfig.RegisterFlags(flags) 51 | 52 | flags.BoolVar(&c.EnableAuth, "auth.enable", true, "require X-Scope-OrgId header") 53 | flags.IntVar(&c.MaxRequestSizeBytes, "max.request.size.bytes", DefaultMaxRequestSizeBytes, "limit the size of incoming batches; 0 for no limit") 54 | } 55 | 56 | // ProxyService is the actual Influx Proxy dskit service. 57 | type ProxyService struct { 58 | services.Service 59 | 60 | logger log.Logger 61 | 62 | config ProxyConfig 63 | server *server.Server 64 | errChan chan error 65 | 66 | tracerCloser func() error 67 | } 68 | 69 | // NewProxy creates a new remotewrite client 70 | func NewProxy(conf ProxyConfig) (*ProxyService, error) { 71 | if conf.Registerer == nil { 72 | conf.Registerer = prometheus.DefaultRegisterer 73 | } 74 | remoteWriteRecorder := remotewrite.NewRecorder("influx_proxy", conf.Registerer) 75 | client, err := remotewrite.NewClient(conf.RemoteWriteConfig, remoteWriteRecorder, nil) 76 | if err != nil { 77 | return nil, fmt.Errorf("failed to create remotewrite.API: %w", err) 78 | } 79 | 80 | return newProxyWithClient(conf, client) 81 | } 82 | 83 | // newProxyWithClient creates the influx API server with the given config options and 84 | // the specified remotewrite client. It returns the HTTP server that is ready to Run. 85 | func newProxyWithClient(conf ProxyConfig, client remotewrite.Client) (*ProxyService, error) { 86 | if conf.Logger == nil { 87 | conf.Logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) 88 | } 89 | 90 | recorder := NewRecorder(conf.Registerer) 91 | router := mux.NewRouter() 92 | 93 | var authMiddleware middleware.Interface 94 | if conf.EnableAuth { 95 | authMiddleware = middleware.NewHTTPAuth(conf.Logger) 96 | } else { 97 | authMiddleware = middleware.HTTPFakeAuth{} 98 | } 99 | 100 | tracer, tracerCloser, err := appcommon.NewTracer(serviceName, conf.Logger) 101 | if err != nil { 102 | return nil, err 103 | } 104 | tracerMiddleware := middleware.NewTracer(router, tracer) 105 | 106 | // Middlewares will be wrapped in order 107 | middlewares := []middleware.Interface{ 108 | tracerMiddleware, 109 | authMiddleware, 110 | } 111 | 112 | server, err := server.NewServer(conf.Logger, conf.HTTPConfig, router, middlewares) 113 | if err != nil { 114 | return nil, fmt.Errorf("failed to create http server: %w", err) 115 | } 116 | 117 | api, err := NewAPI(conf, client, recorder) 118 | if err != nil { 119 | return nil, fmt.Errorf("failed to create influx API: %w", err) 120 | } 121 | 122 | api.Register(server.Router) 123 | err = recorder.RegisterVersionBuildTimestamp() 124 | if err != nil { 125 | return nil, fmt.Errorf("could not register version build timestamp: %w", err) 126 | } 127 | 128 | p := &ProxyService{ 129 | logger: conf.Logger, 130 | config: conf, 131 | server: server, 132 | errChan: make(chan error, 1), 133 | tracerCloser: tracerCloser.Close, 134 | } 135 | p.Service = services.NewBasicService(p.start, p.run, p.stop).WithName(serviceName) 136 | return p, nil 137 | } 138 | 139 | // Addr returns the net.Addr for the configured server. This is useful in case 140 | // it was started with port auto-selection so the port number can be retrieved. 141 | func (p *ProxyService) Addr() net.Addr { 142 | return p.server.Addr() 143 | } 144 | 145 | func (p *ProxyService) start(_ context.Context) error { 146 | // the server does not listen for context canceling, so we have to start it 147 | // in a goroutine so we can listen for both. 148 | go func() { 149 | err := p.server.Run() 150 | p.errChan <- err 151 | }() 152 | 153 | return nil 154 | } 155 | 156 | func (p *ProxyService) run(servCtx context.Context) error { 157 | for { 158 | select { 159 | case <-servCtx.Done(): 160 | return servCtx.Err() 161 | case err := <-p.errChan: 162 | return err 163 | } 164 | } 165 | } 166 | 167 | func (p *ProxyService) stop(_ error) error { 168 | p.server.Shutdown(nil) 169 | return p.tracerCloser() 170 | } 171 | -------------------------------------------------------------------------------- /pkg/influx/recorder.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "time" 7 | 8 | "github.com/grafana/dskit/instrument" 9 | "github.com/prometheus/client_golang/prometheus" 10 | ) 11 | 12 | const ( 13 | prefix = "influxdb_proxy_ingester" 14 | ) 15 | 16 | var ( 17 | CommitUnixTimestamp = "0" 18 | DockerTag = "unset" 19 | ) 20 | 21 | //go:generate mockery --inpackage --testonly --case underscore --name Recorder 22 | type Recorder interface { 23 | measureMetricsParsed(count int) 24 | measureMetricsWritten(count int) 25 | measureProxyErrors(reason string) 26 | measureConversionDuration(duration time.Duration) 27 | RegisterVersionBuildTimestamp() error 28 | } 29 | 30 | func NewRecorder(reg prometheus.Registerer) Recorder { 31 | r := &prometheusRecorder{ 32 | proxyMetricsParsed: prometheus.NewCounterVec(prometheus.CounterOpts{ 33 | Namespace: prefix, 34 | Name: "metrics_parsed_total", 35 | Help: "The total number of metrics that have been parsed.", 36 | }, []string{}), 37 | proxyErrors: prometheus.NewCounterVec(prometheus.CounterOpts{ 38 | Namespace: prefix, 39 | Name: "proxy_errors_total", 40 | Help: "The total number of errors, sliced by the go error type returned.", 41 | }, []string{"reason"}), 42 | proxyMetricsWritten: prometheus.NewCounterVec(prometheus.CounterOpts{ 43 | Namespace: prefix, 44 | Name: "metrics_written_total", 45 | Help: "The total number of metrics that have been written.", 46 | }, []string{}), 47 | conversionDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ 48 | Namespace: prefix, 49 | Name: "data_conversion_seconds", 50 | Help: "Time (in seconds) spent converting ingested InfluxDB data into Prometheus data.", 51 | Buckets: instrument.DefBuckets, 52 | }, []string{}), 53 | buildDateGauge: prometheus.NewGauge(prometheus.GaugeOpts{ 54 | Namespace: prefix, 55 | Name: "build_unix_timestamp", 56 | Help: "A constant build date value reported by each instance as a Unix epoch timestamp", 57 | ConstLabels: prometheus.Labels{"docker_tag": DockerTag}, 58 | }), 59 | } 60 | 61 | reg.MustRegister(r.proxyMetricsParsed, r.proxyMetricsWritten, r.proxyErrors, r.conversionDuration, r.buildDateGauge) 62 | 63 | return r 64 | } 65 | 66 | // prometheusRecorder knows the metrics of the ingester and how to measure them for 67 | // Prometheus. 68 | type prometheusRecorder struct { 69 | proxyMetricsParsed *prometheus.CounterVec 70 | proxyMetricsWritten *prometheus.CounterVec 71 | proxyErrors *prometheus.CounterVec 72 | conversionDuration *prometheus.HistogramVec 73 | buildDateGauge prometheus.Gauge 74 | } 75 | 76 | // measureMetricsParsed measures the total amount of metrics parsed by the proxy. 77 | func (r prometheusRecorder) measureMetricsParsed(count int) { 78 | r.proxyMetricsParsed.WithLabelValues().Add(float64(count)) 79 | } 80 | 81 | // measureMetricsParsed measures the total amount of metrics written. 82 | func (r prometheusRecorder) measureMetricsWritten(count int) { 83 | r.proxyMetricsWritten.WithLabelValues().Add(float64(count)) 84 | } 85 | 86 | // measureProxyErrors measures the total amount of errors encountered. 87 | func (r prometheusRecorder) measureProxyErrors(reason string) { 88 | r.proxyErrors.WithLabelValues(reason).Add(1) 89 | } 90 | 91 | // measureConversionDuration measures the total time spent translating points to Prometheus format 92 | func (r prometheusRecorder) measureConversionDuration(duration time.Duration) { 93 | r.conversionDuration.WithLabelValues().Observe(duration.Seconds()) 94 | } 95 | 96 | func (r prometheusRecorder) RegisterVersionBuildTimestamp() error { 97 | parsedCommitTimestamp, err := strconv.ParseFloat(CommitUnixTimestamp, 64) 98 | if err != nil { 99 | return fmt.Errorf("could not parse CommitUnixTimestamp: %w", err) 100 | } 101 | 102 | r.buildDateGauge.Set(parsedCommitTimestamp) 103 | 104 | return nil 105 | } 106 | -------------------------------------------------------------------------------- /pkg/influx/recorder_test.go: -------------------------------------------------------------------------------- 1 | package influx 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | "time" 7 | 8 | "github.com/prometheus/client_golang/prometheus" 9 | "github.com/prometheus/client_golang/prometheus/testutil" 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func TestRecorder(t *testing.T) { 14 | CommitUnixTimestamp = "1649113429" 15 | DockerTag = "docker:tag" 16 | 17 | reg := prometheus.NewRegistry() 18 | rec := NewRecorder(reg) 19 | 20 | tests := map[string]struct { 21 | measure func(r Recorder) 22 | expMetricNames []string 23 | expMetrics string 24 | }{ 25 | "Measure incoming points": { 26 | measure: func(r Recorder) { 27 | r.measureMetricsParsed(3) 28 | }, 29 | expMetricNames: []string{ 30 | "influxdb_proxy_ingester_metrics_parsed_total", 31 | }, 32 | expMetrics: ` 33 | # HELP influxdb_proxy_ingester_metrics_parsed_total The total number of metrics that have been parsed. 34 | # TYPE influxdb_proxy_ingester_metrics_parsed_total counter 35 | influxdb_proxy_ingester_metrics_parsed_total 3 36 | `, 37 | }, 38 | "Measure rejected samples": { 39 | measure: func(r Recorder) { 40 | r.measureProxyErrors("reason") 41 | }, 42 | expMetricNames: []string{ 43 | "influxdb_proxy_ingester_proxy_errors_total", 44 | }, 45 | expMetrics: ` 46 | # HELP influxdb_proxy_ingester_proxy_errors_total The total number of errors, sliced by the go error type returned. 47 | # TYPE influxdb_proxy_ingester_proxy_errors_total counter 48 | influxdb_proxy_ingester_proxy_errors_total{reason="reason"} 1 49 | `, 50 | }, 51 | "Measure written samples": { 52 | measure: func(r Recorder) { 53 | r.measureMetricsWritten(3) 54 | }, 55 | expMetricNames: []string{ 56 | "influxdb_proxy_ingester_metrics_written_total", 57 | }, 58 | expMetrics: ` 59 | # HELP influxdb_proxy_ingester_metrics_written_total The total number of metrics that have been written. 60 | # TYPE influxdb_proxy_ingester_metrics_written_total counter 61 | influxdb_proxy_ingester_metrics_written_total 3 62 | `, 63 | }, 64 | "Measure conversion duration": { 65 | measure: func(r Recorder) { 66 | r.measureConversionDuration(15 * time.Second) 67 | }, 68 | expMetricNames: []string{ 69 | "influxdb_proxy_ingester_data_conversion_seconds", 70 | }, 71 | expMetrics: ` 72 | # HELP influxdb_proxy_ingester_data_conversion_seconds Time (in seconds) spent converting ingested InfluxDB data into Prometheus data. 73 | # TYPE influxdb_proxy_ingester_data_conversion_seconds histogram 74 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="0.005"} 0 75 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="0.01"} 0 76 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="0.025"} 0 77 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="0.05"} 0 78 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="0.1"} 0 79 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="0.25"} 0 80 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="0.5"} 0 81 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="1"} 0 82 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="2.5"} 0 83 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="5"} 0 84 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="10"} 0 85 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="25"} 1 86 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="50"} 1 87 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="100"} 1 88 | influxdb_proxy_ingester_data_conversion_seconds_bucket{le="+Inf"} 1 89 | influxdb_proxy_ingester_data_conversion_seconds_sum 15 90 | influxdb_proxy_ingester_data_conversion_seconds_count 1 91 | `, 92 | }, 93 | "Register version build timestamp": { 94 | measure: func(r Recorder) { 95 | _ = r.RegisterVersionBuildTimestamp() 96 | }, 97 | expMetricNames: []string{ 98 | "influxdb_proxy_ingester_build_unix_timestamp", 99 | }, 100 | expMetrics: ` 101 | # HELP influxdb_proxy_ingester_build_unix_timestamp A constant build date value reported by each instance as a Unix epoch timestamp 102 | # TYPE influxdb_proxy_ingester_build_unix_timestamp gauge 103 | influxdb_proxy_ingester_build_unix_timestamp{docker_tag="docker:tag"} 1.649113429e+09 104 | `, 105 | }, 106 | } 107 | 108 | for name, test := range tests { 109 | t.Run(name, func(t *testing.T) { 110 | assert := assert.New(t) 111 | 112 | // Measure metrics 113 | test.measure(rec) 114 | 115 | err := testutil.GatherAndCompare(reg, strings.NewReader(test.expMetrics), test.expMetricNames...) 116 | assert.NoError(err) 117 | }) 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /pkg/internalserver/service.go: -------------------------------------------------------------------------------- 1 | package internalserver 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "flag" 7 | "fmt" 8 | "net/http" 9 | "sync/atomic" 10 | "time" 11 | 12 | "github.com/go-kit/log" 13 | "github.com/go-kit/log/level" 14 | "github.com/grafana/dskit/services" 15 | "github.com/prometheus/client_golang/prometheus/promhttp" 16 | ) 17 | 18 | const ( 19 | DefaultListenAddress = "0.0.0.0" 20 | DefaultListenPort = 8081 21 | DefaultGracefulShutdownTimeout = 5 * time.Second 22 | ) 23 | 24 | type ServiceConfig struct { 25 | HTTPListenAddress string 26 | HTTPListenPort int 27 | GracefulShutdownTimeout time.Duration 28 | } 29 | 30 | func (c *ServiceConfig) RegisterFlags(flags *flag.FlagSet) { 31 | flags.StringVar(&c.HTTPListenAddress, "internalserver.http-listen-address", DefaultListenAddress, "Sets the listen address for the internal http server") 32 | flags.IntVar(&c.HTTPListenPort, "internalserver.http-listen-port", DefaultListenPort, "Sets listen address port for the internal http server") 33 | flags.DurationVar(&c.GracefulShutdownTimeout, "internalserver.graceful-shutdown-timeout", DefaultGracefulShutdownTimeout, "Graceful shutdown period") 34 | } 35 | 36 | type Service struct { 37 | services.Service 38 | 39 | logger log.Logger 40 | 41 | config ServiceConfig 42 | server *http.Server 43 | errChan chan error 44 | ready *atomic.Bool 45 | } 46 | 47 | func NewService(config ServiceConfig, logger log.Logger) (*Service, error) { 48 | if logger == nil { 49 | return nil, errors.New("logger should not be nil") 50 | } 51 | 52 | ready := &atomic.Bool{} 53 | ready.Store(true) 54 | mux := http.NewServeMux() 55 | mux.Handle("/metrics", promhttp.Handler()) 56 | mux.Handle("/healthz", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 57 | if ready.Load() { 58 | w.WriteHeader(http.StatusOK) 59 | _, _ = w.Write([]byte("ok")) 60 | } else { 61 | w.WriteHeader(http.StatusInternalServerError) 62 | _, _ = w.Write([]byte("not ready")) 63 | } 64 | })) 65 | 66 | httpServer := &http.Server{ 67 | Addr: fmt.Sprintf("%s:%d", config.HTTPListenAddress, config.HTTPListenPort), 68 | Handler: mux, 69 | } 70 | 71 | s := &Service{ 72 | logger: logger, 73 | config: config, 74 | server: httpServer, 75 | errChan: make(chan error, 1), 76 | ready: ready, 77 | } 78 | s.Service = services.NewBasicService(s.start, s.run, s.stop).WithName("internal") 79 | 80 | return s, nil 81 | } 82 | 83 | // SetReady sets the response for the health check endpoint. 84 | func (s *Service) SetReady(ready bool) { 85 | s.ready.Store(ready) 86 | } 87 | 88 | func (s *Service) start(_ context.Context) error { 89 | _ = level.Info(s.logger).Log("msg", "Starting internal http server", "addr", s.server.Addr) 90 | 91 | go func() { 92 | err := s.server.ListenAndServe() 93 | s.errChan <- err 94 | }() 95 | 96 | return nil 97 | } 98 | 99 | func (s *Service) run(ctx context.Context) error { 100 | for { 101 | select { 102 | case <-ctx.Done(): 103 | return ctx.Err() 104 | case err := <-s.errChan: 105 | return err 106 | } 107 | } 108 | } 109 | 110 | func (s *Service) stop(failureCase error) error { 111 | ctx, cancel := context.WithTimeout(context.Background(), s.config.GracefulShutdownTimeout) 112 | defer cancel() 113 | 114 | if failureCase != nil && !errors.Is(failureCase, context.Canceled) { 115 | _ = level.Warn(s.logger).Log("msg", "shutting down internal http server due to failure", "failure", failureCase) 116 | } else { 117 | _ = level.Info(s.logger).Log("msg", "shutting down internal http server") 118 | } 119 | 120 | err := s.server.Shutdown(ctx) 121 | if err != nil { 122 | return fmt.Errorf("error during shutdown of internal http server: %w", err) 123 | } 124 | 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /scripts/build-local-images.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Builds docker images for local usage (acceptance testing or local k8s) 3 | set -eufo pipefail 4 | export SHELLOPTS # propagate set to children by default 5 | IFS=$'\t\n' 6 | 7 | echo "Test" 8 | command -v docker >/dev/null 2>&1 || { echo 'Please install docker'; exit 1; } 9 | 10 | # Populate a dummy .tag file for consumption by the Dockerfile 11 | echo "local" > .tag 12 | trap 'rm .tag' EXIT 13 | 14 | echo "# Building docker images" 15 | docker build -f ./Dockerfile -t "us.gcr.io/kubernetes-dev/influx2cortex:local" . -------------------------------------------------------------------------------- /scripts/compile_commands.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Builds command binaries 3 | set -eufo pipefail 4 | export SHELLOPTS # propagate set to children by default 5 | IFS=$'\t\n' 6 | 7 | command -v go >/dev/null 2>&1 || { echo 'Please install go'; exit 1; } 8 | 9 | export GOPRIVATE="" 10 | export CGO_ENABLED=0 11 | export GOOS=linux 12 | export GOARCH=amd64 13 | GIT_COMMIT="${DRONE_COMMIT:-$(git rev-list -1 HEAD)}" 14 | COMMIT_UNIX_TIMESTAMP="$(git --no-pager show -s --format=%ct "${GIT_COMMIT}")" 15 | # DOCKER_TAG="$(bash scripts/docker-tag.sh)" 16 | DOCKER_TAG="TODO" 17 | 18 | # shellcheck disable=SC2043 19 | for cmd in influx2cortex 20 | do 21 | go build \ 22 | -o "dist/${cmd}" \ 23 | -ldflags "\ 24 | -w \ 25 | -X 'github.com/grafana/mimir-graphite/v2/pkg/appcommon.CommitUnixTimestamp=${COMMIT_UNIX_TIMESTAMP}' \ 26 | -X 'github.com/grafana/mimir-graphite/v2/pkg/appcommon.DockerTag=${DOCKER_TAG}' \ 27 | " \ 28 | "github.com/grafana/influx2cortex/cmd/${cmd}" 29 | 30 | echo "Succesfully built ${cmd} into dist/${cmd}" 31 | done 32 | -------------------------------------------------------------------------------- /scripts/generate-tags.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # vim: ai:ts=8:sw=8:noet 3 | # Prints the docker tag as: 4 | # 20210617094655-master-deadbeef # using commit date and changeset when no changes were made 5 | # 20210617094655-master-modified # using current date and the string 'modified' instead of changeset. 6 | # Does not print a newline at the end of output 7 | set -eufo pipefail 8 | export SHELLOPTS # propagate set to children by default 9 | IFS=$'\t\n' 10 | umask 0077 11 | 12 | # In GitHub Actions, GITHUB_HEAD_REF will be set to the PR branch if this is a PR build. 13 | # Otherwise, if it's a push, the branch name will be in GITHUB_REF_NAME. 14 | BRANCH="${DRONE_SOURCE_BRANCH:-${GITHUB_HEAD_REF:-${GITHUB_REF_NAME:-$(git branch --show-current)}}}" 15 | 16 | if git diff-index --quiet HEAD -- 17 | then 18 | if [[ ${DRONE_COMMIT:-unset} != "unset" ]]; 19 | then 20 | GIT_COMMIT="${DRONE_COMMIT}" 21 | >&2 echo "\$DRONE_COMMIT=${DRONE_COMMIT}" 22 | elif [[ ${GITHUB_SHA:-unset} != "unset" ]]; 23 | then 24 | GIT_COMMIT="${GITHUB_SHA}" 25 | >&2 echo "\$GITHUB_SHA=${GITHUB_SHA}" 26 | else 27 | GIT_COMMIT="$(git rev-list -1 HEAD)" 28 | >&2 echo "\$DRONE_COMMIT and GITHUB_SHA are unset, using last git commit $GIT_COMMIT" 29 | fi 30 | # no changes 31 | UNIX_TIMESTAMP=$(git show -s --format=%ct "$GIT_COMMIT") 32 | GIT_COMMIT_SHORT="$(git rev-parse --short "$GIT_COMMIT")" 33 | else 34 | # changes 35 | UNIX_TIMESTAMP=$(date +%s) 36 | GIT_COMMIT_SHORT="modified" 37 | fi 38 | 39 | # date -u --rfc-3339=seconds requires GNU date 40 | # when running this on alpine, run `apk add coreutils` to get it 41 | if [[ ${OSTYPE:-notdarwin} == "darwin"* ]]; then 42 | # For MacOS, we need to use `gdate` for GNU `date`; run `brew install coreutils` to get it 43 | ISO_TIMESTAMP=$(gdate -u --rfc-3339=seconds "-d@${UNIX_TIMESTAMP}" | sed "s/+.*$//g" | sed "s/[^0-9]*//g") 44 | else 45 | ISO_TIMESTAMP=$(date -u --rfc-3339=seconds "-d@${UNIX_TIMESTAMP}" | sed "s/+.*$//g" | sed "s/[^0-9]*//g") 46 | fi 47 | DOCKER_TAG=$(echo "${ISO_TIMESTAMP}-${BRANCH}-${GIT_COMMIT_SHORT}" | tr "/" "_") 48 | echo -n "${DOCKER_TAG}" 49 | -------------------------------------------------------------------------------- /scripts/genprotobuf.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Generate all protobuf bindings. 3 | set -euo pipefail 4 | export SHELLOPTS # propagate set to children by default 5 | IFS=$'\t\n' 6 | umask 0077 7 | 8 | command -v protoc >/dev/null 2>&1 || { echo "protoc not installed, Aborting." >&2; exit 1; } 9 | 10 | if ! [[ "$0" =~ scripts/genprotobuf.sh ]]; then 11 | echo "must be run from repository root" 12 | exit 255 13 | fi 14 | 15 | # It's necessary to run go mod vendor because protoc needs the source files to resolve the imports 16 | echo "INFO: Running go mod vendor" 17 | go mod vendor 18 | 19 | DIRS=( "protos/errorx/v1") 20 | 21 | command -v protoc-gen-gogofast >/dev/null 2>&1 || { echo "protoc-gen-gogofast is not installed"; exit 1; } 22 | command -v protoc-gen-gogoslick >/dev/null 2>&1 || { echo "protoc-gen-gogoslick is not installed"; exit 1; } 23 | 24 | # Set the import path for Proto files 25 | GOGOPROTO_ROOT="$(go list -mod=mod -f '{{ .Dir }}' -m github.com/gogo/protobuf)" 26 | GOGOPROTO_PATH="${GOGOPROTO_ROOT}:${GOGOPROTO_ROOT}/protobuf" 27 | PROTO_PATH="protos:${GOGOPROTO_PATH}:vendor" 28 | 29 | echo "INFO: Generating code" 30 | for dir in "${DIRS[@]}"; do 31 | protoc \ 32 | --gogoslick_out=Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,plugins=grpc:./ \ 33 | -I="${PROTO_PATH}" \ 34 | "${dir}"/*.proto 35 | done 36 | 37 | echo "INFO: Proto files are up to date" --------------------------------------------------------------------------------