├── .github
└── workflows
│ └── docker-publish.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── collector
├── collector.go
├── latency_summary.go
├── latency_summary_test.go
├── pg_replication.go
├── pg_replication_test.go
├── pg_settings.go
├── pg_stat_activity.go
├── pg_stat_statements.go
├── query_summary.go
├── version.go
└── version_test.go
├── go.mod
├── go.sum
├── main.go
└── obfuscate
├── runes.go
├── sql.go
└── sql_test.go
/.github/workflows/docker-publish.yml:
--------------------------------------------------------------------------------
1 | name: Docker Image
2 |
3 | on:
4 | release:
5 | types: [created]
6 |
7 | env:
8 | REGISTRY: ghcr.io
9 | IMAGE_NAME: ${{ github.repository }}
10 |
11 | jobs:
12 | build:
13 | runs-on: ubuntu-latest
14 | permissions:
15 | contents: read
16 | packages: write
17 |
18 | steps:
19 | - name: Checkout repository
20 | uses: actions/checkout@v2
21 |
22 | - name: Set up QEMU
23 | uses: docker/setup-qemu-action@v2
24 |
25 | - name: Set up Docker Buildx
26 | uses: docker/setup-buildx-action@v2
27 |
28 | - name: Log into registry ${{ env.REGISTRY }}
29 | uses: docker/login-action@v1
30 | with:
31 | registry: ${{ env.REGISTRY }}
32 | username: ${{ github.actor }}
33 | password: ${{ secrets.GITHUB_TOKEN }}
34 |
35 | - name: Extract Docker metadata
36 | id: meta
37 | uses: docker/metadata-action@v3
38 | with:
39 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
40 | tags: |
41 | type=ref,event=branch
42 | type=ref,event=pr
43 | type=semver,pattern={{version}}
44 |
45 | - name: Build and push Docker image
46 | uses: docker/build-push-action@v2
47 | with:
48 | context: .
49 | platforms: linux/amd64,linux/arm64
50 | push: true
51 | tags: ${{ steps.meta.outputs.tags }}
52 | labels: ${{ steps.meta.outputs.labels }}
53 | build-args: |
54 | VERSION=${{ steps.meta.outputs.version }}
55 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang:1.16-buster AS builder
2 | COPY go.mod /tmp/src/
3 | COPY go.sum /tmp/src/
4 | WORKDIR /tmp/src/
5 | RUN go mod download
6 | COPY . /tmp/src/
7 | RUN go test ./...
8 | ARG VERSION=unknown
9 | RUN go install -mod=readonly -ldflags "-X main.version=$VERSION" /tmp/src
10 |
11 | FROM debian:buster
12 | RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
13 | COPY --from=builder /go/bin/coroot-pg-agent /usr/bin/coroot-pg-agent
14 | ENTRYPOINT ["coroot-pg-agent"]
15 |
--------------------------------------------------------------------------------
/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 2020-present Coroot, 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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Coroot-pg-agent
2 |
3 | [](https://goreportcard.com/report/github.com/coroot/coroot-pg-agent)
4 | [](https://opensource.org/licenses/Apache-2.0)
5 |
6 |
7 | Coroot-pg-agent is an open-source prometheus exporter that gathers metrics from Postgres servers.
8 |
9 | ## Philosophy
10 |
11 | Metrics should help you identify issues with your Postgres servers.
12 | This agent collects metrics that can help you answer questions such as:
13 | * What queries are consuming the most IOPS or CPU time?
14 | * Which transactions are hanging in the *Idle in transaction* state?
15 | * Which query is holding the lock?
16 |
17 | This provides visibility into Postgres performance without the need to navigate through system views manually.
18 |
19 | ## Features
20 |
21 | ### Comprehensive query metrics
22 |
23 | The agent aggregates data from *pg_stat_statements* and *pg_stat_activity* to provide accurate
24 | metrics about queries, whether they are completed or still running.
25 |
26 |
27 |
28 |
29 | Learn more about query metrics in the blog post "[Missing metrics required to gain visibility into Postgres performance](https://coroot.com/blog/pg-missing-metrics)"
30 |
31 |
32 | ### Locks monitoring
33 |
34 | It is not enough to gather the number of active locks from *pg_locks*.
35 | What engineers really want to know is which query is blocking other queries.
36 | The [pg_lock_awaiting_queries](https://docs.coroot.com/metrics/cluster-agent#pg_lock_awaiting_queries) metric can provide the answer to that.
37 |
38 | ### Query normalization and obfuscation
39 |
40 | In addition to query normalization, which Postgres does, the agent obfuscates all queries so that no sensitive data gets into the metrics labels.
41 |
42 | ## Quick start
43 |
44 | ### Create database role
45 |
46 | create role with login password '';
47 | grant pg_monitor to ;
48 |
49 | ### Enable pg_stat_statements
50 |
51 | create extension pg_stat_statements;
52 | select * from pg_stat_statements; -- to check
53 |
54 | ### Run
55 |
56 | docker run --detach --name coroot-pg-agent \
57 | --env DSN="postgresql://:@:5432/postgres?connect_timeout=1&statement_timeout=30000" \
58 | ghcr.io/coroot/coroot-pg-agent
59 |
60 | ## Metrics
61 |
62 | The collected metrics are described [here](https://docs.coroot.com/metrics/cluster-agent#postgres).
63 |
64 | ## License
65 |
66 | Coroot-pg-agent is licensed under the [Apache License, Version 2.0](https://github.com/coroot/coroot-node-agent/blob/main/LICENSE).
67 |
--------------------------------------------------------------------------------
/collector/collector.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "context"
5 | "database/sql"
6 | "strings"
7 | "sync"
8 | "time"
9 |
10 | "github.com/blang/semver"
11 | "github.com/coroot/logger"
12 | _ "github.com/lib/pq"
13 | "github.com/prometheus/client_golang/prometheus"
14 | )
15 |
16 | const (
17 | topQueriesN = 20
18 | hardQuerySizeLimit = 4096
19 | )
20 |
21 | var (
22 | dUp = desc("pg_up", "Is the server reachable")
23 | dProbe = desc("pg_probe_seconds", "Empty query execution time")
24 | dScrapeError = desc("pg_scrape_error", "Scrape error", "error", "warning")
25 |
26 | dInfo = desc("pg_info", "Server info", "server_version")
27 | dSettings = desc("pg_setting", "Value of the pg_setting variable", "name", "unit")
28 |
29 | dConnections = desc("pg_connections", "Number of database connections", "db", "user", "state", "wait_event_type", "query")
30 |
31 | dLatency = desc("pg_latency_seconds", "Query execution time", "summary")
32 |
33 | dDbQueries = desc("pg_db_queries_per_second", "Number of queries executed in the database per second", "db")
34 |
35 | dTopQueryCalls = desc("pg_top_query_calls_per_second", "Number of times the query was executed", "db", "user", "query")
36 | dTopQueryTime = desc("pg_top_query_time_per_second", "Time spent executing the query", "db", "user", "query")
37 | dTopQueryIOTime = desc("pg_top_query_io_time_per_second", "Time the query spent awaiting IO", "db", "user", "query")
38 |
39 | dLockAwaitingQueries = desc("pg_lock_awaiting_queries", "Number of queries awaiting a lock", "db", "user", "blocking_query")
40 |
41 | dWalReceiverStatus = desc("pg_wal_receiver_status", "WAL receiver status: 1 if the receiver is connected, otherwise 0", "sender_host", "sender_port")
42 | dWalReplayPaused = desc("pg_wal_replay_paused", "Whether WAL replay paused or not")
43 | dWalCurrentLsn = desc("pg_wal_current_lsn", "Current WAL sequence number")
44 | dWalReceiveLsn = desc("pg_wal_receive_lsn", "WAL sequence number that has been received and synced to disk by streaming replication")
45 | dWalReplyLsn = desc("pg_wal_reply_lsn", "WAL sequence number that has been replayed during recovery")
46 | )
47 |
48 | type QueryKey struct {
49 | Query string
50 | DB string
51 | User string
52 | }
53 |
54 | func (k QueryKey) EqualByQueryPrefix(other QueryKey) bool {
55 | if k.User != other.User || k.DB != other.DB {
56 | return false
57 | }
58 | if strings.HasPrefix(k.Query, other.Query) {
59 | return true
60 | }
61 | return false
62 | }
63 |
64 | type ConnectionKey struct {
65 | QueryKey
66 | State string
67 | WaitEventType string
68 | }
69 |
70 | type Collector struct {
71 | ctx context.Context
72 | ctxCancelFunc context.CancelFunc
73 |
74 | scrapeInterval time.Duration
75 | collectTimeout time.Duration
76 |
77 | db *sql.DB
78 | origVersion string
79 |
80 | statsDumpInterval time.Duration
81 | ssCurr *ssSnapshot
82 | ssPrev *ssSnapshot
83 | saCurr *saSnapshot
84 | saPrev *saSnapshot
85 | settings []Setting
86 | replicationStatus *replicationStatus
87 | scrapeErrors map[string]bool
88 |
89 | lock sync.RWMutex
90 | logger logger.Logger
91 | }
92 |
93 | func New(dsn string, scrapeInterval, collectTimeout time.Duration, logger logger.Logger) (*Collector, error) {
94 | ctx, cancelFunc := context.WithCancel(context.Background())
95 | c := &Collector{
96 | ctx: ctx,
97 | logger: logger,
98 | ctxCancelFunc: cancelFunc,
99 | scrapeErrors: map[string]bool{},
100 | scrapeInterval: scrapeInterval,
101 | collectTimeout: collectTimeout,
102 | }
103 | var err error
104 | c.db, err = sql.Open("postgres", dsn)
105 | if err != nil {
106 | return nil, err
107 | }
108 | c.db.SetMaxOpenConns(1)
109 | pingCtx, pingCancelFunc := context.WithTimeout(ctx, collectTimeout)
110 | defer pingCancelFunc()
111 | if err := c.db.PingContext(pingCtx); err != nil {
112 | c.logger.Warning("probe failed:", err)
113 | }
114 | go func() {
115 | ticker := time.NewTicker(scrapeInterval)
116 | c.snapshot()
117 | for {
118 | select {
119 | case <-ticker.C:
120 | c.snapshot()
121 | case <-ctx.Done():
122 | c.logger.Info("stopping pg collector")
123 | return
124 | }
125 | }
126 | }()
127 | return c, nil
128 | }
129 |
130 | func (c *Collector) snapshot() {
131 | timeout := c.scrapeInterval - time.Second
132 | if timeout <= 0 {
133 | timeout = time.Second
134 | }
135 |
136 | ctx, cancelFunc := context.WithTimeout(c.ctx, timeout)
137 | defer cancelFunc()
138 | c.lock.Lock()
139 | defer c.lock.Unlock()
140 |
141 | c.scrapeErrors = map[string]bool{}
142 |
143 | c.origVersion = ""
144 | var version semver.Version
145 | var rawVersion string
146 | err := c.db.QueryRowContext(ctx, `SELECT setting FROM pg_settings WHERE name='server_version'`).Scan(&rawVersion)
147 | if err != nil {
148 | c.logger.Warning(err)
149 | c.scrapeErrors[err.Error()] = true
150 | return
151 | }
152 | c.origVersion, version, err = parsePgVersion(rawVersion)
153 | if err != nil {
154 | c.logger.Warning(err)
155 | c.scrapeErrors[err.Error()] = true
156 | return
157 | }
158 |
159 | if c.settings, err = c.getSettings(ctx); err != nil {
160 | c.scrapeErrors[err.Error()] = true
161 | c.logger.Warning(err)
162 | }
163 |
164 | if c.replicationStatus, err = c.getReplicationStatus(ctx, version); err != nil {
165 | c.scrapeErrors[err.Error()] = true
166 | c.logger.Warning(err)
167 | }
168 |
169 | querySizeLimit := 0
170 | for _, s := range c.settings {
171 | if s.Name == "track_activity_query_size" {
172 | switch s.Unit {
173 | case "B":
174 | querySizeLimit = int(s.Value)
175 | case "kB":
176 | querySizeLimit = int(s.Value) * 1024
177 | default:
178 | querySizeLimit = int(s.Value)
179 | }
180 | break
181 | }
182 | }
183 | if querySizeLimit == 0 || querySizeLimit > hardQuerySizeLimit {
184 | querySizeLimit = hardQuerySizeLimit
185 | }
186 |
187 | c.ssPrev = c.ssCurr
188 | c.saPrev = c.saCurr
189 | prevStatements := map[statementId]ssRow{}
190 | if c.ssPrev != nil {
191 | prevStatements = c.ssPrev.rows
192 | }
193 | c.ssCurr, err = c.getStatStatements(ctx, version, querySizeLimit, prevStatements)
194 | if err != nil {
195 | c.logger.Warning(err)
196 | c.scrapeErrors[err.Error()] = true
197 | return
198 | }
199 | c.saCurr, err = c.getPgStatActivity(ctx, version, querySizeLimit)
200 | if err != nil {
201 | c.logger.Warning(err)
202 | c.scrapeErrors[err.Error()] = true
203 | return
204 | }
205 | }
206 |
207 | func (c *Collector) summaries() (map[QueryKey]*QuerySummary, time.Duration) {
208 | if c.saCurr == nil || c.saPrev == nil || c.ssCurr == nil || c.ssPrev == nil {
209 | return nil, 0
210 | }
211 | res := map[QueryKey]*QuerySummary{}
212 | getOrCreateSummary := func(k QueryKey, searchByPrefix bool) *QuerySummary {
213 | s := res[k]
214 | if s == nil && searchByPrefix {
215 | for qk, ss := range res {
216 | if qk.EqualByQueryPrefix(k) {
217 | s = ss
218 | break
219 | }
220 | }
221 | }
222 | if s == nil {
223 | s = &QuerySummary{}
224 | res[k] = s
225 | }
226 | return s
227 | }
228 |
229 | for id, r := range c.ssCurr.rows {
230 | getOrCreateSummary(r.QueryKey(id), false).updateFromStatStatements(r, c.ssPrev.rows[id])
231 | }
232 | for _, conn := range c.saCurr.connections {
233 | getOrCreateSummary(conn.QueryKey(), true).updateFromStatActivity(c.saPrev.ts, c.saCurr.ts, conn)
234 | }
235 | for pid, prev := range c.saPrev.connections {
236 | if !prev.IsClientBackend() || prev.State.String != "active" {
237 | continue
238 | }
239 | curr, ok := c.saCurr.connections[pid]
240 | if ok && curr.State.String == "active" && curr.QueryStart.Time.Equal(prev.QueryStart.Time) { // still executing
241 | continue
242 | }
243 | // prev query finished
244 | getOrCreateSummary(prev.QueryKey(), true).correctFromPrevStatActivity(c.saPrev.ts, prev)
245 | }
246 | return res, c.ssCurr.ts.Sub(c.ssPrev.ts)
247 | }
248 |
249 | func (c *Collector) connectionMetrics(ch chan<- prometheus.Metric) {
250 | if c.saCurr == nil {
251 | return
252 | }
253 | byPid := map[int]QueryKey{}
254 | awaitingQueriesByBlockingPid := map[int]float64{}
255 | connectionsByKey := map[ConnectionKey]float64{}
256 |
257 | for pid, conn := range c.saCurr.connections {
258 | queryKey := conn.QueryKey()
259 | byPid[pid] = queryKey
260 | if conn.BlockingPid.Int32 > 0 {
261 | awaitingQueriesByBlockingPid[int(conn.BlockingPid.Int32)]++
262 | }
263 | key := ConnectionKey{
264 | QueryKey: queryKey,
265 | State: conn.State.String,
266 | WaitEventType: conn.WaitEventType.String,
267 | }
268 | connectionsByKey[key]++
269 | }
270 |
271 | for k, count := range connectionsByKey {
272 | ch <- gauge(dConnections, count, k.DB, k.User, k.State, k.WaitEventType, k.Query)
273 | }
274 |
275 | awaitingQueriesByBlockingQuery := map[QueryKey]float64{}
276 | for blockingPid, awaitingQueries := range awaitingQueriesByBlockingPid {
277 | blockingQuery, ok := byPid[blockingPid]
278 | if !ok {
279 | continue
280 | }
281 | awaitingQueriesByBlockingQuery[blockingQuery] += awaitingQueries
282 | }
283 | for blockingQuery, awaitingQueries := range awaitingQueriesByBlockingQuery {
284 | ch <- gauge(dLockAwaitingQueries, awaitingQueries, blockingQuery.DB, blockingQuery.User, blockingQuery.Query)
285 | }
286 | }
287 |
288 | func (c *Collector) queryMetrics(ch chan<- prometheus.Metric) {
289 | summaries, interval := c.summaries()
290 | if summaries == nil {
291 | c.logger.Warning("no summaries")
292 | return
293 | }
294 |
295 | latency := NewLatencySummary()
296 | queriesByDB := map[string]float64{}
297 | for k, summary := range summaries {
298 | latency.Add(summary.TotalTime, uint64(summary.Queries))
299 | queriesByDB[k.DB] += summary.Queries
300 | }
301 | for s, v := range latency.GetSummaries(50, 75, 95, 99) {
302 | ch <- gauge(dLatency, v, s)
303 | }
304 |
305 | for db, queries := range queriesByDB {
306 | ch <- gauge(dDbQueries, queries/interval.Seconds(), db)
307 | }
308 |
309 | for k, summary := range top(summaries, topQueriesN) {
310 | ch <- gauge(dTopQueryCalls, summary.Queries/interval.Seconds(), k.DB, k.User, k.Query)
311 | ch <- gauge(dTopQueryTime, summary.TotalTime/interval.Seconds(), k.DB, k.User, k.Query)
312 | ch <- gauge(dTopQueryIOTime, summary.IOTime/interval.Seconds(), k.DB, k.User, k.Query)
313 | }
314 | }
315 |
316 | func (c *Collector) Close() error {
317 | c.ctxCancelFunc()
318 | return c.db.Close()
319 | }
320 |
321 | func (c *Collector) Collect(ch chan<- prometheus.Metric) {
322 | ctx, cancelFunc := context.WithTimeout(c.ctx, c.collectTimeout)
323 | defer cancelFunc()
324 | now := time.Now()
325 | if err := c.db.PingContext(ctx); err != nil {
326 | c.logger.Warning("probe failed:", err)
327 | ch <- gauge(dUp, 0)
328 | ch <- gauge(dScrapeError, 1, err.Error(), "")
329 | return
330 | }
331 | ch <- gauge(dUp, 1)
332 | ch <- gauge(dProbe, time.Since(now).Seconds())
333 | if c.origVersion != "" {
334 | ch <- gauge(dInfo, 1, c.origVersion)
335 | }
336 |
337 | c.lock.RLock()
338 | defer c.lock.RUnlock()
339 |
340 | if len(c.scrapeErrors) > 0 {
341 | for e := range c.scrapeErrors {
342 | ch <- gauge(dScrapeError, 1, "", e)
343 | }
344 | } else {
345 | ch <- gauge(dScrapeError, 0, "", "")
346 | }
347 |
348 | c.connectionMetrics(ch)
349 | c.queryMetrics(ch)
350 | for _, s := range c.settings {
351 | ch <- gauge(dSettings, s.Value, s.Name, s.Unit)
352 | }
353 |
354 | if c.replicationStatus != nil {
355 | rs := c.replicationStatus
356 | if rs.isInRecovery {
357 | if rs.receiveLsn.Valid {
358 | ch <- counter(dWalReceiveLsn, float64(rs.receiveLsn.Int64))
359 | }
360 | if rs.replyLsn.Valid {
361 | ch <- counter(dWalReplyLsn, float64(rs.replyLsn.Int64))
362 | }
363 | isReplayPaused := 0.0
364 | if rs.isReplayPaused {
365 | isReplayPaused = 1.0
366 | }
367 | ch <- gauge(dWalReplayPaused, isReplayPaused)
368 | host, port, err := rs.primaryHostPort()
369 | if err != nil {
370 | c.logger.Warning(err)
371 | }
372 | ch <- gauge(dWalReceiverStatus, float64(rs.walReceiverStatus), host, port)
373 | } else {
374 | if rs.currentLsn.Valid {
375 | ch <- counter(dWalCurrentLsn, float64(rs.currentLsn.Int64))
376 | }
377 | }
378 | }
379 | }
380 |
381 | func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
382 | ch <- dUp
383 | ch <- dProbe
384 | ch <- dScrapeError
385 | ch <- dInfo
386 | ch <- dConnections
387 | ch <- dLatency
388 | ch <- dLockAwaitingQueries
389 | ch <- dSettings
390 | ch <- dTopQueryCalls
391 | ch <- dTopQueryTime
392 | ch <- dTopQueryIOTime
393 | ch <- dDbQueries
394 | ch <- dWalReceiverStatus
395 | ch <- dWalReplayPaused
396 | ch <- dWalCurrentLsn
397 | ch <- dWalReceiveLsn
398 | ch <- dWalReplyLsn
399 | }
400 |
401 | func desc(name, help string, labels ...string) *prometheus.Desc {
402 | return prometheus.NewDesc(name, help, labels, nil)
403 | }
404 |
405 | func gauge(desc *prometheus.Desc, value float64, labels ...string) prometheus.Metric {
406 | return prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, value, labels...)
407 | }
408 |
409 | func counter(desc *prometheus.Desc, value float64, labels ...string) prometheus.Metric {
410 | return prometheus.MustNewConstMetric(desc, prometheus.CounterValue, value, labels...)
411 | }
412 |
--------------------------------------------------------------------------------
/collector/latency_summary.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "github.com/dustin/go-humanize"
5 | "sort"
6 | )
7 |
8 | type Batch struct {
9 | avg float64
10 | events uint64
11 | }
12 |
13 | type LatencySummary struct {
14 | totalEvents uint64
15 | totalTime float64
16 | batches []Batch
17 | }
18 |
19 | func NewLatencySummary() *LatencySummary {
20 | return &LatencySummary{}
21 | }
22 |
23 | func (s *LatencySummary) Add(totalTime float64, numberOfEvents uint64) {
24 | if numberOfEvents == 0 {
25 | return
26 | }
27 | s.totalEvents += numberOfEvents
28 | s.totalTime += totalTime
29 | s.batches = append(s.batches, Batch{avg: totalTime / float64(numberOfEvents), events: numberOfEvents})
30 | }
31 |
32 | func (s *LatencySummary) GetCalls() float64 {
33 | return float64(s.totalEvents)
34 | }
35 |
36 | func (s *LatencySummary) GetTotalTime() float64 {
37 | return s.totalTime
38 | }
39 |
40 | func (s *LatencySummary) GetSummaries(percentiles ...float64) map[string]float64 {
41 | if len(s.batches) == 0 || len(percentiles) == 0 {
42 | return nil
43 | }
44 | sort.Slice(s.batches, func(i, j int) bool {
45 | return s.batches[i].avg < s.batches[j].avg
46 | })
47 | res := map[string]float64{
48 | "avg": s.totalTime / float64(s.totalEvents),
49 | "max": s.batches[len(s.batches)-1].avg,
50 | }
51 |
52 | for _, p := range percentiles {
53 | q := p / 100
54 | if q <= 0 || q > 1 {
55 | return nil
56 | }
57 | idx := uint64(float64(s.totalEvents) * q)
58 | var counter uint64
59 | for _, b := range s.batches {
60 | counter += b.events
61 | if counter >= idx {
62 | res["p"+humanize.Ftoa(p)] = b.avg
63 | break
64 | }
65 | }
66 | }
67 | return res
68 | }
69 |
--------------------------------------------------------------------------------
/collector/latency_summary_test.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "github.com/stretchr/testify/assert"
5 | "testing"
6 | )
7 |
8 | func TestLatencySummary(t *testing.T) {
9 | s := NewLatencySummary()
10 | s.Add(0, 0)
11 | assert.Nil(t, s.GetSummaries(0.5))
12 |
13 | s.Add(0.1*50, 50)
14 | s.Add(0.2*40, 40)
15 | s.Add(0.3*10, 10)
16 |
17 | assert.Nil(t, s.GetSummaries())
18 | assert.Nil(t, s.GetSummaries(-1))
19 | assert.Nil(t, s.GetSummaries(200))
20 |
21 | assert.Equal(t,
22 | map[string]float64{
23 | "avg": 0.16,
24 | "max": 0.3,
25 | "p50": 0.1,
26 | "p90": 0.2,
27 | "p95": 0.3,
28 | },
29 | s.GetSummaries(50, 90, 95),
30 | )
31 | }
32 |
--------------------------------------------------------------------------------
/collector/pg_replication.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "context"
5 | "database/sql"
6 | "errors"
7 | "fmt"
8 | "net/url"
9 | "regexp"
10 | "strings"
11 |
12 | "github.com/blang/semver"
13 | )
14 |
15 | var (
16 | valueRe = `\s*=[\s']*([^\s']+)`
17 | hostRe = regexp.MustCompile("host" + valueRe)
18 | hostaddrRe = regexp.MustCompile("hostaddr" + valueRe)
19 | portRe = regexp.MustCompile("port" + valueRe)
20 | )
21 |
22 | func findValue(src string, re *regexp.Regexp) string {
23 | res := re.FindStringSubmatch(src)
24 | if len(res) < 2 {
25 | return ""
26 | }
27 | return res[1]
28 | }
29 |
30 | type replicationStatus struct {
31 | isInRecovery bool
32 |
33 | currentLsn sql.NullInt64
34 | receiveLsn sql.NullInt64
35 | replyLsn sql.NullInt64
36 |
37 | isReplayPaused bool
38 |
39 | walReceiverStatus int64
40 | primaryConnectionInfo string
41 | }
42 |
43 | func (rs *replicationStatus) primaryHostPort() (string, string, error) {
44 | ci := rs.primaryConnectionInfo
45 | if strings.HasPrefix(ci, "postgres://") || strings.HasPrefix(ci, "postgresql://") {
46 | u, err := url.Parse(ci)
47 | if err != nil {
48 | // don't log url.Parse errors since they might contain security sensitive data
49 | return "", "", fmt.Errorf("failed to parse primary_conninfo")
50 | }
51 | return u.Hostname(), u.Port(), nil
52 | }
53 | host := findValue(ci, hostRe)
54 | if host == "" {
55 | host = findValue(ci, hostaddrRe)
56 | }
57 | port := findValue(ci, portRe)
58 | return host, port, nil
59 | }
60 |
61 | func (c *Collector) getReplicationStatus(ctx context.Context, version semver.Version) (*replicationStatus, error) {
62 | var isInRecovery sql.NullBool
63 | if err := c.db.QueryRowContext(ctx, `SELECT pg_is_in_recovery()`).Scan(&isInRecovery); err != nil {
64 | return nil, err
65 | }
66 |
67 | if !isInRecovery.Valid {
68 | return nil, fmt.Errorf("pg_is_in_recovery() returned null")
69 | }
70 |
71 | var fCurrentLsn, fReceiveLsn, fReplyLsn, fIsReplayPaused string
72 | switch {
73 | // the `pg_stat_wal_receiver` view has been introduced in 9.6
74 | case semver.MustParseRange(">=9.6.0 <10.0.0")(version):
75 | fCurrentLsn = "pg_current_xlog_location"
76 | fReceiveLsn = "pg_last_xlog_receive_location"
77 | fReplyLsn = "pg_last_xlog_replay_location"
78 | fIsReplayPaused = "pg_is_xlog_replay_paused"
79 | case semver.MustParseRange(">=10.0.0")(version):
80 | fCurrentLsn = "pg_current_wal_lsn"
81 | fReceiveLsn = "pg_last_wal_receive_lsn"
82 | fReplyLsn = "pg_last_wal_replay_lsn"
83 | fIsReplayPaused = "pg_is_wal_replay_paused"
84 | default:
85 | return nil, fmt.Errorf("postgres version %s is not supported", version)
86 | }
87 |
88 | rs := &replicationStatus{isInRecovery: isInRecovery.Bool}
89 | if rs.isInRecovery {
90 | if err := c.db.QueryRowContext(ctx, fmt.Sprintf(
91 | `SELECT %s()-'0/0', %s()-'0/0', %s()`, fReceiveLsn, fReplyLsn, fIsReplayPaused)).Scan(
92 | &rs.receiveLsn, &rs.replyLsn, &rs.isReplayPaused); err != nil {
93 | return nil, err
94 | }
95 | if err := c.db.QueryRowContext(ctx, `SELECT count(1) FROM pg_stat_wal_receiver`).Scan(&rs.walReceiverStatus); err != nil {
96 | return nil, err
97 | }
98 | if err := c.db.QueryRowContext(ctx, `SELECT setting FROM pg_settings WHERE name='primary_conninfo'`).Scan(&rs.primaryConnectionInfo); err != nil {
99 | if !errors.Is(err, sql.ErrNoRows) {
100 | return nil, err
101 | }
102 | }
103 | } else {
104 | if err := c.db.QueryRowContext(ctx, fmt.Sprintf(`SELECT %s()-'0/0'`, fCurrentLsn)).Scan(&rs.currentLsn); err != nil {
105 | return nil, err
106 | }
107 | }
108 | return rs, nil
109 | }
110 |
--------------------------------------------------------------------------------
/collector/pg_replication_test.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "github.com/stretchr/testify/assert"
5 | "testing"
6 | )
7 |
8 | func Test_parsePrimaryConnectionInfo(t *testing.T) {
9 | check := func(src string, host, port string) {
10 | rs := replicationStatus{primaryConnectionInfo: src}
11 | h, p, err := rs.primaryHostPort()
12 | assert.NoError(t, err)
13 | assert.Equal(t, host, h)
14 | assert.Equal(t, port, p)
15 | }
16 |
17 | check("host=127.0.0.1 port=5432", "127.0.0.1", "5432")
18 | check("host=127.0.0.1", "127.0.0.1", "")
19 |
20 | check("host = 127.0.0.1 port = 5432", "127.0.0.1", "5432")
21 | check("host = '127.0.0.1' port = 5432", "127.0.0.1", "5432")
22 | check("host = ' 127.0.0.1 ' port = 5432", "127.0.0.1", "5432")
23 |
24 | check("hostaddr=127.0.0.1 port=5432", "127.0.0.1", "5432")
25 |
26 | check("postgresql://localhost:5433", "localhost", "5433")
27 | check("postgres://localhost:5433", "localhost", "5433")
28 | check("postgresql://user:secret@localhost", "localhost", "")
29 | check("postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp", "localhost", "")
30 | check("postgresql://[2001:db8::1234]/database", "2001:db8::1234", "")
31 | }
32 |
--------------------------------------------------------------------------------
/collector/pg_settings.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "context"
5 | "database/sql"
6 | "strconv"
7 | )
8 |
9 | type Setting struct {
10 | Name string
11 | Unit string
12 | Value float64
13 | }
14 |
15 | func (c *Collector) getSettings(ctx context.Context) ([]Setting, error) {
16 | rows, err := c.db.QueryContext(ctx, `SELECT name, setting, unit, vartype FROM pg_settings WHERE vartype in ('integer','real', 'bool')`)
17 | if err != nil {
18 | return nil, err
19 | }
20 | defer rows.Close()
21 |
22 | var res []Setting
23 | for rows.Next() {
24 | var name, value, unit, vartype sql.NullString
25 | err := rows.Scan(&name, &value, &unit, &vartype)
26 | if err != nil {
27 | c.logger.Warning("failed to scan pg_settings row:", err)
28 | continue
29 | }
30 | var v float64
31 | switch vartype.String {
32 | case "integer", "real":
33 | v, err = strconv.ParseFloat(value.String, 64)
34 | if err != nil {
35 | c.logger.Warningf("failed to parse value for %s=%s setting: %s", name.String, value.String, err)
36 | continue
37 | }
38 | case "bool":
39 | if value.String == "on" {
40 | v = 1.
41 | }
42 | default:
43 | continue
44 | }
45 | res = append(res, Setting{Name: name.String, Unit: unit.String, Value: v})
46 | }
47 | return res, nil
48 | }
49 |
--------------------------------------------------------------------------------
/collector/pg_stat_activity.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "context"
5 | "database/sql"
6 | "fmt"
7 | "strings"
8 | "time"
9 |
10 | "github.com/blang/semver"
11 | "github.com/coroot/coroot-pg-agent/obfuscate"
12 | )
13 |
14 | type Connection struct {
15 | DB sql.NullString
16 | User sql.NullString
17 | Query sql.NullString
18 | State sql.NullString
19 | QueryStart sql.NullTime
20 | BackendType sql.NullString
21 | WaitEventType sql.NullString
22 | BlockingPid sql.NullInt32
23 | }
24 |
25 | func (c Connection) IsClientBackend() bool {
26 | return c.BackendType.String == "" || c.BackendType.String == "client backend"
27 | }
28 |
29 | func (c Connection) QueryKey() QueryKey {
30 | return QueryKey{Query: obfuscate.Sql(c.Query.String), User: c.User.String, DB: c.DB.String}
31 | }
32 |
33 | type saSnapshot struct {
34 | ts time.Time
35 | connections map[int]Connection
36 | }
37 |
38 | func (c *Collector) getPgStatActivity(ctx context.Context, version semver.Version, querySizeLimit int) (*saSnapshot, error) {
39 | snapshot := &saSnapshot{connections: map[int]Connection{}}
40 | var query string
41 | switch {
42 | case semver.MustParseRange(">=9.3.0 <9.6.0")(version):
43 | query = "SELECT s.pid, s.datname, s.usename, LEFT(s.query, %d), s.state, now(), s.query_start, s.waiting, null, null, null"
44 | case semver.MustParseRange(">=9.6.0 <10.0.0")(version):
45 | query = "SELECT s.pid, s.datname, s.usename, LEFT(s.query, %d), s.state, now(), s.query_start, null, s.wait_event_type, null, (pg_blocking_pids(s.pid))[1]"
46 | case semver.MustParseRange(">=10.0.0")(version):
47 | query = "SELECT s.pid, s.datname, s.usename, LEFT(s.query, %d), s.state, now(), s.query_start, null, s.wait_event_type, s.backend_type, (pg_blocking_pids(s.pid))[1]"
48 | default:
49 | return nil, fmt.Errorf("postgres version %s is not supported", version)
50 | }
51 | query += " FROM pg_stat_activity s JOIN pg_database d ON s.datid = d.oid AND NOT d.datistemplate"
52 | rows, err := c.db.QueryContext(ctx, fmt.Sprintf(query, querySizeLimit))
53 | if err != nil {
54 | return nil, err
55 | }
56 | defer rows.Close()
57 |
58 | for rows.Next() {
59 | var (
60 | conn Connection
61 | pid int
62 | oldStyleWaiting sql.NullBool
63 | )
64 | err := rows.Scan(
65 | &pid, &conn.DB, &conn.User, &conn.Query, &conn.State, &snapshot.ts, &conn.QueryStart,
66 | &oldStyleWaiting, &conn.WaitEventType, &conn.BackendType, &conn.BlockingPid,
67 | )
68 | if err != nil {
69 | c.logger.Warning("failed to scan pg_stat_activity row:", err)
70 | continue
71 | }
72 | if conn.DB.String == "" || conn.User.String == "" || conn.State.String == "" {
73 | continue
74 | }
75 | if oldStyleWaiting.Bool {
76 | conn.WaitEventType.String = "Lock"
77 | }
78 | if conn.State.String != "active" && !strings.HasPrefix(conn.State.String, "idle in transaction") {
79 | conn.Query.String = ""
80 | }
81 | snapshot.connections[pid] = conn
82 | }
83 | return snapshot, nil
84 | }
85 |
--------------------------------------------------------------------------------
/collector/pg_stat_statements.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "context"
5 | "database/sql"
6 | "fmt"
7 | "time"
8 |
9 | "github.com/blang/semver"
10 | "github.com/coroot/coroot-pg-agent/obfuscate"
11 | )
12 |
13 | type ssRow struct {
14 | obfuscatedQueryText string
15 | calls sql.NullInt64
16 | rows sql.NullInt64
17 | totalTime sql.NullFloat64
18 | ioTime sql.NullFloat64
19 | }
20 |
21 | func (r ssRow) QueryKey(id statementId) QueryKey {
22 | return QueryKey{Query: r.obfuscatedQueryText, User: id.user.String, DB: id.db.String}
23 | }
24 |
25 | type statementId struct {
26 | id sql.NullInt64
27 | user sql.NullString
28 | db sql.NullString
29 | }
30 |
31 | type ssSnapshot struct {
32 | ts time.Time
33 | rows map[statementId]ssRow
34 | }
35 |
36 | func (c *Collector) getStatStatements(ctx context.Context, version semver.Version, querySizeLimit int, prev map[statementId]ssRow) (*ssSnapshot, error) {
37 | snapshot := &ssSnapshot{ts: time.Now(), rows: map[statementId]ssRow{}}
38 | var query string
39 | switch {
40 | case semver.MustParseRange(">=9.4.0 <13.0.0")(version):
41 | query = `SELECT d.datname, r.rolname, LEFT(s.query, %d), s.queryid, s.calls, s.total_time, s.blk_read_time + s.blk_write_time`
42 | case semver.MustParseRange(">=13.0.0 <17.0.0")(version):
43 | query = `SELECT d.datname, r.rolname, LEFT(s.query, %d), s.queryid, s.calls, s.total_plan_time + s.total_exec_time, s.blk_read_time + s.blk_write_time`
44 | case semver.MustParseRange(">=17.0.0")(version):
45 | query = `SELECT d.datname, r.rolname, LEFT(s.query, %d), s.queryid, s.calls, s.total_plan_time + s.total_exec_time, s.shared_blk_read_time + s.shared_blk_write_time + s.local_blk_read_time + s.local_blk_write_time + s.temp_blk_read_time + s.temp_blk_write_time`
46 | default:
47 | return nil, fmt.Errorf("postgres version %s is not supported", version)
48 | }
49 | query += ` FROM pg_stat_statements s JOIN pg_roles r ON r.oid=s.userid JOIN pg_database d ON d.oid=s.dbid AND NOT d.datistemplate`
50 | rows, err := c.db.QueryContext(ctx, fmt.Sprintf(query, querySizeLimit))
51 | if err != nil {
52 | return nil, err
53 | }
54 | defer rows.Close()
55 | var queryText sql.NullString
56 | for rows.Next() {
57 | var id statementId
58 | r := ssRow{}
59 | err := rows.Scan(&id.db, &id.user, &queryText, &id.id, &r.calls, &r.totalTime, &r.ioTime)
60 | if err != nil {
61 | c.logger.Warning("failed to scan pg_stat_statements row:", err)
62 | continue
63 | }
64 | if id.user.String == "" || id.db.String == "" || !id.id.Valid {
65 | continue
66 | }
67 | if p, ok := prev[id]; ok {
68 | r.obfuscatedQueryText = p.obfuscatedQueryText
69 | } else {
70 | r.obfuscatedQueryText = obfuscate.Sql(queryText.String)
71 | }
72 | snapshot.rows[id] = r
73 | }
74 | return snapshot, nil
75 | }
76 |
--------------------------------------------------------------------------------
/collector/query_summary.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "sort"
5 | "time"
6 | )
7 |
8 | type QuerySummary struct {
9 | Queries float64
10 | TotalTime float64
11 | IOTime float64
12 | }
13 |
14 | func (s *QuerySummary) updateFromStatActivity(prevTs, ts time.Time, conn Connection) {
15 | if conn.State.String != "active" {
16 | return
17 | }
18 | if !conn.QueryStart.Valid {
19 | return
20 | }
21 | duration := ts.Sub(conn.QueryStart.Time)
22 | if duration < 0 {
23 | return
24 | }
25 | interval := ts.Sub(prevTs)
26 | if duration > interval {
27 | duration = interval
28 | }
29 | if conn.IsClientBackend() {
30 | s.Queries += 1
31 | s.TotalTime += duration.Seconds()
32 | }
33 | if conn.WaitEventType.String == "IO" {
34 | s.IOTime += duration.Seconds()
35 | }
36 | }
37 |
38 | func (s *QuerySummary) correctFromPrevStatActivity(ts time.Time, conn Connection) {
39 | if !conn.QueryStart.Valid {
40 | return
41 | }
42 | duration := ts.Sub(conn.QueryStart.Time).Seconds()
43 | if duration < 0 {
44 | return
45 | }
46 | if conn.IsClientBackend() && s.Queries > 0 && s.TotalTime > duration {
47 | s.Queries -= 1
48 | s.TotalTime -= duration
49 | }
50 | if conn.WaitEventType.String == "IO" && s.IOTime > duration {
51 | s.IOTime -= duration
52 | }
53 | }
54 |
55 | func (s *QuerySummary) updateFromStatStatements(cur, prev ssRow) {
56 | callsDelta := float64(cur.calls.Int64 - prev.calls.Int64)
57 | totalTimeDelta := (cur.totalTime.Float64 - prev.totalTime.Float64) / 1000
58 | ioTimeDelta := (cur.ioTime.Float64 - prev.ioTime.Float64) / 1000
59 | if totalTimeDelta < 0 || callsDelta < 0 || ioTimeDelta < 0 {
60 | return
61 | }
62 | s.Queries += callsDelta
63 | s.TotalTime += totalTimeDelta
64 | s.IOTime += ioTimeDelta
65 | }
66 |
67 | type summaryWithKey struct {
68 | key QueryKey
69 | last float64
70 | summary *QuerySummary
71 | }
72 |
73 | func top(all map[QueryKey]*QuerySummary, n int) map[QueryKey]*QuerySummary {
74 | withKeys := make([]summaryWithKey, 0, len(all))
75 | for k, s := range all {
76 | withKeys = append(withKeys, summaryWithKey{key: k, summary: s, last: s.TotalTime})
77 | }
78 | sort.Slice(withKeys, func(i, j int) bool {
79 | return withKeys[i].last > withKeys[j].last
80 | })
81 | if n > len(withKeys) {
82 | n = len(withKeys)
83 | }
84 | res := make(map[QueryKey]*QuerySummary, n)
85 | for _, i := range withKeys[:n] {
86 | res[i.key] = i.summary
87 | }
88 | return res
89 | }
90 |
--------------------------------------------------------------------------------
/collector/version.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "github.com/blang/semver"
5 | "regexp"
6 | "strings"
7 | )
8 |
9 | var trimVersionRe = regexp.MustCompile("[^0-9.].*")
10 |
11 | func parsePgVersion(v string) (string, semver.Version, error) {
12 | original := strings.Fields(v)[0]
13 | version, err := semver.ParseTolerant(trimVersionRe.ReplaceAllString(v, ""))
14 | if err != nil {
15 | original = ""
16 | }
17 | return original, version, err
18 | }
19 |
--------------------------------------------------------------------------------
/collector/version_test.go:
--------------------------------------------------------------------------------
1 | package collector
2 |
3 | import (
4 | "github.com/blang/semver"
5 | "github.com/stretchr/testify/assert"
6 | "testing"
7 | )
8 |
9 | func Test_parsePgVersion(t *testing.T) {
10 | check := func(src, orig string, ver semver.Version) {
11 | o, v, err := parsePgVersion(src)
12 | assert.Nil(t, err)
13 | assert.Equal(t, orig, o)
14 | assert.True(t, ver.Equals(v))
15 | }
16 | check("14.4 (Ubuntu 14.4-1.pgdg18.04+1)", "14.4", semver.Version{Major: 14, Minor: 4})
17 | check("9.4.1", "9.4.1", semver.Version{Major: 9, Minor: 4, Patch: 1})
18 | check("11.2-YB-2.15.0.1-b0", "11.2-YB-2.15.0.1-b0", semver.Version{Major: 11, Minor: 2})
19 | }
20 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/coroot/coroot-pg-agent
2 |
3 | go 1.16
4 |
5 | require (
6 | github.com/blang/semver v3.5.1+incompatible
7 | github.com/coroot/logger v1.0.0
8 | github.com/dustin/go-humanize v1.0.0
9 | github.com/lib/pq v1.10.3
10 | github.com/prometheus/client_golang v1.11.0
11 | github.com/stretchr/testify v1.6.1
12 | gopkg.in/alecthomas/kingpin.v2 v2.2.6
13 | )
14 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
3 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM=
4 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
5 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
6 | github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
7 | github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d h1:UQZhZ2O0vMHr2cI+DC1Mbh0TJxzA3RcLoMsFw+aXw7E=
8 | github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
9 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
10 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
11 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
12 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
13 | github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ=
14 | github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
15 | github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
16 | github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
17 | github.com/coroot/logger v1.0.0 h1:n8iNkGk6ete9wp/L49FXsZlNiySuA+IJ7TsTkYkiqPc=
18 | github.com/coroot/logger v1.0.0/go.mod h1:rEO5EQqDbB4bnCoo5Ot9Dj51Bkl40RUVqB03rba54HE=
19 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
20 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
21 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
22 | github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
23 | github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
24 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
25 | github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
26 | github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
27 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
28 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
29 | github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
30 | github.com/go-logr/logr v1.0.0 h1:kH951GinvFVaQgy/ki/B3YYmQtRpExGigSJg6O8z5jo=
31 | github.com/go-logr/logr v1.0.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
32 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
33 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
34 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
35 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
36 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
37 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
38 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
39 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
40 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
41 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
42 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
43 | github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=
44 | github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
45 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
46 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
47 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
48 | github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
49 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
50 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
51 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
52 | github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
53 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
54 | github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
55 | github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
56 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
57 | github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
58 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
59 | github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
60 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
61 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
62 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
63 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
64 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
65 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
66 | github.com/lib/pq v1.10.3 h1:v9QZf2Sn6AmjXtQeFpdoq/eaNtYP6IN+7lcrygsIAtg=
67 | github.com/lib/pq v1.10.3/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
68 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
69 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
70 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
71 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
72 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
73 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
74 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
75 | github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
76 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
77 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
78 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
79 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
80 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
81 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
82 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
83 | github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
84 | github.com/prometheus/client_golang v1.11.0 h1:HNkLOAEQMIDv/K+04rukrLx6ch7msSRwf3/SASFAGtQ=
85 | github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
86 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
87 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
88 | github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M=
89 | github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
90 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
91 | github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
92 | github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ=
93 | github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
94 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
95 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
96 | github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
97 | github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4=
98 | github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
99 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
100 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
101 | github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
102 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
103 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
104 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
105 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
106 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
107 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
108 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
109 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
110 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
111 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
112 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
113 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
114 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
115 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
116 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
117 | golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
118 | golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
119 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
120 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
121 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
122 | golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
123 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
124 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
125 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
126 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
127 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
128 | golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
129 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
130 | golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
131 | golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
132 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
133 | golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40 h1:JWgyZ1qgdTaF3N3oxC+MdTV7qvEEgHo3otj+HB5CM7Q=
134 | golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
135 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
136 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
137 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
138 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
139 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
140 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
141 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
142 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
143 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
144 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
145 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
146 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
147 | google.golang.org/protobuf v1.26.0-rc.1 h1:7QnIQpGRHE5RnLKnESfDoxm2dTapTZua5a0kS0A+VXQ=
148 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
149 | gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
150 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
151 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
152 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
153 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
154 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
155 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
156 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
157 | gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
158 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
159 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
160 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
161 | k8s.io/klog/v2 v2.20.0 h1:tlyxlSvd63k7axjhuchckaRJm+a92z5GSOrTOQY5sHw=
162 | k8s.io/klog/v2 v2.20.0/go.mod h1:Gm8eSIfQN6457haJuPaMxZw4wyP5k+ykPFlrhQDvhvw=
163 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net/http"
5 | _ "net/http/pprof"
6 |
7 | "github.com/coroot/coroot-pg-agent/collector"
8 | "github.com/coroot/logger"
9 | "github.com/prometheus/client_golang/prometheus"
10 | "github.com/prometheus/client_golang/prometheus/promhttp"
11 | "gopkg.in/alecthomas/kingpin.v2"
12 | )
13 |
14 | var version = "unknown"
15 |
16 | func main() {
17 | dsn := kingpin.Arg("dsn", `Data source name (env: DSN) - "postgresql://:@:5432/postgres?connect_timeout=1&statement_timeout=30000".`).Envar("DSN").Required().String()
18 | listen := kingpin.Flag("listen", `Listen address (env: LISTEN) - ":" or ":".`).Envar("LISTEN").Default("0.0.0.0:80").String()
19 | scrapeInterval := kingpin.Flag("scrape-interval", `How often to snapshot system views (env: PG_SCRAPE_INTERVAL)`).Envar("PG_SCRAPE_INTERVAL").Default("15s").Duration()
20 | collectTimeout := kingpin.Flag("collect-timeout", `Timeout for the entire collect operation`).Envar("PG_COLLECT_TIMEOUT").Default("5s").Duration()
21 | staticLabels := kingpin.Flag("label", `A static label:value pair to be added to all metrics (env: STATIC_LABELS)`).Envar("STATIC_LABELS").StringMap()
22 |
23 | kingpin.HelpFlag.Short('h').Hidden()
24 | kingpin.Version(version)
25 | kingpin.Parse()
26 |
27 | log := logger.NewKlog("")
28 |
29 | c, err := collector.New(*dsn, *scrapeInterval, *collectTimeout, log)
30 | if err != nil {
31 | log.Error(err)
32 | return
33 | }
34 |
35 | registry := prometheus.NewRegistry()
36 |
37 | log.Info("static labels:", *staticLabels)
38 | registerer := prometheus.WrapRegistererWith(*staticLabels, registry)
39 | registerer.MustRegister(info("pg_agent_info", version))
40 | registerer.MustRegister(c)
41 |
42 | http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
43 | log.Info("listening on:", *listen)
44 | log.Error(http.ListenAndServe(*listen, nil))
45 | }
46 |
47 | func info(name, version string) prometheus.Collector {
48 | g := prometheus.NewGauge(prometheus.GaugeOpts{
49 | Name: name,
50 | ConstLabels: prometheus.Labels{"version": version},
51 | })
52 | g.Set(1)
53 | return g
54 | }
55 |
--------------------------------------------------------------------------------
/obfuscate/runes.go:
--------------------------------------------------------------------------------
1 | package obfuscate
2 |
3 | type runes struct {
4 | data []rune
5 | len int
6 | }
7 |
8 | func newRunes(s string) *runes {
9 | d := []rune(s)
10 | return &runes{data: d, len: len(d)}
11 | }
12 |
13 | func (r *runes) get(i int) rune {
14 | if i >= r.len {
15 | return 0
16 | }
17 | return r.data[i]
18 | }
19 |
--------------------------------------------------------------------------------
/obfuscate/sql.go:
--------------------------------------------------------------------------------
1 | package obfuscate
2 |
3 | import (
4 | "bytes"
5 | "regexp"
6 | "strings"
7 | )
8 |
9 | var (
10 | rePlaceholder = regexp.MustCompile(`\$\d+`)
11 | reNumber = regexp.MustCompile(`[+-]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:e[+-]?\d+)?`)
12 | reWhitespace = regexp.MustCompile(`\s+`)
13 | reTypecast = regexp.MustCompile(`\s*::\s*"?\w+"?(?:\(\s*\d*\s*\))?(?:\[\s*\])?`)
14 | reOperator = regexp.MustCompile(`([!#$%&*+\-/:<=>@^~|]+)`)
15 | rePunctuation = regexp.MustCompile(`([(),;[\]{}])`)
16 | reBoolean = regexp.MustCompile(`(\W)(:?true|false|null)(\W|$)`)
17 | reValues = regexp.MustCompile(`(values?)\s*(?:\(\s*\?\s*\)\s*,?\s*)+`)
18 | )
19 |
20 | func Sql(query string) string {
21 | query = strings.ToLower(query)
22 | query = removeCommentsAndStrings(query)
23 | query = reWhitespace.ReplaceAllString(query, " ")
24 | query = rePlaceholder.ReplaceAllString(query, "?")
25 | query = reTypecast.ReplaceAllString(query, "")
26 | query = reNumber.ReplaceAllString(query, "?")
27 | query = reBoolean.ReplaceAllString(query, "$1?$3")
28 |
29 | query = collapseLists(query)
30 | query = reValues.ReplaceAllString(query, "$1(?)")
31 |
32 | query = reOperator.ReplaceAllString(query, " $1 ")
33 | query = rePunctuation.ReplaceAllString(query, " $1 ")
34 | query = reWhitespace.ReplaceAllString(query, " ")
35 | query = strings.ReplaceAll(query, " ,", ",")
36 | query = strings.TrimLeft(query, " ")
37 | query = strings.TrimRight(query, "; ")
38 | return query
39 | }
40 |
41 | func removeCommentsAndStrings(query string) string {
42 | q := newRunes(query)
43 | var curr, next rune
44 | var res bytes.Buffer
45 | for i := 0; i < q.len; i++ {
46 | curr, next = q.get(i), q.get(i+1)
47 | switch {
48 | case curr == '\'': // string constant
49 | i++
50 | for ; i < q.len; i++ {
51 | if q.get(i) == '\'' {
52 | if q.get(i+1) == '\'' { // escaped quote
53 | i++
54 | continue
55 | }
56 | break
57 | }
58 | }
59 | res.WriteRune('?')
60 | case curr == 'e' && next == '\'': // postgres C-style escaped string
61 | i += 2
62 | for ; i < q.len; i++ {
63 | if q.get(i) == '\'' {
64 | if q.get(i+1) == '\'' || (q.get(i-1) == '\\' && q.get(i-2) != '\\') { // escaped quote
65 | i++
66 | continue
67 | }
68 | break
69 | }
70 | }
71 | res.WriteRune('?')
72 | case curr == '$' && next == '$': // postgres dollar-quoted string
73 | i += 2
74 | for ; i < q.len; i++ {
75 | if q.get(i-1) == '$' && q.get(i) == '$' {
76 | break
77 | }
78 | }
79 | res.WriteRune('?')
80 | case (curr == 'b' || curr == 'x') && next == '\'': // postgres bit string
81 | i += 2
82 | for ; i < q.len; i++ {
83 | if q.get(i) == '\'' {
84 | break
85 | }
86 | }
87 | res.WriteRune('?')
88 | case curr == '-' && next == '-': // single-line comment
89 | i += 2
90 | for ; i < q.len; i++ {
91 | if q.get(i) == '\n' {
92 | res.WriteRune('\n')
93 | break
94 | }
95 | }
96 | case curr == '/' && next == '*': // multi-line comment
97 | i += 2
98 | for ; i < q.len; i++ {
99 | if q.get(i-1) == '*' && q.get(i) == '/' {
100 | break
101 | }
102 | }
103 | default:
104 | res.WriteRune(curr)
105 | }
106 | }
107 | return res.String()
108 | }
109 |
110 | func collapseLists(query string) string {
111 | q := newRunes(query)
112 | var res bytes.Buffer
113 | for i := 0; i < q.len; i++ {
114 | curr := q.get(i)
115 | switch curr {
116 | case '(':
117 | j := i + 1
118 | for level := 1; j < q.len && level > 0; j++ {
119 | switch q.get(j) {
120 | case '(':
121 | level++
122 | continue
123 | case ')':
124 | level--
125 | continue
126 | case '?', ' ', ',':
127 | continue
128 | default:
129 | goto OUT
130 | }
131 | }
132 | res.WriteString("(?)")
133 | i = j - 1
134 | continue
135 | case '[':
136 | j := i + 1
137 | for level := 1; j < q.len && level > 0; j++ {
138 | switch q.get(j) {
139 | case '[':
140 | level++
141 | continue
142 | case ']':
143 | level--
144 | continue
145 | case '?', ' ', ',':
146 | continue
147 | default:
148 | goto OUT
149 | }
150 | }
151 | res.WriteString("[?]")
152 | i = j - 1
153 | continue
154 | }
155 | OUT:
156 | res.WriteRune(curr)
157 | }
158 | return res.String()
159 | }
160 |
--------------------------------------------------------------------------------
/obfuscate/sql_test.go:
--------------------------------------------------------------------------------
1 | package obfuscate
2 |
3 | import (
4 | "github.com/stretchr/testify/assert"
5 | "testing"
6 | )
7 |
8 | func TestRemoveComments(t *testing.T) {
9 | for _, c := range []struct{ in, out string }{
10 | {
11 | in: `select '你好', 柱子 from "桌子"`,
12 | out: `select ?, 柱子 from "桌子"`,
13 | },
14 | {
15 | in: "/*comment*/query",
16 | out: "query",
17 | },
18 | {
19 | in: "/**/ query",
20 | out: " query",
21 | },
22 | {
23 | in: "/**/ query 1 /*comment1*/ /*comment2*/query2",
24 | out: " query 1 query2",
25 | },
26 | {
27 | in: "/* comment */query --comment --foo /",
28 | out: "query ",
29 | },
30 | {
31 | in: "select --comment1 \n from--comment2\n where",
32 | out: "select \n from\n where",
33 | },
34 | {
35 | in: "/* comment */query \n, foo --comment /",
36 | out: "query \n, foo ",
37 | },
38 | {
39 | in: "/* multi-line \n comment */query \n, foo --comment /",
40 | out: "query \n, foo ",
41 | },
42 |
43 | {
44 | in: "/* --comment */select 1",
45 | out: "select 1",
46 | },
47 |
48 | {
49 | in: "/* comment */query \n, foo --comment \n bar --comment /",
50 | out: "query \n, foo \n bar ",
51 | },
52 | {
53 | in: `select * from t where f = 'foo --fake comment' and bar`,
54 | out: `select * from t where f = ? and bar`,
55 | },
56 | {
57 | in: `select * from t where f = 'foo /*fake comment*/' and bar`,
58 | out: `select * from t where f = ? and bar`,
59 | },
60 | {
61 | in: `select * from t where f = 'foo ''/*fake comment*/' and bar`, // escaped quote
62 | out: `select * from t where f = ? and bar`,
63 | },
64 | {
65 | in: `select * from t where f = $$foo /*fake comment*/$$ and bar`, // string constant in postgres
66 | out: `select * from t where f = ? and bar`,
67 | },
68 | {
69 | in: `select * from t where f = 'foo --fake comment`, // truncated query
70 | out: `select * from t where f = ?`,
71 | },
72 | {
73 | in: `select * from t where f = 'foo ''--fake comment''`, // truncated query and escaped quote
74 | out: `select * from t where f = ?`,
75 | },
76 | {
77 | in: `select * from t where f = $$foo --fake comment`, // truncated query
78 | out: `select * from t where f = ?`,
79 | },
80 | {
81 | in: `select e' \' \\'' \\' as`, // postgres C-style escapes
82 | out: "select ? as",
83 | },
84 | {
85 | in: `select b'1000', x'ff' from t where id in (b'100', x'ff')`, // postgres bit strings
86 | out: "select ?, ? from t where id in (?, ?)",
87 | },
88 | } {
89 | assert.Equal(t, c.out, removeCommentsAndStrings(c.in), c.in)
90 | }
91 | }
92 |
93 | func TestReplaceNumbers(t *testing.T) {
94 | for _, c := range []struct{ in, out string }{
95 | {in: "42", out: "?"},
96 | {in: "3.5", out: "?"},
97 | {in: "4.", out: "?"},
98 | {in: ".001", out: "?"},
99 | {in: "5e2", out: "?"},
100 | {in: "+5e-2", out: "?"},
101 |
102 | {in: "42, 3.5, 4., .001 , 5e2", out: "?, ?, ?, ?, ?"},
103 |
104 | {in: "tbl2", out: "tbl?"},
105 | {in: "tbl2s", out: "tbl?s"},
106 | {in: "col12v3", out: "col?v?"},
107 | } {
108 | assert.Equal(t, c.out, Sql(c.in), c.in)
109 | }
110 | }
111 |
112 | func TestCollapseLists(t *testing.T) {
113 | for _, c := range []struct{ in, out string }{
114 | {
115 | in: "foo in (?, ?, ?, ? , ? ) and bar",
116 | out: "foo in (?) and bar",
117 | },
118 | {
119 | in: "foo in(?, ?, ?, ? , ? )",
120 | out: "foo in(?)",
121 | },
122 | {
123 | in: "foo or (bar and id in (?, ?))",
124 | out: "foo or (bar and id in (?))",
125 | },
126 | {
127 | in: "foo in (?, ?,",
128 | out: "foo in (?)",
129 | },
130 | {
131 | in: "select array[?, ? ,?], foo",
132 | out: "select array[?], foo",
133 | },
134 | {
135 | in: "select array[?, ? ",
136 | out: "select array[?]",
137 | },
138 | {
139 | in: "select array[[?, ? ], [? ,?]]",
140 | out: "select array[?]",
141 | },
142 | {
143 | in: "select array [[?, ? ], [? ,",
144 | out: "select array [?]",
145 | },
146 | {
147 | in: "select any(array[[?, ? ], [? ,?]])",
148 | out: "select any(array[?])",
149 | },
150 | {
151 | in: "values(?, ?), (?, ?)",
152 | out: "values(?), (?)",
153 | },
154 | {
155 | in: "values(?, ?), (",
156 | out: "values(?), (?)",
157 | },
158 | {
159 | in: "values((?), (?))",
160 | out: "values(?)",
161 | },
162 | {
163 | in: "values((?), (?)",
164 | out: "values(?)",
165 | },
166 | } {
167 | assert.Equal(t, c.out, collapseLists(c.in), c.in)
168 | }
169 | }
170 |
171 | func TestSql(t *testing.T) {
172 | for _, c := range []struct{ in, out string }{
173 | {
174 | in: "select null, 5.001 ,true::bool, count(truefield) from \"truetable\",truetable2, truetable3 where d=123 and b is null and c=false and d = true",
175 | out: "select ?, ?, ?, count ( truefield ) from \"truetable\", truetable?, truetable? where d = ? and b is ? and c = ? and d = ?",
176 | },
177 | { // pg type casts
178 | in: "select a::int, b::int[], c::varchar(256), d::varchar(256)[], array[ a::int ], e :: \"foo_8\"( 8 )[ ] where id in (c::int)",
179 | out: "select a, b, c, d, array [ a ], e where id in ( c )",
180 | },
181 | {
182 | in: "SELECT col235v1::\"int_8\"[] AS foo --comment\n\tFROM table1\n \tWHERE col123 IN(42, 3.5::int, $1 ) AND s=E'''' AND j->>2 = +5e-2",
183 | out: "select col?v? as foo from table? where col? in ( ? ) and s = ? and j ->> ? = ?",
184 | },
185 | {
186 | in: "SELECT price*currency, price/currency*100 from invoice",
187 | out: "select price * currency, price / currency * ? from invoice",
188 | },
189 | {
190 | in: "SELECT * FROM (ValUes (1, 'one'), (2, 'two'), (3, 'three')) AS t (num,letter)",
191 | out: "select * from ( values ( ? ) ) as t ( num, letter )",
192 | },
193 | {
194 | in: "select ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3]",
195 | out: "select array [ ? ] = array [ ? ]",
196 | },
197 | {
198 | in: `select t.field from schema.table as t`,
199 | out: `select t.field from schema.table as t`,
200 | },
201 | {
202 | in: `select t."field" from "schema"."table" as t`,
203 | out: `select t."field" from "schema"."table" as t`,
204 | },
205 | {
206 | in: "insert into foo(a, b, c) values(2, 4, 5) , (2,4,5)",
207 | out: "insert into foo ( a, b, c ) values ( ? )",
208 | },
209 | {
210 | in: "insert into foo(a, b, c) value(2, 4, 5) , (2,4,5)",
211 | out: "insert into foo ( a, b, c ) value ( ? )",
212 | },
213 | {
214 | in: "select value, 'a', 2 from t",
215 | out: "select value, ?, ? from t",
216 | },
217 | {
218 | in: "INSERT INTO test VALUES (B'10'::bit(3), B'101')",
219 | out: "insert into test values ( ? )",
220 | },
221 | {
222 | in: "insert into t values (1), (2), (3)\n\n\ton duplicate key update query_count=1",
223 | out: "insert into t values ( ? ) on duplicate key update query_count = ?",
224 | },
225 | {
226 | in: "SELECT * FROM articles WHERE id > 10 ORDER BY id asc LIMIT 15,20",
227 | out: "select * from articles where id > ? order by id asc limit ?, ?",
228 | },
229 | {
230 | in: "SELECT * FROM articles WHERE (articles.created_at BETWEEN '2020-10-31' AND '2021-11-01')",
231 | out: "select * from articles where ( articles.created_at between ? and ? )",
232 | },
233 | {
234 | in: "SELECT * FROM articles WHERE (articles.created_at BETWEEN $1 AND $2)",
235 | out: "select * from articles where ( articles.created_at between ? and ? )",
236 | },
237 | {
238 | in: `SAVEPOINT "s139956586256192_x1"`,
239 | out: `savepoint "s?_x?"`,
240 | },
241 | {
242 | in: "select lower('DdD'), cast(f as text)",
243 | out: "select lower ( ? ), cast ( f as text )",
244 | },
245 | {
246 | in: " select 1 ; ",
247 | out: "select ?",
248 | },
249 | } {
250 | assert.Equal(t, c.out, Sql(c.in), c.in)
251 | }
252 | }
253 |
254 | func BenchmarkSql(b *testing.B) {
255 | query := `
256 | /* topics by state */
257 | SELECT
258 | t.state::text as state,
259 | COUNT(t.id) as count
260 | FROM
261 | topic t
262 | join site s on s.id = t.site_id
263 | WHERE true
264 | AND s.name = 'example.com'
265 | AND t.author IS NOT NULL
266 | AND NOT archived -- todo: replace by archived_at
267 | AND id IN ($1, $2, $3, $4, $5, $6, $7, $8, $9)
268 | GROUP by 1
269 | ORDER BY count DESC
270 | `
271 | b.ResetTimer()
272 | for i := 0; i < b.N; i++ {
273 | Sql(query)
274 | }
275 | }
276 |
--------------------------------------------------------------------------------