forked from moby/buildkit
-
Notifications
You must be signed in to change notification settings - Fork 3
/
common.go
80 lines (67 loc) · 1.97 KB
/
common.go
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
package common
import (
"context"
"net/url"
"os"
"path/filepath"
"time"
"github.com/moby/buildkit/client"
"github.com/pkg/errors"
"github.com/urfave/cli"
"go.opentelemetry.io/otel/trace"
)
// ResolveClient resolves a client from CLI args
func ResolveClient(c *cli.Context) (*client.Client, error) {
serverName := c.GlobalString("tlsservername")
if serverName == "" {
// guess servername as hostname of target address
uri, err := url.Parse(c.GlobalString("addr"))
if err != nil {
return nil, err
}
serverName = uri.Hostname()
}
var caCert string
var cert string
var key string
tlsDir := c.GlobalString("tlsdir")
if tlsDir != "" {
// Look for ca.pem and, if it exists, set caCert to that
// Look for cert.pem and, if it exists, set key to that
// Look for key.pem and, if it exists, set tlsDir to that
for _, v := range [3]string{"ca.pem", "cert.pem", "key.pem"} {
file := filepath.Join(tlsDir, v)
if _, err := os.Stat(file); err == nil {
switch v {
case "ca.pem":
caCert = file
case "cert.pem":
cert = file
case "key.pem":
key = file
}
} else {
return nil, err
}
}
if c.GlobalString("tlscacert") != "" || c.GlobalString("tlscert") != "" || c.GlobalString("tlskey") != "" {
return nil, errors.New("cannot specify tlsdir and tlscacert/tlscert/tlskey at the same time")
}
} else {
caCert = c.GlobalString("tlscacert")
cert = c.GlobalString("tlscert")
key = c.GlobalString("tlskey")
}
opts := []client.ClientOpt{client.WithFailFast()}
ctx := CommandContext(c)
if span := trace.SpanFromContext(ctx); span.SpanContext().IsValid() {
opts = append(opts, client.WithTracer(span.Tracer()))
}
if caCert != "" || cert != "" || key != "" {
opts = append(opts, client.WithCredentials(serverName, caCert, cert, key))
}
timeout := time.Duration(c.GlobalInt("timeout"))
ctx, cancel := context.WithTimeout(ctx, timeout*time.Second)
defer cancel()
return client.New(ctx, c.GlobalString("addr"), opts...)
}