├── .gitignore ├── Dockerfile ├── go.mod ├── makefile ├── start.sh ├── README.md ├── LICENSE ├── main.go └── pkg └── postgresql └── client.go /.gitignore: -------------------------------------------------------------------------------- 1 | postgresql-prometheus-adapter 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM centos:7 2 | 3 | MAINTAINER Yogesh Sharma 4 | 5 | COPY postgresql-prometheus-adapter start.sh / 6 | 7 | ENTRYPOINT ["/start.sh"] 8 | 9 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/crunchydata/postgresql-prometheus-adapter 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/go-kit/kit v0.12.0 7 | github.com/gogo/protobuf v1.3.2 8 | github.com/golang/snappy v0.0.4 9 | github.com/jackc/pgx/v4 v4.16.1 10 | github.com/prometheus/client_golang v1.12.1 11 | github.com/prometheus/common v0.34.0 12 | github.com/prometheus/prometheus v0.35.0 13 | golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122 // indirect 14 | golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect 15 | golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect 16 | gopkg.in/alecthomas/kingpin.v2 v2.2.6 17 | ) 18 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | VERSION=1.1 2 | ORGANIZATION=crunchydata 3 | 4 | SOURCES:=$(shell find . -name '*.go' | grep -v './vendor') 5 | 6 | TARGET:=postgresql-prometheus-adapter 7 | 8 | .PHONY: all clean build docker-image docker-push test prepare-for-docker-build 9 | 10 | all: $(TARGET) 11 | 12 | build: $(TARGET) 13 | 14 | $(TARGET): main.go $(SOURCES) 15 | go build -ldflags="-X 'main.Version=${VERSION}'" -o $(TARGET) 16 | 17 | container: $(TARGET) Dockerfile 18 | @#podman rmi $(ORGANIZATION)/$(TARGET):latest $(ORGANIZATION)/$(TARGET):$(VERSION) 19 | podman build -t $(ORGANIZATION)/$(TARGET):latest . 20 | podman tag $(ORGANIZATION)/$(TARGET):latest $(ORGANIZATION)/$(TARGET):$(VERSION) 21 | 22 | container-save: container 23 | rm -f $(TARGET)-$(VERSION).tar 24 | podman save --output=$(TARGET)-$(VERSION).tar $(ORGANIZATION)/$(TARGET):$(VERSION) 25 | 26 | clean: 27 | rm -f *~ $(TARGET) 28 | 29 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ "${DATABASE_URL}" == "" ]]; then 4 | echo 'Missing DATABASE_URL' 5 | echo 'example -e DATABASE_URL="user= password= host= port= database="' 6 | exit 1 7 | fi 8 | 9 | trap shutdown INT 10 | 11 | function shutdown() { 12 | pkill -SIGINT postgresql-prometheus-adapter 13 | } 14 | 15 | adapter_send_timeout=${adapter_send_timeout:-'30s'} 16 | web_listen_address="${web_listen_address:-':9201'}" 17 | web_telemetry_path="${web_telemetry_path:-'/metrics'}" 18 | log_level="${log_level:-'info'}" 19 | log_format="${log_format:-'logfmt'}" 20 | pg_partition="${pg_partition:-'hourly'}" 21 | pg_commit_secs=${pg_commit_secs:-30} 22 | pg_commit_rows=${pg_commit_rows:-20000} 23 | pg_threads="${pg_threads:-1}" 24 | parser_threads="${parser_threads:-5}" 25 | 26 | echo /postgresql-prometheus-adapter \ 27 | --adapter-send-timeout=${adapter_send_timeout} \ 28 | --web-listen-address=${web_listen_address} \ 29 | --web-telemetry-path=${web_telemetry_path} \ 30 | --log.level=${log_level} \ 31 | --log.format=${log_format} \ 32 | --pg-partition=${pg_partition} \ 33 | --pg-commit-secs=${pg_commit_secs} \ 34 | --pg-commit-rows=${pg_commit_rows} \ 35 | --pg-threads=${pg_threads} \ 36 | --parser-threads=${parser_threads} 37 | 38 | /postgresql-prometheus-adapter \ 39 | --adapter-send-timeout=${adapter_send_timeout} \ 40 | --web-listen-address=${web_listen_address} \ 41 | --web-telemetry-path=${web_telemetry_path} \ 42 | --log.level=${log_level} \ 43 | --log.format=${log_format} \ 44 | --pg-partition=${pg_partition} \ 45 | --pg-commit-secs=${pg_commit_secs} \ 46 | --pg-commit-rows=${pg_commit_rows} \ 47 | --pg-threads=${pg_threads} \ 48 | --parser-threads=${parser_threads} 49 | 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PostgreSQL Prometheus Adapter 2 | 3 | Remote storage adapter enabling Prometheus to use PostgreSQL as a long-term store for time-series metrics. Code is based on [Prometheus - Remote storage adapter](https://github.com/prometheus/prometheus/tree/master/documentation/examples/remote_storage/remote_storage_adapter). 4 | 5 | The PostgreSQL Prometheus Adapter is designed to utilize native partitioning enhancements available in recent versions of core PostgreSQL to efficiently store Prometheus time series data in a PostgreSQL database, and is not dependent on external PostgreSQL extensions. 6 | 7 | The design is based on partitioning and threads. Incoming data is processed by one or more threads and one or more writer threads will store data in PostgreSQL daily or hourly partitions. Partitions will be auto-created by the adapter based on the timestamp of incoming data. 8 | 9 | The PostgreSQL Prometheus Adapter accepts Prometheus remote read/write requests, and sends them to PostgreSQL. 10 | 11 | Additional information regarding the adapter and getting started is provided below and available in this [blog post introducing the PostgreSQL Prometheus Adapter](https://info.crunchydata.com/blog/using-postgres-to-back-prometheus-for-your-postgresql-monitoring-1). 12 | 13 | ## PostgreSQL Version Support 14 | 15 | PostgreSQL Prometheus Adapter supports: 16 | 17 | * PostgreSQL 14 18 | * PostgreSQL 13 19 | * PostgreSQL 12 20 | * PostgreSQL 11 21 | 22 | ## Building 23 | 24 | ### Compile 25 | 26 | ```shell 27 | make 28 | ``` 29 | 30 | ### Make a container (optional) 31 | 32 | ```shell 33 | make container 34 | ``` 35 | 36 | ## Running 37 | 38 | ### Running adapter 39 | 40 | ```shell 41 | export DATABASE_URL=... 42 | ./postgresql-prometheus-adapter 43 | ``` 44 | 45 | #### Database Connection 46 | 47 | DATABASE_URL environment variable defines PostgreSQL connection string. 48 | 49 | ```shell 50 | export DATABASE_URL=... 51 | 52 | ``` 53 | 54 | ```shell 55 | Default: None 56 | Description: Database connection parameters 57 | Ex: “user=<> password=<> host=<> port=<> database=<>” 58 | ``` 59 | 60 | #### Adapter parameters 61 | 62 | Following parameters can be used to tweak adapter behavior. 63 | 64 | ```shell 65 | ./postgresql-prometheus-adapter --help 66 | usage: postgresql-prometheus-adapter [] 67 | 68 | Remote storage adapter [ PostgreSQL ] 69 | 70 | Flags: 71 | -h, --help Show context-sensitive help (also try --help-long and --help-man). 72 | --adapter-send-timeout=30s The timeout to use when sending samples to the remote storage. 73 | --web-listen-address=":9201" Address to listen on for web endpoints. 74 | --web-telemetry-path="/metrics" Address to listen on for web endpoints. 75 | --log.level=info Only log messages with the given severity or above. One of: [debug, info, warn, error] 76 | --log.format=logfmt Output format of log messages. One of: [logfmt, json] 77 | --pg-partition="hourly" daily or hourly partitions, default: hourly 78 | --pg-commit-secs=15 Write data to database every N seconds 79 | --pg-commit-rows=20000 Write data to database every N Rows 80 | --pg-threads=1 Writer DB threads to run 1-10 81 | --parser-threads=5 parser threads to run per DB writer 1-10 82 | ``` 83 | :point_right: Note: pg_commit_secs and pg_commit_rows controls when data rows will be flushed to database. First one to reach threshold will trigger the flush. 84 | 85 | ### Container 86 | 87 | #### Run container 88 | 89 | ```shell 90 | podman run --rm \ 91 | --name postgresql-prometheus-adapter \ 92 | -p 9201:9201 \ 93 | -e DATABASE_URL="user=testuser password=test123 host=192.168.12.36 port=5432 database=testdb" \ 94 | --detach \ 95 | crunchydata/postgresql-prometheus-adapterl:latest 96 | ``` 97 | 98 | #### Stop container 99 | 100 | ```shell 101 | podman stop postgresql-prometheus-adapter 102 | ``` 103 | 104 | #### Adapter ENV 105 | 106 | Following `-e NAME:VALUE` can be used to tweak adapter behavior. 107 | 108 | ```shell 109 | adapter_send_timeout=30s The timeout to use when sending samples to the remote storage. 110 | web_listen_address=":9201" Address to listen on for web endpoints. 111 | web_telemetry_path="/metrics" Address to listen on for web endpoints. 112 | log_level=info Only log messages with the given severity or above. One of: [debug, info, warn, error] 113 | log_format=logfmt Output format of log messages. One of: [logfmt, json] 114 | pg_partition="hourly" daily or hourly partitions, default: hourly 115 | pg_commit_secs=15 Write data to database every N seconds 116 | pg_commit_rows=20000 Write data to database every N Rows 117 | pg_threads=1 Writer DB threads to run 1-10 118 | parser_threads=5 parser threads to run per DB writer 1-10 119 | ``` 120 | :point_right: Note: pg_commit_secs and pg_commit_rows controls when data rows will be flushed to database. First one to reach threshold will trigger the flush. 121 | 122 | ## Prometheus Configuration 123 | 124 | Add the following to your prometheus.yml: 125 | 126 | ```yaml 127 | remote_write: 128 | - url: "http://:9201/write" 129 | remote_read: 130 | - url: "http://:9201/read" 131 | ``` 132 | 133 | ## Maintainers 134 | 135 | The PostgreSQL Prometheus Adapter is maintained by the team at [Crunchy Data](https://www.crunchydata.com/). 136 | 137 | ## Contributing to the Project 138 | 139 | Want to contribute to the PostgreSQL Prometheus Adapter? Great! Please use GitHub to submit an issue for the PostgreSQL Prometheus Adapter project. If you would like to work the issue, please add that information in the issue so that we can confirm we are not already working no need to duplicate efforts. 140 | 141 | ## License 142 | 143 | The PostgreSQL Prometheus Adapter is available under the Apache 2.0 license. See [LICENSE](https://github.com/CrunchyData/postgresql-prometheus-adapter/blob/master/LICENSE) for details. 144 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Crunchy Data Solutions, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Prometheus Authors 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // 15 | // Copyright 2019 Crunchy Data 16 | // 17 | // Based on the Prometheus remote storage example: 18 | // documentation/examples/remote_storage/remote_storage_adapter/main.go 19 | // 20 | 21 | // The main package for the Prometheus server executable. 22 | package main 23 | 24 | import ( 25 | "fmt" 26 | "io/ioutil" 27 | "net/http" 28 | _ "net/http/pprof" 29 | "os" 30 | "os/signal" 31 | "time" 32 | 33 | "path/filepath" 34 | 35 | "github.com/crunchydata/postgresql-prometheus-adapter/pkg/postgresql" 36 | 37 | "github.com/go-kit/kit/log" 38 | "github.com/go-kit/kit/log/level" 39 | "github.com/gogo/protobuf/proto" 40 | "github.com/golang/snappy" 41 | 42 | //"github.com/jamiealquiza/envy" 43 | 44 | "github.com/prometheus/common/promlog" 45 | "github.com/prometheus/common/promlog/flag" 46 | 47 | "github.com/prometheus/client_golang/prometheus" 48 | "github.com/prometheus/client_golang/prometheus/promhttp" 49 | "github.com/prometheus/prometheus/prompb" 50 | 51 | //"github.com/prometheus/client_model/go" 52 | "github.com/prometheus/common/model" 53 | "gopkg.in/alecthomas/kingpin.v2" 54 | //"flag" 55 | ) 56 | 57 | var Version = "development" 58 | 59 | type config struct { 60 | remoteTimeout time.Duration 61 | listenAddr string 62 | telemetryPath string 63 | pgPrometheusConfig postgresql.Config 64 | logLevel string 65 | haGroupLockId int 66 | prometheusTimeout time.Duration 67 | promlogConfig promlog.Config 68 | } 69 | 70 | const ( 71 | tickInterval = time.Second 72 | promLivenessCheck = time.Second 73 | maxBgWriter = 10 74 | maxBgParser = 20 75 | ) 76 | 77 | var ( 78 | receivedSamples = prometheus.NewCounter( 79 | prometheus.CounterOpts{ 80 | Name: "received_samples_total", 81 | Help: "Total number of received samples.", 82 | }, 83 | ) 84 | sentSamples = prometheus.NewCounterVec( 85 | prometheus.CounterOpts{ 86 | Name: "sent_samples_total", 87 | Help: "Total number of processed samples sent to remote storage.", 88 | }, 89 | []string{"remote"}, 90 | ) 91 | failedSamples = prometheus.NewCounterVec( 92 | prometheus.CounterOpts{ 93 | Name: "failed_samples_total", 94 | Help: "Total number of processed samples which failed on send to remote storage.", 95 | }, 96 | []string{"remote"}, 97 | ) 98 | sentBatchDuration = prometheus.NewHistogramVec( 99 | prometheus.HistogramOpts{ 100 | Name: "sent_batch_duration_seconds", 101 | Help: "Duration of sample batch send calls to the remote storage.", 102 | Buckets: prometheus.DefBuckets, 103 | }, 104 | []string{"remote"}, 105 | ) 106 | httpRequestDuration = prometheus.NewHistogramVec( 107 | prometheus.HistogramOpts{ 108 | Name: "http_request_duration_ms", 109 | Help: "Duration of HTTP request in milliseconds", 110 | Buckets: prometheus.DefBuckets, 111 | }, 112 | []string{"path"}, 113 | ) 114 | ) 115 | 116 | var worker [maxBgWriter]postgresql.PGWriter 117 | 118 | func init() { 119 | prometheus.MustRegister(receivedSamples) 120 | prometheus.MustRegister(sentSamples) 121 | prometheus.MustRegister(failedSamples) 122 | prometheus.MustRegister(sentBatchDuration) 123 | prometheus.MustRegister(httpRequestDuration) 124 | } 125 | 126 | func main() { 127 | cfg := parseFlags() 128 | logger := promlog.New(&cfg.promlogConfig) 129 | level.Info(logger).Log("config", fmt.Sprintf("%+v", cfg)) 130 | level.Info(logger).Log("pgPrometheusConfig", fmt.Sprintf("%+v", cfg.pgPrometheusConfig)) 131 | 132 | if cfg.pgPrometheusConfig.PGWriters < 0 { 133 | cfg.pgPrometheusConfig.PGWriters = 1 134 | } 135 | if cfg.pgPrometheusConfig.PGWriters > maxBgWriter { 136 | cfg.pgPrometheusConfig.PGWriters = maxBgWriter 137 | } 138 | 139 | if cfg.pgPrometheusConfig.PGParsers < 0 { 140 | cfg.pgPrometheusConfig.PGParsers = 1 141 | } 142 | if cfg.pgPrometheusConfig.PGParsers > maxBgParser { 143 | cfg.pgPrometheusConfig.PGParsers = maxBgParser 144 | } 145 | 146 | http.Handle(cfg.telemetryPath, promhttp.Handler()) 147 | writer, reader := buildClients(logger, cfg) 148 | 149 | c := make(chan os.Signal, 1) 150 | signal.Notify(c, os.Interrupt) 151 | go func() { 152 | for sig := range c { 153 | fmt.Printf("Signal: %v\n", sig) 154 | for t := 0; t < cfg.pgPrometheusConfig.PGWriters; t++ { 155 | fmt.Printf("Calling shutdown %d\n", t) 156 | worker[t].PGWriterShutdown() 157 | } 158 | for t := 0; t < cfg.pgPrometheusConfig.PGWriters; t++ { 159 | for worker[t].Running { 160 | time.Sleep(1 * time.Second) 161 | fmt.Printf("Waiting for shutdown %d...\n", t) 162 | } 163 | } 164 | os.Exit(0) 165 | } 166 | }() 167 | for t := 0; t < cfg.pgPrometheusConfig.PGWriters; t++ { 168 | go worker[t].RunPGWriter(logger, t, cfg.pgPrometheusConfig.CommitSecs, cfg.pgPrometheusConfig.CommitRows, cfg.pgPrometheusConfig.PGParsers, cfg.pgPrometheusConfig.PartitionScheme) 169 | defer worker[t].PGWriterShutdown() 170 | } 171 | 172 | level.Info(logger).Log("msg", "Starting HTTP Listerner") 173 | 174 | http.Handle("/write", timeHandler("write", write(logger, writer))) 175 | http.Handle("/read", timeHandler("read", read(logger, reader))) 176 | 177 | level.Info(logger).Log("msg", "Starting up...") 178 | level.Info(logger).Log("msg", "Listening", "addr", cfg.listenAddr) 179 | 180 | err := http.ListenAndServe(cfg.listenAddr, nil) 181 | 182 | level.Info(logger).Log("msg", "Started HTTP Listerner") 183 | 184 | if err != nil { 185 | level.Error(logger).Log("msg", "Listen failure", "err", err) 186 | os.Exit(1) 187 | } 188 | } 189 | 190 | func parseFlags() *config { 191 | a := kingpin.New(filepath.Base(os.Args[0]), fmt.Sprintf("Remote storage adapter [ PostgreSQL ], Version: %s", Version)) 192 | a.HelpFlag.Short('h') 193 | 194 | cfg := &config{ 195 | promlogConfig: promlog.Config{}, 196 | } 197 | 198 | a.Flag("adapter-send-timeout", "The timeout to use when sending samples to the remote storage.").Default("30s").DurationVar(&cfg.remoteTimeout) 199 | a.Flag("web-listen-address", "Address to listen on for web endpoints.").Default(":9201").StringVar(&cfg.listenAddr) 200 | a.Flag("web-telemetry-path", "Address to listen on for web endpoints.").Default("/metrics").StringVar(&cfg.telemetryPath) 201 | flag.AddFlags(a, &cfg.promlogConfig) 202 | 203 | a.Flag("pg-partition", "daily or hourly partitions, default: hourly").Default("hourly").StringVar(&cfg.pgPrometheusConfig.PartitionScheme) 204 | a.Flag("pg-commit-secs", "Write data to database every N seconds").Default("15").IntVar(&cfg.pgPrometheusConfig.CommitSecs) 205 | a.Flag("pg-commit-rows", "Write data to database every N Rows").Default("20000").IntVar(&cfg.pgPrometheusConfig.CommitRows) 206 | a.Flag("pg-threads", "Writer DB threads to run 1-10").Default("1").IntVar(&cfg.pgPrometheusConfig.PGWriters) 207 | a.Flag("parser-threads", "parser threads to run per DB writer 1-10").Default("5").IntVar(&cfg.pgPrometheusConfig.PGParsers) 208 | 209 | _, err := a.Parse(os.Args[1:]) 210 | if err != nil { 211 | fmt.Fprintln(os.Stderr, "Error parsing commandline arguments") 212 | a.Usage(os.Args[1:]) 213 | os.Exit(2) 214 | } 215 | 216 | return cfg 217 | } 218 | 219 | type writer interface { 220 | Write(samples model.Samples) error 221 | Name() string 222 | } 223 | 224 | type reader interface { 225 | Read(req *prompb.ReadRequest) (*prompb.ReadResponse, error) 226 | Name() string 227 | HealthCheck() error 228 | } 229 | 230 | func buildClients(logger log.Logger, cfg *config) (writer, reader) { 231 | pgClient := postgresql.NewClient(log.With(logger, "storage", "PostgreSQL"), &cfg.pgPrometheusConfig) 232 | 233 | return pgClient, pgClient 234 | } 235 | 236 | func write(logger log.Logger, writer writer) http.Handler { 237 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 238 | compressed, err := ioutil.ReadAll(r.Body) 239 | if err != nil { 240 | level.Error(logger).Log("msg", "Read error", "err", err.Error()) 241 | http.Error(w, err.Error(), http.StatusInternalServerError) 242 | return 243 | } 244 | 245 | reqBuf, err := snappy.Decode(nil, compressed) 246 | if err != nil { 247 | level.Error(logger).Log("msg", "Decode error", "err", err.Error()) 248 | http.Error(w, err.Error(), http.StatusBadRequest) 249 | return 250 | } 251 | 252 | var req prompb.WriteRequest 253 | if err := proto.Unmarshal(reqBuf, &req); err != nil { 254 | level.Error(logger).Log("msg", "Unmarshal error", "err", err.Error()) 255 | http.Error(w, err.Error(), http.StatusBadRequest) 256 | return 257 | } 258 | 259 | samples := protoToSamples(&req) 260 | receivedSamples.Add(float64(len(samples))) 261 | 262 | err = sendSamples(writer, samples) 263 | if err != nil { 264 | level.Warn(logger).Log("msg", "Error sending samples to remote storage", "err", err, "storage", writer.Name(), "num_samples", len(samples)) 265 | } 266 | 267 | }) 268 | } 269 | 270 | func read(logger log.Logger, reader reader) http.Handler { 271 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 272 | compressed, err := ioutil.ReadAll(r.Body) 273 | if err != nil { 274 | level.Error(logger).Log("msg", "Read error", "err", err.Error()) 275 | http.Error(w, err.Error(), http.StatusInternalServerError) 276 | return 277 | } 278 | 279 | reqBuf, err := snappy.Decode(nil, compressed) 280 | if err != nil { 281 | level.Error(logger).Log("msg", "Decode error", "err", err.Error()) 282 | http.Error(w, err.Error(), http.StatusBadRequest) 283 | return 284 | } 285 | 286 | var req prompb.ReadRequest 287 | if err := proto.Unmarshal(reqBuf, &req); err != nil { 288 | level.Error(logger).Log("msg", "Unmarshal error", "err", err.Error()) 289 | http.Error(w, err.Error(), http.StatusBadRequest) 290 | return 291 | } 292 | 293 | var resp *prompb.ReadResponse 294 | resp, err = reader.Read(&req) 295 | if err != nil { 296 | fmt.Printf("MAIN req.Queries: %v\n", req.Queries) 297 | level.Warn(logger).Log("msg", "Error executing query", "query", req, "storage", reader.Name(), "err", err) 298 | http.Error(w, err.Error(), http.StatusInternalServerError) 299 | return 300 | } 301 | 302 | data, err := proto.Marshal(resp) 303 | if err != nil { 304 | http.Error(w, err.Error(), http.StatusInternalServerError) 305 | return 306 | } 307 | 308 | w.Header().Set("Content-Type", "application/x-protobuf") 309 | w.Header().Set("Content-Encoding", "snappy") 310 | 311 | compressed = snappy.Encode(nil, data) 312 | if _, err := w.Write(compressed); err != nil { 313 | http.Error(w, err.Error(), http.StatusInternalServerError) 314 | return 315 | } 316 | }) 317 | } 318 | 319 | func health(reader reader) http.Handler { 320 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 321 | err := reader.HealthCheck() 322 | if err != nil { 323 | http.Error(w, err.Error(), http.StatusInternalServerError) 324 | return 325 | } 326 | w.Header().Set("Content-Length", "0") 327 | }) 328 | } 329 | 330 | func protoToSamples(req *prompb.WriteRequest) model.Samples { 331 | var samples model.Samples 332 | for _, ts := range req.Timeseries { 333 | metric := make(model.Metric, len(ts.Labels)) 334 | for _, l := range ts.Labels { 335 | metric[model.LabelName(l.Name)] = model.LabelValue(l.Value) 336 | } 337 | 338 | for _, s := range ts.Samples { 339 | samples = append(samples, &model.Sample{ 340 | Metric: metric, 341 | Value: model.SampleValue(s.Value), 342 | Timestamp: model.Time(s.Timestamp), 343 | }) 344 | } 345 | } 346 | return samples 347 | } 348 | 349 | func sendSamples(w writer, samples model.Samples) error { 350 | begin := time.Now() 351 | var err error 352 | err = w.Write(samples) 353 | duration := time.Since(begin).Seconds() 354 | if err != nil { 355 | failedSamples.WithLabelValues(w.Name()).Add(float64(len(samples))) 356 | return err 357 | } 358 | sentSamples.WithLabelValues(w.Name()).Add(float64(len(samples))) 359 | sentBatchDuration.WithLabelValues(w.Name()).Observe(duration) 360 | return nil 361 | } 362 | 363 | // timeHandler uses Prometheus histogram to track request time 364 | func timeHandler(path string, handler http.Handler) http.Handler { 365 | f := func(w http.ResponseWriter, r *http.Request) { 366 | start := time.Now() 367 | handler.ServeHTTP(w, r) 368 | elapsedMs := time.Since(start).Nanoseconds() / int64(time.Millisecond) 369 | httpRequestDuration.WithLabelValues(path).Observe(float64(elapsedMs)) 370 | } 371 | return http.HandlerFunc(f) 372 | } 373 | -------------------------------------------------------------------------------- /pkg/postgresql/client.go: -------------------------------------------------------------------------------- 1 | package postgresql 2 | 3 | import ( 4 | "container/list" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "os" 9 | "reflect" 10 | "runtime" 11 | "sort" 12 | "strings" 13 | "sync" 14 | "time" 15 | 16 | "github.com/go-kit/kit/log" 17 | "github.com/go-kit/kit/log/level" 18 | "github.com/jackc/pgx/v4" 19 | "github.com/prometheus/common/model" 20 | "github.com/prometheus/prometheus/prompb" 21 | ) 22 | 23 | type tMetricIDMap map[string]int64 24 | 25 | // Config for the database 26 | type Config struct { 27 | CommitSecs int 28 | CommitRows int 29 | PGWriters int 30 | PGParsers int 31 | PartitionScheme string 32 | } 33 | 34 | var promSamples = list.New() 35 | 36 | // QueueMutex is used thread safe operations on promSamples list object. 37 | var QueueMutex sync.Mutex 38 | var vMetricIDMapMutex sync.Mutex 39 | var vMetricIDMap tMetricIDMap 40 | 41 | // PGWriter - Threaded writer 42 | type PGWriter struct { 43 | DB *pgx.Conn 44 | id int 45 | KeepRunning bool 46 | Running bool 47 | 48 | valueRows [][]interface{} 49 | labelRows [][]interface{} 50 | 51 | PGWriterMutex sync.Mutex 52 | logger log.Logger 53 | } 54 | 55 | // PGParser - Threaded parser 56 | type PGParser struct { 57 | id int 58 | KeepRunning bool 59 | Running bool 60 | 61 | lastPartitionTS time.Time 62 | valueRows [][]interface{} 63 | } 64 | 65 | // RunPGParser starts the client and listens for a shutdown call. 66 | func (p *PGParser) RunPGParser(tid int, partitionScheme string, c *PGWriter) { 67 | var samples *model.Samples 68 | p.id = tid 69 | level.Info(c.logger).Log(fmt.Sprintf("bgparser%d", p.id), "Started") 70 | p.Running = true 71 | p.KeepRunning = true 72 | 73 | // Loop that runs forever 74 | for p.KeepRunning { 75 | samples = Pop() 76 | if samples != nil { 77 | for _, sample := range *samples { 78 | sMetric := metricString(sample.Metric) 79 | ts := time.Unix(sample.Timestamp.Unix(), 0) 80 | milliseconds := sample.Timestamp.UnixNano() / 1000000 81 | if ts.Year() != p.lastPartitionTS.Year() || 82 | ts.Month() != p.lastPartitionTS.Month() || 83 | ts.Day() != p.lastPartitionTS.Day() { 84 | p.lastPartitionTS = ts 85 | _ = c.setupPgPartitions(partitionScheme, p.lastPartitionTS) 86 | } 87 | vMetricIDMapMutex.Lock() 88 | id, ok := vMetricIDMap[sMetric] 89 | 90 | if !ok { 91 | var nextId int64 = int64(len(vMetricIDMap) + 1) 92 | vMetricIDMap[sMetric] = nextId 93 | i := strings.Index(sMetric, "{") 94 | jsonbMap := make(map[string]interface{}) 95 | json.Unmarshal([]byte(sMetric[i:]), &jsonbMap) 96 | c.labelRows = append(c.labelRows, []interface{}{int64(nextId), sMetric[:i], sMetric, jsonbMap}) 97 | id = nextId 98 | } 99 | vMetricIDMapMutex.Unlock() 100 | p.valueRows = append(p.valueRows, []interface{}{int64(id), toTimestamp(milliseconds), float64(sample.Value)}) 101 | } 102 | vMetricIDMapMutex.Lock() 103 | c.valueRows = append(c.valueRows, p.valueRows...) 104 | p.valueRows = nil 105 | vMetricIDMapMutex.Unlock() 106 | runtime.GC() 107 | } 108 | time.Sleep(10 * time.Millisecond) 109 | } 110 | level.Info(c.logger).Log(fmt.Sprintf("bgparser%d", p.id), "Shutdown") 111 | p.Running = false 112 | } 113 | 114 | // PGParserShutdown is a graceful shutdown 115 | func (p *PGParser) PGParserShutdown() { 116 | p.KeepRunning = false 117 | } 118 | 119 | // RunPGWriter starts the client and listens for a shutdown call. 120 | func (c *PGWriter) RunPGWriter(l log.Logger, tid int, commitSecs int, commitRows int, Parsers int, partitionScheme string) { 121 | c.logger = l 122 | c.id = tid 123 | period := commitSecs * 1000 124 | var err error 125 | var parser [20]PGParser 126 | c.DB, err = pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) 127 | if err != nil { 128 | level.Error(c.logger).Log("err", err) 129 | os.Exit(1) 130 | } 131 | if c.id == 0 { 132 | c.setupPgPrometheus() 133 | _ = c.setupPgPartitions(partitionScheme, time.Now()) 134 | } 135 | level.Info(c.logger).Log(fmt.Sprintf("bgwriter%d", c.id), fmt.Sprintf("Starting %d Parsers", Parsers)) 136 | for p := 0; p < Parsers; p++ { 137 | go parser[p].RunPGParser(p, partitionScheme, c) 138 | defer parser[p].PGParserShutdown() 139 | } 140 | level.Info(c.logger).Log(fmt.Sprintf("bgwriter%d", c.id), "Started") 141 | c.Running = true 142 | c.KeepRunning = true 143 | // Loop that runs forever 144 | for c.KeepRunning { 145 | if (period <= 0 && len(c.valueRows) > 0) || (len(c.valueRows) > commitRows) { 146 | c.PGWriterSave() 147 | period = commitSecs * 1000 148 | } else { 149 | time.Sleep(10 * time.Millisecond) 150 | period -= 10 151 | } 152 | } 153 | c.PGWriterSave() 154 | level.Info(c.logger).Log(fmt.Sprintf("bgwriter%d", c.id), "Shutdown") 155 | c.Running = false 156 | } 157 | 158 | // PGWriterShutdown - Set shutdown flag for graceful shutdown 159 | func (c *PGWriter) PGWriterShutdown() { 160 | c.KeepRunning = false 161 | } 162 | 163 | // PGWriterSave save data to DB 164 | func (c *PGWriter) PGWriterSave() { 165 | var copyCount, lblCount, rowCount int64 166 | var err error 167 | begin := time.Now() 168 | lblCount = int64(len(c.labelRows)) 169 | c.PGWriterMutex.Lock() 170 | if lblCount > 0 { 171 | copyCount, err := c.DB.CopyFrom(context.Background(), pgx.Identifier{"metric_labels"}, []string{"metric_id", "metric_name", "metric_name_label", "metric_labels"}, pgx.CopyFromRows(c.labelRows)) 172 | c.labelRows = nil 173 | if err != nil { 174 | level.Error(c.logger).Log("msg", "COPY failed for metric_labels", "err", err) 175 | } 176 | if copyCount != lblCount { 177 | level.Error(c.logger).Log("msg", "All rows not copied metric_labels", "err", err) 178 | } 179 | } 180 | copyCount, err = c.DB.CopyFrom(context.Background(), pgx.Identifier{"metric_values"}, []string{"metric_id", "metric_time", "metric_value"}, pgx.CopyFromRows(c.valueRows)) 181 | rowCount = int64(len(c.valueRows)) 182 | c.valueRows = nil 183 | c.PGWriterMutex.Unlock() 184 | if err != nil { 185 | level.Error(c.logger).Log("msg", "COPY failed for metric_values", "err", err) 186 | } 187 | if copyCount != rowCount { 188 | level.Error(c.logger).Log("msg", "All rows not copied metric_values", "err", err) 189 | } 190 | duration := time.Since(begin).Seconds() 191 | level.Info(c.logger).Log("metric", fmt.Sprintf("BGWriter%d: Processed samples count,%d, duration,%v", c.id, rowCount+lblCount, duration)) 192 | } 193 | 194 | // Push - Push element at then end of list 195 | func Push(samples *model.Samples) { 196 | QueueMutex.Lock() 197 | promSamples.PushBack(samples) 198 | QueueMutex.Unlock() 199 | } 200 | 201 | // Pop - Pop first element from list 202 | func Pop() *model.Samples { 203 | QueueMutex.Lock() 204 | defer QueueMutex.Unlock() 205 | p := promSamples.Front() 206 | if p != nil { 207 | return promSamples.Remove(p).(*model.Samples) 208 | } 209 | return nil 210 | } 211 | 212 | // Client - struct to hold critical values 213 | type Client struct { 214 | logger log.Logger 215 | DB *pgx.Conn 216 | cfg *Config 217 | } 218 | 219 | // NewClient creates a new PostgreSQL client 220 | func NewClient(logger log.Logger, cfg *Config) *Client { 221 | if logger == nil { 222 | logger = log.NewNopLogger() 223 | } 224 | 225 | conn1, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) 226 | if err != nil { 227 | fmt.Fprintln(os.Stderr, "Error: Unable to connect to database using DATABASE_URL=", os.Getenv("DATABASE_URL")) 228 | os.Exit(1) 229 | } 230 | 231 | client := &Client{ 232 | logger: logger, 233 | DB: conn1, 234 | cfg: cfg, 235 | } 236 | 237 | return client 238 | } 239 | 240 | func (c *PGWriter) setupPgPrometheus() error { 241 | level.Info(c.logger).Log("msg", "creating tables") 242 | 243 | _, err := c.DB.Exec(context.Background(), "CREATE TABLE IF NOT EXISTS metric_labels ( metric_id BIGINT PRIMARY KEY, metric_name TEXT NOT NULL, metric_name_label TEXT NOT NULL, metric_labels jsonb, UNIQUE(metric_name, metric_labels) )") 244 | if err != nil { 245 | return err 246 | } 247 | 248 | _, err = c.DB.Exec(context.Background(), "CREATE INDEX IF NOT EXISTS metric_labels_labels_idx ON metric_labels USING GIN (metric_labels)") 249 | if err != nil { 250 | return err 251 | } 252 | 253 | _, err = c.DB.Exec(context.Background(), "CREATE TABLE IF NOT EXISTS metric_values (metric_id BIGINT, metric_time TIMESTAMPTZ, metric_value FLOAT8 ) PARTITION BY RANGE (metric_time)") 254 | if err != nil { 255 | return err 256 | } 257 | 258 | _, err = c.DB.Exec(context.Background(), "CREATE INDEX IF NOT EXISTS metric_values_id_time_idx on metric_values USING btree (metric_id, metric_time DESC)") 259 | if err != nil { 260 | return err 261 | } 262 | 263 | _, err = c.DB.Exec(context.Background(), "CREATE INDEX IF NOT EXISTS metric_values_time_idx on metric_values USING btree (metric_time DESC)") 264 | if err != nil { 265 | return err 266 | } 267 | 268 | vMetricIDMapMutex.Lock() 269 | defer vMetricIDMapMutex.Unlock() 270 | vMetricIDMap = make(tMetricIDMap) 271 | rows, err1 := c.DB.Query(context.Background(), "SELECT metric_name_label, metric_id from metric_labels") 272 | 273 | if err1 != nil { 274 | rows.Close() 275 | level.Info(c.logger).Log("msg", "Error reading metric_labels") 276 | return err 277 | } 278 | 279 | for rows.Next() { 280 | var ( 281 | metricNameLabel string 282 | metricID int64 283 | ) 284 | err := rows.Scan(&metricNameLabel, &metricID) 285 | 286 | if err != nil { 287 | rows.Close() 288 | level.Info(c.logger).Log("msg", "Error scaning metric_labels") 289 | return err 290 | } 291 | vMetricIDMap[metricNameLabel] = metricID 292 | } 293 | level.Info(c.logger).Log("msg", fmt.Sprintf("%d Rows Loaded in map: ", len(vMetricIDMap))) 294 | rows.Close() 295 | 296 | return nil 297 | } 298 | 299 | func (c *PGWriter) setupPgPartitions(partitionScheme string, lastPartitionTS time.Time) error { 300 | sDate := lastPartitionTS 301 | eDate := sDate 302 | if partitionScheme == "daily" { 303 | level.Info(c.logger).Log("msg", "Creating partition, daily") 304 | _, err := c.DB.Exec(context.Background(), fmt.Sprintf("CREATE TABLE IF NOT EXISTS metric_values_%s PARTITION OF metric_values FOR VALUES FROM ('%s 00:00:00') TO ('%s 00:00:00')", sDate.Format("20060102"), sDate.Format("2006-01-02"), eDate.AddDate(0, 0, 1).Format("2006-01-02"))) 305 | if err != nil { 306 | return err 307 | } 308 | } else if partitionScheme == "hourly" { 309 | sql := fmt.Sprintf("CREATE TABLE IF NOT EXISTS metric_values_%s PARTITION OF metric_values FOR VALUES FROM ('%s 00:00:00') TO ('%s 00:00:00') PARTITION BY RANGE (metric_time);", sDate.Format("20060102"), sDate.Format("2006-01-02"), eDate.AddDate(0, 0, 1).Format("2006-01-02")) 310 | var h int 311 | for h = 0; h < 23; h++ { 312 | sql = fmt.Sprintf("%s CREATE TABLE IF NOT EXISTS metric_values_%s_%02d PARTITION OF metric_values_%s FOR VALUES FROM ('%s %02d:00:00') TO ('%s %02d:00:00');", sql, sDate.Format("20060102"), h, sDate.Format("20060102"), sDate.Format("2006-01-02"), h, eDate.Format("2006-01-02"), h+1) 313 | } 314 | level.Info(c.logger).Log("msg", "Creating partition, hourly") 315 | _, err := c.DB.Exec(context.Background(), fmt.Sprintf("%s CREATE TABLE IF NOT EXISTS metric_values_%s_%02d PARTITION OF metric_values_%s FOR VALUES FROM ('%s %02d:00:00') TO ('%s 00:00:00');", sql, sDate.Format("20060102"), h, sDate.Format("20060102"), sDate.Format("2006-01-02"), h, eDate.AddDate(0, 0, 1).Format("2006-01-02"))) 316 | if err != nil { 317 | return err 318 | } 319 | } 320 | return nil 321 | } 322 | 323 | func metricString(m model.Metric) string { 324 | metricName, hasName := m[model.MetricNameLabel] 325 | numLabels := len(m) - 1 326 | if !hasName { 327 | numLabels = len(m) 328 | } 329 | labelStrings := make([]string, 0, numLabels) 330 | for label, value := range m { 331 | if label != model.MetricNameLabel { 332 | labelStrings = append(labelStrings, fmt.Sprintf("\"%s\": %q", label, value)) 333 | } 334 | } 335 | 336 | switch numLabels { 337 | case 0: 338 | if hasName { 339 | return string(metricName) 340 | } 341 | return "{}" 342 | default: 343 | sort.Strings(labelStrings) 344 | return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", ")) 345 | } 346 | } 347 | 348 | // Write implements the Writer interface and writes metric samples to the database 349 | func (c *Client) Write(samples model.Samples) error { 350 | Push(&samples) 351 | return nil 352 | } 353 | 354 | type sampleLabels struct { 355 | JSON []byte 356 | Map map[string]string 357 | OrderedKeys []string 358 | } 359 | 360 | func createOrderedKeys(m *map[string]string) []string { 361 | keys := make([]string, 0, len(*m)) 362 | for k := range *m { 363 | keys = append(keys, k) 364 | } 365 | sort.Strings(keys) 366 | return keys 367 | } 368 | 369 | // Close - Close database connections 370 | func (c *Client) Close() { 371 | if c.DB != nil { 372 | if err1 := c.DB.Close(context.Background()); err1 != nil { 373 | level.Error(c.logger).Log("msg", err1.Error()) 374 | } 375 | } 376 | } 377 | 378 | func (l *sampleLabels) Scan(value interface{}) error { 379 | if value == nil { 380 | l = &sampleLabels{} 381 | return nil 382 | } 383 | 384 | switch t := value.(type) { 385 | case []uint8: 386 | m := make(map[string]string) 387 | err := json.Unmarshal(t, &m) 388 | 389 | if err != nil { 390 | return err 391 | } 392 | 393 | *l = sampleLabels{ 394 | JSON: t, 395 | Map: m, 396 | OrderedKeys: createOrderedKeys(&m), 397 | } 398 | return nil 399 | } 400 | return fmt.Errorf("invalid labels value %s", reflect.TypeOf(value)) 401 | } 402 | 403 | func (l sampleLabels) String() string { 404 | return string(l.JSON) 405 | } 406 | 407 | func (l sampleLabels) key(extra string) string { 408 | // 0xff cannot cannot occur in valid UTF-8 sequences, so use it 409 | // as a separator here. 410 | separator := "\xff" 411 | pairs := make([]string, 0, len(l.Map)+1) 412 | pairs = append(pairs, extra+separator) 413 | 414 | for _, k := range l.OrderedKeys { 415 | pairs = append(pairs, k+separator+l.Map[k]) 416 | } 417 | return strings.Join(pairs, separator) 418 | } 419 | 420 | func (l *sampleLabels) len() int { 421 | return len(l.OrderedKeys) 422 | } 423 | 424 | // Read implements the Reader interface and reads metrics samples from the database 425 | func (c *Client) Read(req *prompb.ReadRequest) (*prompb.ReadResponse, error) { 426 | 427 | fmt.Printf("READ req.Queries: %v\n", req.Queries) 428 | labelsToSeries := map[string]*prompb.TimeSeries{} 429 | 430 | for _, q := range req.Queries { 431 | command, err := c.buildCommand(q) 432 | 433 | if err != nil { 434 | return nil, err 435 | } 436 | 437 | level.Debug(c.logger).Log("msg", "Executed query", "query", command) 438 | 439 | rows, err := c.DB.Query(context.Background(), command) 440 | 441 | if err != nil { 442 | rows.Close() 443 | return nil, err 444 | } 445 | 446 | for rows.Next() { 447 | var ( 448 | value float64 449 | name string 450 | labels sampleLabels 451 | time time.Time 452 | ) 453 | err := rows.Scan(&time, &name, &value, &labels) 454 | 455 | if err != nil { 456 | rows.Close() 457 | return nil, err 458 | } 459 | 460 | key := labels.key(name) 461 | ts, ok := labelsToSeries[key] 462 | 463 | if !ok { 464 | labelPairs := make([]prompb.Label, 0, labels.len()+1) 465 | labelPairs = append(labelPairs, prompb.Label{ 466 | Name: model.MetricNameLabel, 467 | Value: name, 468 | }) 469 | 470 | for _, k := range labels.OrderedKeys { 471 | labelPairs = append(labelPairs, prompb.Label{ 472 | Name: k, 473 | Value: labels.Map[k], 474 | }) 475 | } 476 | 477 | ts = &prompb.TimeSeries{ 478 | Labels: labelPairs, 479 | Samples: make([]prompb.Sample, 0, 100), 480 | } 481 | labelsToSeries[key] = ts 482 | } 483 | 484 | ts.Samples = append(ts.Samples, prompb.Sample{ 485 | Timestamp: time.UnixNano() / 1000000, 486 | Value: value, 487 | }) 488 | } 489 | 490 | err = rows.Err() 491 | rows.Close() 492 | 493 | if err != nil { 494 | return nil, err 495 | } 496 | } 497 | 498 | resp := prompb.ReadResponse{ 499 | Results: []*prompb.QueryResult{ 500 | { 501 | Timeseries: make([]*prompb.TimeSeries, 0, len(labelsToSeries)), 502 | }, 503 | }, 504 | } 505 | for _, ts := range labelsToSeries { 506 | resp.Results[0].Timeseries = append(resp.Results[0].Timeseries, ts) 507 | } 508 | 509 | level.Debug(c.logger).Log("msg", "Returned response", "#timeseries", len(labelsToSeries)) 510 | 511 | return &resp, nil 512 | } 513 | 514 | // HealthCheck implements the healtcheck interface 515 | func (c *Client) HealthCheck() error { 516 | rows, err := c.DB.Query(context.Background(), "SELECT 1") 517 | defer rows.Close() 518 | if err != nil { 519 | level.Debug(c.logger).Log("msg", "Health check error", "err", err) 520 | return err 521 | } 522 | 523 | return nil 524 | } 525 | 526 | func toTimestamp(milliseconds int64) time.Time { 527 | sec := milliseconds / 1000 528 | nsec := (milliseconds - (sec * 1000)) * 1000000 529 | return time.Unix(sec, nsec).UTC() 530 | } 531 | 532 | func (c *Client) buildQuery(q *prompb.Query) (string, error) { 533 | matchers := make([]string, 0, len(q.Matchers)) 534 | labelEqualPredicates := make(map[string]string) 535 | 536 | for _, m := range q.Matchers { 537 | escapedName := escapeValue(m.Name) 538 | escapedValue := escapeValue(m.Value) 539 | 540 | if m.Name == model.MetricNameLabel { 541 | switch m.Type { 542 | case prompb.LabelMatcher_EQ: 543 | if len(escapedValue) == 0 { 544 | matchers = append(matchers, fmt.Sprintf("(l.metric_name IS NULL OR name = '')")) 545 | } else { 546 | matchers = append(matchers, fmt.Sprintf("l.metric_name = '%s'", escapedValue)) 547 | } 548 | case prompb.LabelMatcher_NEQ: 549 | matchers = append(matchers, fmt.Sprintf("l.metric_name != '%s'", escapedValue)) 550 | case prompb.LabelMatcher_RE: 551 | matchers = append(matchers, fmt.Sprintf("l.metric_name ~ '%s'", anchorValue(escapedValue))) 552 | case prompb.LabelMatcher_NRE: 553 | matchers = append(matchers, fmt.Sprintf("l.metric_name !~ '%s'", anchorValue(escapedValue))) 554 | default: 555 | return "", fmt.Errorf("unknown metric name match type %v", m.Type) 556 | } 557 | } else { 558 | switch m.Type { 559 | case prompb.LabelMatcher_EQ: 560 | if len(escapedValue) == 0 { 561 | // From the PromQL docs: "Label matchers that match 562 | // empty label values also select all time series that 563 | // do not have the specific label set at all." 564 | matchers = append(matchers, fmt.Sprintf("((l.metric_labels ? '%s') = false OR (l.metric_labels->>'%s' = ''))", 565 | escapedName, escapedName)) 566 | } else { 567 | labelEqualPredicates[escapedName] = escapedValue 568 | } 569 | case prompb.LabelMatcher_NEQ: 570 | matchers = append(matchers, fmt.Sprintf("l.metric_labels->>'%s' != '%s'", escapedName, escapedValue)) 571 | case prompb.LabelMatcher_RE: 572 | matchers = append(matchers, fmt.Sprintf("l.metric_labels->>'%s' ~ '%s'", escapedName, anchorValue(escapedValue))) 573 | case prompb.LabelMatcher_NRE: 574 | matchers = append(matchers, fmt.Sprintf("l.metric_labels->>'%s' !~ '%s'", escapedName, anchorValue(escapedValue))) 575 | default: 576 | return "", fmt.Errorf("unknown match type %v", m.Type) 577 | } 578 | } 579 | } 580 | equalsPredicate := "" 581 | 582 | if len(labelEqualPredicates) > 0 { 583 | labelsJSON, err := json.Marshal(labelEqualPredicates) 584 | 585 | if err != nil { 586 | return "", err 587 | } 588 | equalsPredicate = fmt.Sprintf(" AND l.metric_labels @> '%s'", labelsJSON) 589 | } 590 | 591 | matchers = append(matchers, fmt.Sprintf("v.metric_time >= '%v'", toTimestamp(q.StartTimestampMs).Format(time.RFC3339))) 592 | matchers = append(matchers, fmt.Sprintf("v.metric_time <= '%v'", toTimestamp(q.EndTimestampMs).Format(time.RFC3339))) 593 | 594 | return fmt.Sprintf("SELECT v.metric_time, l.metric_name, v.metric_value, l.metric_labels FROM metric_values v, metric_labels l WHERE l.metric_id = v.metric_id and %s %s ORDER BY v.metric_time", 595 | strings.Join(matchers, " AND "), equalsPredicate), nil 596 | } 597 | 598 | func (c *Client) buildCommand(q *prompb.Query) (string, error) { 599 | return c.buildQuery(q) 600 | } 601 | 602 | func escapeValue(str string) string { 603 | return strings.Replace(str, `'`, `''`, -1) 604 | } 605 | 606 | // anchorValue adds anchors to values in regexps since PromQL docs 607 | // states that "Regex-matches are fully anchored." 608 | func anchorValue(str string) string { 609 | l := len(str) 610 | 611 | if l == 0 || (str[0] == '^' && str[l-1] == '$') { 612 | return str 613 | } 614 | 615 | if str[0] == '^' { 616 | return fmt.Sprintf("%s$", str) 617 | } 618 | 619 | if str[l-1] == '$' { 620 | return fmt.Sprintf("^%s", str) 621 | } 622 | 623 | return fmt.Sprintf("^%s$", str) 624 | } 625 | 626 | // Name identifies the client as a PostgreSQL client. 627 | func (c Client) Name() string { 628 | return "PostgreSQL" 629 | } 630 | --------------------------------------------------------------------------------