Repository navigation
Expand file tree
/
Copy pathdrivers.go
More file actions
712 lines (629 loc) · 19.5 KB
/
Copy pathdrivers.go
File metadata and controls
712 lines (629 loc) · 19.5 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
// Copyright 2026 Columnar Technologies Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbc
import (
"context"
"crypto/sha256"
_ "embed"
"errors"
"fmt"
"io"
"iter"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"runtime/debug"
"slices"
"sort"
"strconv"
"strings"
"sync"
"github.com/Masterminds/semver/v3"
"github.com/columnar-tech/dbc/auth"
"github.com/columnar-tech/dbc/internal"
"github.com/go-faster/yaml"
"github.com/google/uuid"
)
var (
ErrUnauthorized = errors.New("not authorized")
ErrUnauthorizedColumnar = errors.New("not authorized to access")
)
type Registry struct {
Name string
Drivers []Driver
BaseURL *url.URL
}
func mustParseURL(u string) *url.URL {
uri, err := url.Parse(u)
if err != nil {
panic(fmt.Sprintf("failed to parse URL %s: %v", u, err))
}
return uri
}
var (
Version = "unknown"
mid string
uid uuid.UUID
// DefaultClient is the HTTP client used for all requests.
//
// Deprecated: Use NewClient with WithHTTPClient instead.
// DefaultClient must be set during program initialization,
// before any concurrent calls to GetDriverList or makereq.
DefaultClient = http.DefaultClient
setupOnce sync.Once
internalClient *http.Client
)
type uaRoundTripper struct {
http.RoundTripper
userAgent string
}
// custom RoundTripper that sets the User-Agent header on any requests
func (u *uaRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context())
req.Header.Set("User-Agent", u.userAgent)
return u.RoundTripper.RoundTrip(req)
}
func init() {
info, ok := debug.ReadBuildInfo()
if ok && Version == "unknown" {
Version = info.Main.Version
}
}
func ensureSetup() {
setupOnce.Do(func() {
userAgent := fmt.Sprintf("dbc-cli/%s (%s; %s)",
Version, runtime.GOOS, runtime.GOARCH)
if ci := os.Getenv("CI"); ci != "" {
if val, _ := strconv.ParseBool(ci); val {
userAgent += " CI"
}
}
internalClient = &http.Client{
Transport: &uaRoundTripper{
RoundTripper: http.DefaultTransport,
userAgent: userAgent,
},
CheckRedirect: checkRedirect,
}
mid, _ = telemetryMachineID()
userdir, err := internal.GetUserConfigPath()
if err != nil {
uid = uuid.New()
return
}
fp := filepath.Join(userdir, "uid.uuid")
data, err := os.ReadFile(fp)
if err == nil {
if err = uid.UnmarshalBinary(data); err == nil {
return
}
}
uid = uuid.New()
if err = os.MkdirAll(filepath.Dir(fp), 0o700); err == nil {
if data, err = uid.MarshalBinary(); err == nil {
os.WriteFile(fp, data, 0o600)
}
}
})
}
func getHTTPClient() *http.Client {
ensureSetup()
if DefaultClient != http.DefaultClient {
return DefaultClient
}
return internalClient
}
func makereq(u string) (resp *http.Response, err error) {
uri, err := url.Parse(u)
if err != nil {
return nil, fmt.Errorf("failed to parse URL %s: %w", u, err)
}
// Replaced requests are anonymous: no credentials, no telemetry ids.
router := defaultRouter.Load()
eff, replaced, err := router.route(uri)
if err != nil {
return nil, err
}
if replaced {
return anonymousGet(context.Background(), getHTTPClient(), router, eff, uri.Path)
}
ensureSetup()
// A redirect must not reach an origin that a rule replaces either.
hc := router.guardRedirects(getHTTPClient(), false)
cred, err := auth.GetCredentials(uri)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to read credentials: %w", err)
}
q := uri.Query()
q.Add("mid", mid)
q.Add("uid", uid.String())
uri.RawQuery = q.Encode()
buildLegacyReq := func(token string) (*http.Request, error) {
urlCopy := *uri
r, err := http.NewRequestWithContext(context.Background(), http.MethodGet, urlCopy.String(), nil)
if err != nil {
return nil, err
}
if uri.Path == "/index.yaml" {
r.Header.Set("Accept", "application/yaml")
}
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
}
return r, nil
}
token := ""
if cred != nil {
if auth.IsColumnarPrivateRegistry(uri) {
// if we're accessing the private registry then attempt to
// fetch the trial license. This will be a no-op if they have
// a license saved already, and if they haven't started their
// trial or it is expired, then this will silently fail.
_ = auth.FetchColumnarLicense(context.Background(), cred)
}
token = cred.GetAuthToken(context.Background())
}
req, err := buildLegacyReq(token)
if err != nil {
return nil, fmt.Errorf("failed to build request: %w", err)
}
resp, err = hc.Do(req)
if err != nil {
return
}
if resp.StatusCode == http.StatusUnauthorized && cred != nil {
resp.Body.Close()
if err := cred.RefreshAndPersist(context.Background()); err != nil {
return nil, fmt.Errorf("failed to refresh auth token: %w", err)
}
retryReq, retryErr := buildLegacyReq(cred.GetAuthToken(context.Background()))
if retryErr != nil {
return nil, fmt.Errorf("failed to build retry request: %w", retryErr)
}
resp, err = hc.Do(retryReq)
if err != nil {
return
}
}
switch resp.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden:
err = ErrUnauthorized
if auth.IsColumnarPrivateRegistry(uri) && cred != nil {
err = ErrUnauthorizedColumnar
}
resp.Body.Close()
return nil, fmt.Errorf("%s%s: %w", uri.Host, uri.Path, err)
}
return resp, err
}
//go:embed columnar.pubkey
var armoredPubKey string
type ProgressFunc func(written, total int64)
type progressWriter struct {
w io.Writer
total int64
written int64
fn ProgressFunc
}
func (pw *progressWriter) Write(p []byte) (n int, err error) {
n, err = pw.w.Write(p)
pw.written += int64(n)
if pw.fn != nil {
pw.fn(pw.written, pw.total)
}
return
}
type PkgInfo struct {
Driver Driver
Version *semver.Version
PlatformTuple string
Path *url.URL
// ArchiveSHA256 is the lowercase hex SHA-256 (64 characters, without the
// "sha256:" prefix) of the package archive as published by the registry.
// It is empty when the registry did not publish a hash for this package.
ArchiveSHA256 string
}
// Deprecated: Use Client.Download instead.
func (p PkgInfo) DownloadPackage(prog ProgressFunc) (*os.File, error) {
if p.Path == nil {
return nil, fmt.Errorf("cannot download package for %s: no url set", p.Driver.Title)
}
location := p.Path.String()
rsp, err := makereq(location)
if err != nil {
return nil, fmt.Errorf("failed to download driver: %w", err)
}
if rsp.StatusCode != http.StatusOK {
rsp.Body.Close()
return nil, fmt.Errorf("failed to download driver %s: %s", location, rsp.Status)
}
defer rsp.Body.Close()
// Name the file after the escaped URL path only: a query (for example a
// registry token) must not end up in the file name, and decoding could
// turn %5C into a Windows path separator.
fname := path.Base(p.Path.EscapedPath())
tmpdir, err := os.MkdirTemp(os.TempDir(), "adbc-drivers-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
output, err := os.Create(path.Join(tmpdir, fname))
if err != nil {
os.RemoveAll(tmpdir)
return nil, fmt.Errorf("failed to create temp file to download to: %w", err)
}
pw := &progressWriter{
w: output,
total: rsp.ContentLength,
fn: prog,
}
_, err = io.Copy(pw, rsp.Body)
if err != nil {
output.Close()
output = nil
os.RemoveAll(tmpdir)
}
return output, err
}
const registryHashPrefix = "sha256:"
// registryHash is the optional "hash" of a registry package entry. Decoding
// never fails: a malformed value is only recorded, so that just the affected
// package is rejected when it is resolved instead of the whole index.
type registryHash struct {
digest string
present bool
valid bool
}
func (h *registryHash) UnmarshalYAML(value *yaml.Node) error {
h.present = true
h.valid = false
if value.Kind != yaml.ScalarNode || value.Tag != "!!str" {
return nil
}
hexDigest, ok := strings.CutPrefix(value.Value, registryHashPrefix)
if !ok || len(hexDigest) != sha256.Size*2 {
return nil
}
for _, c := range hexDigest {
if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
return nil
}
}
h.digest = hexDigest
h.valid = true
return nil
}
type pkgEntry struct {
PlatformTuple string `yaml:"platform"`
URL string `yaml:"url"`
Hash registryHash `yaml:"hash"`
}
type pkginfo struct {
Version *semver.Version `yaml:"version"`
Packages []pkgEntry `yaml:"packages"`
}
func (p pkginfo) GetPackage(d Driver, platformTuple string) (PkgInfo, error) {
if len(p.Packages) == 0 {
return PkgInfo{}, fmt.Errorf("no packages available for version %s", p.Version)
}
if d.Registry == nil {
return PkgInfo{}, fmt.Errorf("cannot resolve package URL for %s: driver has no registry", d.Title)
}
base := d.Registry.BaseURL
for _, pkg := range p.Packages {
if pkg.PlatformTuple == platformTuple {
if pkg.Hash.present && !pkg.Hash.valid {
return PkgInfo{}, fmt.Errorf("invalid archive hash in registry for driver %s version %s platform %s: expected %s followed by 64 lowercase hex characters",
d.Path, p.Version, platformTuple, registryHashPrefix)
}
var uri *url.URL
if pkg.URL != "" {
var err error
uri, err = url.Parse(pkg.URL)
if err != nil {
return PkgInfo{}, fmt.Errorf("invalid package URL %q: %w", pkg.URL, err)
}
if !uri.IsAbs() {
uri = base.JoinPath(pkg.URL)
}
} else {
uri = base.JoinPath(d.Path, p.Version.String(),
d.Path+"_"+platformTuple+"-"+p.Version.String()+".tar.gz")
}
return PkgInfo{
Driver: d,
Version: p.Version,
PlatformTuple: platformTuple,
Path: uri,
ArchiveSHA256: pkg.Hash.digest,
}, nil
}
}
return PkgInfo{}, fmt.Errorf("no package found for platform '%s'", platformTuple)
}
func filter[T any](items iter.Seq[T], predicate func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for item := range items {
if predicate(item) && !yield(item) {
return
}
}
}
}
// Driver is a single driver in a registry and its available versions.
type Driver struct {
Registry *Registry `yaml:"-"`
Title string `yaml:"name"`
Desc string `yaml:"description"`
License string `yaml:"license"`
Path string `yaml:"path"`
URLs []string `yaml:"urls"`
DocsURL string `yaml:"docs_url"`
PkgInfo []pkginfo `yaml:"pkginfo"`
}
func (d Driver) HasNonPrerelease() bool {
return slices.ContainsFunc(d.PkgInfo, func(p pkginfo) bool {
return p.Version.Prerelease() == ""
})
}
func (d Driver) validatePackageVersions() error {
for _, pkg := range d.PkgInfo {
// TODO: we may want to do other validation
if pkg.Version == nil {
return fmt.Errorf("invalid package metadata for driver %s: missing version", d.Path)
}
}
return nil
}
// GetWithConstraint returns the newest compatible package satisfying c.
func (d Driver) GetWithConstraint(c *semver.Constraints, platformTuple string) (PkgInfo, error) {
return d.latestPackage(c, platformTuple, false)
}
// GetLatestPackage returns the newest compatible package for the given platform.
func (d Driver) GetLatestPackage(platform string, allowPrerelease bool) (PkgInfo, error) {
return d.latestPackage(nil, platform, allowPrerelease)
}
// GetLatestVersionAnyPlatform returns the newest eligible version regardless of platform.
// When constraint is supplied, it determines prerelease eligibility, regardless of allowPrerelease.
func (d Driver) GetLatestVersionAnyPlatform(constraint *semver.Constraints, allowPrerelease bool) (*semver.Version, error) {
if err := d.validatePackageVersions(); err != nil {
return nil, err
}
var latest *semver.Version
for pkg := range d.eligiblePackages(constraint, allowPrerelease) {
if latest == nil || pkg.Version.GreaterThan(latest) {
latest = pkg.Version
}
}
if latest == nil {
return nil, d.selectionMiss(constraint)
}
return latest, nil
}
func (d Driver) eligiblePackages(constraint *semver.Constraints, allowPrerelease bool) iter.Seq[pkginfo] {
return filter(slices.Values(d.PkgInfo), func(pkg pkginfo) bool {
if constraint != nil {
return constraint.Check(pkg.Version)
}
return allowPrerelease || pkg.Version.Prerelease() == ""
})
}
func (d Driver) selectionMiss(constraint *semver.Constraints) error {
switch {
case constraint != nil && len(d.PkgInfo) == 0:
return packageMiss{fmt.Errorf("no package info available for driver %s", d.Path)}
case constraint != nil:
return packageMiss{fmt.Errorf("no package found for driver %s that satisfies constraints %s", d.Path, constraint)}
case len(d.PkgInfo) > 0:
// TODO: it may also be possible there's no packages for this platform?
return packageMiss{fmt.Errorf("driver `%s` not found (but prerelease versions filtered out); try: dbc install --pre %s", d.Path, d.Path)}
default:
return packageMiss{fmt.Errorf("driver `%s` not found", d.Path)}
}
}
func (d Driver) latestPackage(constraint *semver.Constraints, platform string, allowPrerelease bool) (PkgInfo, error) {
if err := d.validatePackageVersions(); err != nil {
return PkgInfo{}, err
}
var latest pkginfo
var eligible bool
for pkg := range d.eligiblePackages(constraint, allowPrerelease) {
eligible = true
if latest.Version != nil && !pkg.Version.GreaterThan(latest.Version) {
continue
}
if slices.ContainsFunc(pkg.Packages, func(entry pkgEntry) bool {
return entry.PlatformTuple == platform
}) {
latest = pkg
}
}
if !eligible {
return PkgInfo{}, d.selectionMiss(constraint)
}
if latest.Version == nil {
return PkgInfo{}, fmt.Errorf("no package found for platform '%s'", platform)
}
return latest.GetPackage(d, platform)
}
func (d Driver) Versions(platformTuple string) semver.Collection {
versions := make(semver.Collection, 0, len(d.PkgInfo))
for _, pkg := range d.PkgInfo {
if pkg.Version == nil {
continue
}
for _, p := range pkg.Packages {
if p.PlatformTuple == platformTuple {
versions = append(versions, pkg.Version)
}
}
}
sort.Sort(versions)
return versions
}
func (d Driver) GetPackage(version *semver.Version, platformTuple string, allowPrerelease bool) (PkgInfo, error) {
if err := d.validatePackageVersions(); err != nil {
return PkgInfo{}, err
}
pkglist := d.PkgInfo
// Filter prereleases when no specific stable version is requested.
// When version is a specific stable release (Prerelease() == ""),
// filtering is unnecessary — the exact-match search below will
// only match the requested stable version.
if !allowPrerelease && (version == nil || version.Prerelease() != "") {
hadPackages := len(d.PkgInfo) > 0
pkglist = slices.Collect(filter(slices.Values(d.PkgInfo), func(p pkginfo) bool {
return p.Version.Prerelease() == ""
}))
if len(pkglist) == 0 {
if hadPackages {
return PkgInfo{}, packageMiss{fmt.Errorf("driver `%s` not found (but prerelease versions filtered out); try: dbc install --pre %s", d.Path, d.Path)}
}
return PkgInfo{}, packageMiss{fmt.Errorf("driver `%s` not found", d.Path)}
}
}
var pkg pkginfo
if version == nil {
if len(pkglist) == 0 {
return PkgInfo{}, packageMiss{fmt.Errorf("driver `%s` not found", d.Path)}
}
pkg = slices.MaxFunc(pkglist, func(a, b pkginfo) int {
return a.Version.Compare(b.Version)
})
version = pkg.Version
} else {
idx := slices.IndexFunc(pkglist, func(p pkginfo) bool {
return p.Version.Equal(version)
})
if idx == -1 {
if !allowPrerelease && version.Prerelease() != "" {
return PkgInfo{}, packageMiss{fmt.Errorf("version %s is a prerelease; use --pre to allow it", version)}
}
return PkgInfo{}, packageMiss{fmt.Errorf("version %s not found", version)}
}
pkg = pkglist[idx]
}
return pkg.GetPackage(d, platformTuple)
}
func (d Driver) MaxVersion() (VersionInfo, bool) {
if len(d.PkgInfo) == 0 {
return VersionInfo{}, false
}
p := slices.MaxFunc(d.PkgInfo, func(a, b pkginfo) int {
return a.Version.Compare(b.Version)
})
pkgs := make([]PackageInfo, 0, len(p.Packages))
for _, pkg := range p.Packages {
pkgs = append(pkgs, PackageInfo{
Platform: pkg.PlatformTuple,
URL: pkg.URL,
})
}
return VersionInfo{Version: p.Version, Packages: pkgs}, true
}
// PackageInfo holds the platform and raw URL string for a single package entry.
// The URL may be relative (joined against the registry base URL) or absolute.
type PackageInfo struct {
Platform string
URL string
}
// VersionInfo holds the version and its associated packages for a driver.
type VersionInfo struct {
Version *semver.Version
Packages []PackageInfo
}
// AllVersions returns all version/package entries for the driver as exported
// VersionInfo values. This allows callers outside the dbc package to iterate
// over every version and platform without needing access to the unexported
// pkginfo type.
func (d Driver) AllVersions() []VersionInfo {
result := make([]VersionInfo, 0, len(d.PkgInfo))
for _, pi := range d.PkgInfo {
pkgs := make([]PackageInfo, 0, len(pi.Packages))
for _, p := range pi.Packages {
pkgs = append(pkgs, PackageInfo{
Platform: p.PlatformTuple,
URL: p.URL,
})
}
result = append(result, VersionInfo{
Version: pi.Version,
Packages: pkgs,
})
}
return result
}
// GetDriverList returns a list of all available drivers from all configured registries.
//
// Deprecated: Use NewClient and Client.Search instead.
func GetDriverList() ([]Driver, error) {
ensureSetup()
var opts []Option
if val := os.Getenv("DBC_BASE_URL"); val != "" {
opts = append(opts, WithBaseURL(val))
}
c, err := NewClient(append(opts, WithHTTPClient(getHTTPClient()))...)
if err != nil {
return nil, err
}
return c.Search(context.Background(), "")
}
// Deprecated: Signature verification is now handled internally by Client.Install.
// SignedByColumnar returns nil if the library was signed by
// the columnar public key (embedded in the CLI) or an error
// otherwise.
func SignedByColumnar(lib, sig io.Reader) error {
key, err := ColumnarSigningKey()
if err != nil {
return err
}
return key.Verify(lib, sig)
}
// ErrPackageMiss indicates that a registry entry has no eligible version.
var ErrPackageMiss = errors.New("no eligible package version")
// packageMiss marks a selection miss that permits registry fallback.
type packageMiss struct{ error }
func (e packageMiss) Is(target error) bool { return target == ErrPackageMiss }
// ResolvePackage tries matching driver entries in order, advancing only on
// ErrPackageMiss. The returned package identifies the selected driver on
// success or a terminal error. If all matching entries miss, it identifies
// the first matching driver and returns that entry's error. If no entry
// matches, it returns a zero package and a driver-not-found error.
func ResolvePackage(drivers []Driver, name string, selectPackage func(*Driver) (PkgInfo, error)) (PkgInfo, error) {
var first PkgInfo
var firstErr error
for _, d := range drivers {
if d.Path != name {
continue
}
pkg, err := selectPackage(&d)
if err == nil {
pkg.Driver = d
return pkg, nil
}
if !errors.Is(err, ErrPackageMiss) {
return PkgInfo{Driver: d}, err
}
if firstErr == nil {
first = PkgInfo{Driver: d}
firstErr = err
}
}
if firstErr != nil {
return first, firstErr
}
return PkgInfo{}, fmt.Errorf("driver `%s` not found in driver registry index; try: `dbc search` to list available drivers", name)
}