File: nrpgx.go

package info (click to toggle)
golang-github-newrelic-go-agent 3.15.2-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,356 kB
  • sloc: sh: 65; makefile: 6
file content (344 lines) | stat: -rw-r--r-- 10,528 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2021 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

// +build go1.10

// Package nrpgx instruments https://github.com/jackc/pgx/v4.
//
// Use this package to instrument your PostgreSQL calls using the pgx
// library.
//
// USING WITH PGX AS A DATABASE/SQL DRIVER
//
// The pgx library may be used as a database/sql driver rather than making
// direct calls into pgx itself. In this scenario, just use the nrpgx integration
// in place of the pgx driver. In other words,
// if your code without New Relic's agent looks like this:
//
//	import (
//      "database/sql"
//		_ "github.com/jackc/pgx/v4/stdlib"
//	)
//
//	func main() {
//		db, err := sql.Open("pgx", "user=pqgotest dbname=pqgotest sslmode=verify-full")
//	}
//
// Then change the side-effect import to this package, and open "nrpgx" instead:
//
//	import (
//      "database/sql"
//
//		_ "github.com/newrelic/go-agent/v3/integrations/nrpgx"
//	)
//
//	func main() {
//		db, err := sql.Open("nrpgx", "user=pqgotest dbname=pqgotest sslmode=verify-full")
//	}
//
// Next, provide a context containing a newrelic.Transaction to all exec and query
// methods on sql.DB, sql.Conn, and sql.Tx.  This requires using the
// context methods ExecContext, QueryContext, and QueryRowContext in place of
// Exec, Query, and QueryRow respectively.  For example, instead of the
// following:
//
//	row := db.QueryRow("SELECT count(*) FROM pg_catalog.pg_tables")
//
// Do this:
//
//	ctx := newrelic.NewContext(context.Background(), txn)
//	row := db.QueryRowContext(ctx, "SELECT count(*) FROM pg_catalog.pg_tables")
//
// A working example is shown here:
// https://github.com/newrelic/go-agent/tree/master/v3/integrations/nrpgx/example/sql_compat/main.go
//
//
// USING WITH DIRECT PGX CALLS WITHOUT DATABASE/SQL
//
// This mode of operation is not supported by the nrpgx integration at this time.
//
package nrpgx

import (
	"database/sql"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"

	"github.com/jackc/pgx"
	"github.com/jackc/pgx/v4/stdlib"
	"github.com/newrelic/go-agent/v3/internal"
	"github.com/newrelic/go-agent/v3/newrelic"
	"github.com/newrelic/go-agent/v3/newrelic/sqlparse"
)

var (
	baseBuilder = newrelic.SQLDriverSegmentBuilder{
		BaseSegment: newrelic.DatastoreSegment{
			Product: newrelic.DatastorePostgres,
		},
		ParseQuery: sqlparse.ParseQuery,
		ParseDSN:   parseDSN(os.Getenv),
	}
)

func init() {
	sql.Register("nrpgx", newrelic.InstrumentSQLDriver(&stdlib.Driver{}, baseBuilder))
	internal.TrackUsage("integration", "driver", "nrpgx")
}

/*
 * The general format for these is:
 *   postgres[ql]://[user[:pass]@][host][:port][,...][/db][?params]
 *
 *   pgx recognizes:
 *     sql.Open("pgx", "hostname=x host_port=x username=x password=x databasename=x sslmode=x")
 *   or
 *     sql.Open("pgx", URI)
 *   or
 *     driverConfig := stdlib.DriverConfig{...}
 *     sql.RegisterDriverConfig(&driverConfig)
 *     sql.Open("pgx", driverConfig.ConnectionString(URI))
 *
 * params may include
 *   host=name (see below)
 *   hostaddr=IPv4/IPv6 address
 *   port=number
 *   dbname=name
 *   user=name
 *   password=string
 *   passfile=path
 *   connect_timeout=sec
 *   client_encoding=scheme|"auto"
 *   options=command-line opts
 *   application_name=name
 *   fallback_appliction_name=name
 *   keepalives=0|1
 *   keepalives_idle=sec
 *   keepalives_interval=sec
 *   keepalives_count=n
 *   tcp_user_timeout=ms
 *   tty=name
 *   replication=mode
 *   gssencmode=mode
 *   sslmode=disable|allow|prefer|require|verify-ca|verify-full
 *   requiressl=bool
 *   sslcompression=bool
 *   sslcert=file
 *   sslkey=file
 *   sslrootcert=file
 *   sslcrl=file
 *   requirepeer=user
 *   krbsrvname=name
 *   gsslib=name
 *   service=name
 *   target_session_attrs=value
 *   ssl=true  is equivalent to sslmode=require
 *
 * may include %-encoded values
 * host may be a DNS name, IP4 address, or IP6 address in square brackets, or may be
 * a pathname for a UNIX domain socket (but since slash is reserved in URI syntax,
 * this may need to be put in the params list)
 *  (Note that the IP6 address contains colons)
 * multiple hosts may be given as a comma-separated list
 *
 * pgx provides
 *  ParseConnectionString(string) -> ConnConfig, error	(URI or DSN)
 *  ParseDSN(string) -> ConnConfig, error				(DSN only)
 *  ParseURI(string) -> ConnConfig, error				(URI only)
 *
 * which we'll use to parse out all of the above and avoid second-guessing
 * anything or duplicating effort.
 */

//
// parsePort takes a string representation which purports to be a TCP port number
// or a comma-separated list of port numbers, and returns the port number as a
// uint16 value and as a string. If a list was given, the returned values are for
// the first item in the list, discarding the others.
//
// If the string can't be understood as an unsigned integer value, then 0 is
// returned as the uint16 value.
//
func parsePort(p string) (uint16, string) {
	if p == "" {
		return 0, ""
	}

	np, err := strconv.ParseUint(p, 10, 16)
	if err != nil {
		// Maybe multiple values were specified?
		// (The code could be more concise if we did more processing up front,
		// but this avoids needless work if a single number was given, so should
		// be more runtime efficient.)
		if comma := strings.IndexRune(p, ','); comma >= 0 {
			p = p[0:comma]
			np, err = strconv.ParseUint(p, 10, 16)
			if err != nil {
				// even the first one isn't a real number
				np = 0
			}
		} else {
			// Nope, it's just something we can't grok
			np = 0
		}
	}
	return uint16(np), p
}

//
// ip6HostPort is a regular expression to parse IPv6 hostnames (which must be in
// square brackets in the connection strings we're working with). The hostname may
// optionally be followed by a colon and a TCP port number.
//
// Any text after the hostname (and port, if any), is ignored.
//
var ip6HostPort = regexp.MustCompile(`^\[([0-9a-fA-F:]*)\](:([0-9]+))?`)

//
// fullIp6ConnectPattern and fullConnectPattern are regular expressions which
// match a postgres URI connection string using IPv6 addresses, or other forms,
// respectively.
//
var fullIp6ConnectPattern = regexp.MustCompile(
	//                     user     password    host                 port                dbname      params
	//                     __1__    __2__     _________3________     __4__               __5__       __6_
	`^postgres(?:ql)?://(?:(.*?)(?::(.*?))?@)?(\[[0-9a-fA-F:]+\])(?::(.*?))?(?:,.*?)*(?:/(.*?))?(?:\?(.*))?$`)
var fullConnectPattern = regexp.MustCompile(
	//                     user     password  host                 port                dbname      params
	//                     __1__    __2__     ________3________    __4__               __5__       __6_
	`^postgres(?:ql)?://(?:(.*?)(?::(.*?))?@)?([a-zA-Z0-9_.-]+)(?::(.*?))?(?:,.*?)*(?:/(.*?))?(?:\?(.*))?$`)

//
// fullParamPattern is a regular expression to match the key=value pairs of a
// parameterized DSN string.
//
var fullParamPattern = regexp.MustCompile(
	`(\w+)\s*=\s*('[^=]*'|[^'\s]+)`)

//
// parseDSN returns a function which will set datastore segment attributes to show
// the database, host, and port as extracted from a supplied DSN string.
//
func parseDSN(getenv func(string) string) func(*newrelic.DatastoreSegment, string) {
	return func(s *newrelic.DatastoreSegment, dsn string) {

		cc, err := pgx.ParseConnectionString(dsn)
		if err != nil {
			// the connection string is invalid

			// Sometimes we've found that pgx.ParseConnectionString doesn't recognize
			// all patterns so if that call failed, we'll do a little pattern matching
			// of our own and see if we can figure it out.
			cc = pgx.ConnConfig{}
			conn := fullIp6ConnectPattern.FindStringSubmatch(dsn)
			if conn == nil {
				conn = fullConnectPattern.FindStringSubmatch(dsn)
				if conn == nil {
					// maybe it's a parameterized string that ParseConnectionString didn't like.
					for _, par := range fullParamPattern.FindAllStringSubmatch(dsn, -1) {
						if len(par) != 3 {
							continue
						}
						v := strings.Trim(par[2], "'")
						switch par[1] {
						case "dbname":
							cc.Database = v
						case "host":
							// don't overwrite if hostaddr already put a value here
							if cc.Host == "" {
								cc.Host = v
							}
						case "hostaddr":
							cc.Host = v
						case "port":
							cc.Port, _ = parsePort(v)
						}
					}
					if cc.Database == "" && cc.Host == "" && cc.Port == 0 {
						// Ok, we give up.
						return
					}
				}
			}
			if conn != nil {
				cc.Host = conn[3]
				cc.Database = conn[5]
				cc.Port, _ = parsePort(conn[4])
			}
		}

		// default to the environment variables in case
		// we can't find them in the connection string
		var ppoid string

		if p, ok := cc.RuntimeParams["port"]; ok {
			cc.Port, ppoid = parsePort(p)
		}

		if cc.Port == 0 {
			cc.Port, ppoid = parsePort(getenv("PGPORT"))
		} else {
			ppoid = strconv.Itoa(int(cc.Port))
		}

		// explicit hostaddr=xxx overrides the hostname
		if ha, ok := cc.RuntimeParams["hostaddr"]; ok {
			cc.Host = ha
		}

		if cc.Host == "" {
			cc.Host = getenv("PGHOST")
		}

		// The host string could have multiple comma-separated hosts,
		// which could have an attached ":port" at the end, but also
		// note that we can't get too anxious to jump on any colons in
		// the hostname string because the hostname could also be an IPv6
		// address with optional port, as in
		// "[2001:db8:3333:4444:5555:6666:7777:8888]:5432", so we need
		// to look for that explicitly.
		cc.Host = strings.SplitN(cc.Host, ",", 2)[0]

		ip6parts := ip6HostPort.FindStringSubmatch(cc.Host)
		if ip6parts != nil {
			cc.Host = ip6parts[1]
			if ip6parts[2] != "" {
				cc.Port, ppoid = parsePort(ip6parts[2])
			}
		} else {
			if colon := strings.IndexRune(cc.Host, ':'); colon >= 0 {
				// This host had an explicit port number attached to it.
				// Use that in preference to what's in cc.Port.
				if colon+1 < len(cc.Host) {
					cc.Port, ppoid = parsePort(cc.Host[colon+1:])
				}
				cc.Host = cc.Host[0:colon]
			}
		}

		if cc.Database == "" {
			cc.Database = getenv("PGDATABASE")
		}

		// fill in the Postgres defaults explicitly
		if cc.Host == "" {
			cc.Host = "localhost"
		}
		if cc.Port == 0 {
			cc.Port, ppoid = parsePort("5432")
		}

		// Unix sockets are handled a little differently
		if strings.HasPrefix(cc.Host, "/") {
			ppoid = path.Join(cc.Host, ".s.PGSQL."+ppoid)
			cc.Host = "localhost"
		}

		s.Host = cc.Host
		s.PortPathOrID = ppoid
		s.DatabaseName = cc.Database
	}
}