Skip to content

Commit 7336a1a

Browse files
committed
TUN-8914: Create a flags module to group all cloudflared cli flags
## Summary This commit refactors some of the flags of cloudflared to their own module, so that they can be used across the code without requiring to literal strings which are much more error prone. Closes TUN-8914
1 parent df5dafa commit 7336a1a

File tree

17 files changed

+350
-235
lines changed

17 files changed

+350
-235
lines changed

cmd/cloudflared/access/cmd.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919

2020
"github.com/cloudflare/cloudflared/carrier"
2121
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
22+
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
2223
"github.com/cloudflare/cloudflared/logger"
2324
"github.com/cloudflare/cloudflared/sshgen"
2425
"github.com/cloudflare/cloudflared/token"
@@ -172,15 +173,15 @@ func Commands() []*cli.Command {
172173
EnvVars: []string{"TUNNEL_SERVICE_TOKEN_SECRET"},
173174
},
174175
&cli.StringFlag{
175-
Name: logger.LogFileFlag,
176+
Name: cfdflags.LogFile,
176177
Usage: "Save application log to this file for reporting issues.",
177178
},
178179
&cli.StringFlag{
179-
Name: logger.LogSSHDirectoryFlag,
180+
Name: cfdflags.LogDirectory,
180181
Usage: "Save application log to this directory for reporting issues.",
181182
},
182183
&cli.StringFlag{
183-
Name: logger.LogSSHLevelFlag,
184+
Name: cfdflags.LogLevelSSH,
184185
Aliases: []string{"loglevel"}, //added to match the tunnel side
185186
Usage: "Application logging level {debug, info, warn, error, fatal}. ",
186187
},
@@ -342,15 +343,15 @@ func run(cmd string, args ...string) error {
342343
return err
343344
}
344345
go func() {
345-
io.Copy(os.Stderr, stderr)
346+
_, _ = io.Copy(os.Stderr, stderr)
346347
}()
347348

348349
stdout, err := c.StdoutPipe()
349350
if err != nil {
350351
return err
351352
}
352353
go func() {
353-
io.Copy(os.Stdout, stdout)
354+
_, _ = io.Copy(os.Stdout, stdout)
354355
}()
355356
return c.Run()
356357
}
@@ -531,7 +532,7 @@ func isFileThere(candidate string) bool {
531532
}
532533

533534
// verifyTokenAtEdge checks for a token on disk, or generates a new one.
534-
// Then makes a request to to the origin with the token to ensure it is valid.
535+
// Then makes a request to the origin with the token to ensure it is valid.
535536
// Returns nil if token is valid.
536537
func verifyTokenAtEdge(appUrl *url.URL, appInfo *token.AppInfo, c *cli.Context, log *zerolog.Logger) error {
537538
headers := parseRequestHeaders(c.StringSlice(sshHeaderFlag))

cmd/cloudflared/cliutil/logger.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import (
44
"github.com/urfave/cli/v2"
55
"github.com/urfave/cli/v2/altsrc"
66

7-
"github.com/cloudflare/cloudflared/logger"
7+
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
88
)
99

1010
var (
@@ -15,34 +15,34 @@ var (
1515
func ConfigureLoggingFlags(shouldHide bool) []cli.Flag {
1616
return []cli.Flag{
1717
altsrc.NewStringFlag(&cli.StringFlag{
18-
Name: logger.LogLevelFlag,
18+
Name: cfdflags.LogLevel,
1919
Value: "info",
2020
Usage: "Application logging level {debug, info, warn, error, fatal}. " + debugLevelWarning,
2121
EnvVars: []string{"TUNNEL_LOGLEVEL"},
2222
Hidden: shouldHide,
2323
}),
2424
altsrc.NewStringFlag(&cli.StringFlag{
25-
Name: logger.LogTransportLevelFlag,
25+
Name: cfdflags.TransportLogLevel,
2626
Aliases: []string{"proto-loglevel"}, // This flag used to be called proto-loglevel
2727
Value: "info",
2828
Usage: "Transport logging level(previously called protocol logging level) {debug, info, warn, error, fatal}",
2929
EnvVars: []string{"TUNNEL_PROTO_LOGLEVEL", "TUNNEL_TRANSPORT_LOGLEVEL"},
3030
Hidden: shouldHide,
3131
}),
3232
altsrc.NewStringFlag(&cli.StringFlag{
33-
Name: logger.LogFileFlag,
33+
Name: cfdflags.LogFile,
3434
Usage: "Save application log to this file for reporting issues.",
3535
EnvVars: []string{"TUNNEL_LOGFILE"},
3636
Hidden: shouldHide,
3737
}),
3838
altsrc.NewStringFlag(&cli.StringFlag{
39-
Name: logger.LogDirectoryFlag,
39+
Name: cfdflags.LogDirectory,
4040
Usage: "Save application log to this directory for reporting issues.",
4141
EnvVars: []string{"TUNNEL_LOGDIRECTORY"},
4242
Hidden: shouldHide,
4343
}),
4444
altsrc.NewStringFlag(&cli.StringFlag{
45-
Name: "trace-output",
45+
Name: cfdflags.TraceOutput,
4646
Usage: "Name of trace output file, generated when cloudflared stops.",
4747
EnvVars: []string{"TUNNEL_TRACE_OUTPUT"},
4848
Hidden: shouldHide,

cmd/cloudflared/flags/flags.go

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
package flags
2+
3+
const (
4+
// HaConnections specifies how many connections to make to the edge
5+
HaConnections = "ha-connections"
6+
7+
// SshPort is the port on localhost the cloudflared ssh server will run on
8+
SshPort = "local-ssh-port"
9+
10+
// SshIdleTimeout defines the duration a SSH session can remain idle before being closed
11+
SshIdleTimeout = "ssh-idle-timeout"
12+
13+
// SshMaxTimeout defines the max duration a SSH session can remain open for
14+
SshMaxTimeout = "ssh-max-timeout"
15+
16+
// SshLogUploaderBucketName is the bucket name to use for the SSH log uploader
17+
SshLogUploaderBucketName = "bucket-name"
18+
19+
// SshLogUploaderRegionName is the AWS region name to use for the SSH log uploader
20+
SshLogUploaderRegionName = "region-name"
21+
22+
// SshLogUploaderSecretID is the Secret id of SSH log uploader
23+
SshLogUploaderSecretID = "secret-id"
24+
25+
// SshLogUploaderAccessKeyID is the Access key id of SSH log uploader
26+
SshLogUploaderAccessKeyID = "access-key-id"
27+
28+
// SshLogUploaderSessionTokenID is the Session token of SSH log uploader
29+
SshLogUploaderSessionTokenID = "session-token"
30+
31+
// SshLogUploaderS3URL is the S3 URL of SSH log uploader (e.g. don't use AWS s3 and use google storage bucket instead)
32+
SshLogUploaderS3URL = "s3-url-host"
33+
34+
// HostKeyPath is the path of the dir to save SSH host keys too
35+
HostKeyPath = "host-key-path"
36+
37+
// RpcTimeout is how long to wait for a Capnp RPC request to the edge
38+
RpcTimeout = "rpc-timeout"
39+
40+
// WriteStreamTimeout sets if we should have a timeout when writing data to a stream towards the destination (edge/origin).
41+
WriteStreamTimeout = "write-stream-timeout"
42+
43+
// QuicDisablePathMTUDiscovery sets if QUIC should not perform PTMU discovery and use a smaller (safe) packet size.
44+
// Packets will then be at most 1252 (IPv4) / 1232 (IPv6) bytes in size.
45+
// Note that this may result in packet drops for UDP proxying, since we expect being able to send at least 1280 bytes of inner packets.
46+
QuicDisablePathMTUDiscovery = "quic-disable-pmtu-discovery"
47+
48+
// QuicConnLevelFlowControlLimit controls the max flow control limit allocated for a QUIC connection. This controls how much data is the
49+
// receiver willing to buffer. Once the limit is reached, the sender will send a DATA_BLOCKED frame to indicate it has more data to write,
50+
// but it's blocked by flow control
51+
QuicConnLevelFlowControlLimit = "quic-connection-level-flow-control-limit"
52+
53+
// QuicStreamLevelFlowControlLimit is similar to quicConnLevelFlowControlLimit but for each QUIC stream. When the sender is blocked,
54+
// it will send a STREAM_DATA_BLOCKED frame
55+
QuicStreamLevelFlowControlLimit = "quic-stream-level-flow-control-limit"
56+
57+
// Ui is to enable launching cloudflared in interactive UI mode
58+
Ui = "ui"
59+
60+
// ConnectorLabel is the command line flag to give a meaningful label to a specific connector
61+
ConnectorLabel = "label"
62+
63+
// MaxActiveFlows is the command line flag to set the maximum number of flows that cloudflared can be processing at the same time
64+
MaxActiveFlows = "max-active-flows"
65+
66+
// Tag is the command line flag to set custom tags used to identify this tunnel via added HTTP request headers to the origin
67+
Tag = "tag"
68+
69+
// Protocol is the command line flag to set the protocol to use to connect to the Cloudflare Edge
70+
Protocol = "protocol"
71+
72+
// PostQuantum is the command line flag to force the connection to Cloudflare Edge to use Post Quantum cryptography
73+
PostQuantum = "post-quantum"
74+
75+
// Features is the command line flag to opt into various features that are still being developed or tested
76+
Features = "features"
77+
78+
// EdgeIpVersion is the command line flag to set the Cloudflare Edge IP address version to connect with
79+
EdgeIpVersion = "edge-ip-version"
80+
81+
// EdgeBindAddress is the command line flag to bind to IP address for outgoing connections to Cloudflare Edge
82+
EdgeBindAddress = "edge-bind-address"
83+
84+
// Force is the command line flag to specify if you wish to force an action
85+
Force = "force"
86+
87+
// Edge is the command line flag to set the address of the Cloudflare tunnel server. Only works in Cloudflare's internal testing environment
88+
Edge = "edge"
89+
90+
// Region is the command line flag to set the Cloudflare Edge region to connect to
91+
Region = "region"
92+
93+
// IsAutoUpdated is the command line flag to signal the new process that cloudflared has been autoupdated
94+
IsAutoUpdated = "is-autoupdated"
95+
96+
// LBPool is the command line flag to set the name of the load balancing pool to add this origin to
97+
LBPool = "lb-pool"
98+
99+
// Retries is the command line flag to set the maximum number of retries for connection/protocol errors
100+
Retries = "retries"
101+
102+
// MaxEdgeAddrRetries is the command line flag to set the maximum number of times to retry on edge addrs before falling back to a lower protocol
103+
MaxEdgeAddrRetries = "max-edge-addr-retries"
104+
105+
// GracePeriod is the command line flag to set the maximum amount of time that cloudflared waits to shut down if it is still serving requests
106+
GracePeriod = "grace-period"
107+
108+
// ICMPV4Src is the command line flag to set the source address and the interface name to send/receive ICMPv4 messages
109+
ICMPV4Src = "icmpv4-src"
110+
111+
// ICMPV6Src is the command line flag to set the source address and the interface name to send/receive ICMPv6 messages
112+
ICMPV6Src = "icmpv6-src"
113+
114+
// ProxyDns is the command line flag to run DNS server over HTTPS
115+
ProxyDns = "proxy-dns"
116+
117+
// Name is the command line to set the name of the tunnel
118+
Name = "name"
119+
120+
// AutoUpdateFreq is the command line for setting the frequency that cloudflared checks for updates
121+
AutoUpdateFreq = "autoupdate-freq"
122+
123+
// NoAutoUpdate is the command line flag to disable cloudflared from checking for updates
124+
NoAutoUpdate = "no-autoupdate"
125+
126+
// LogLevel is the command line flag for the cloudflared logging level
127+
LogLevel = "loglevel"
128+
129+
// LogLevelSSH is the command line flag for the cloudflared ssh logging level
130+
LogLevelSSH = "log-level"
131+
132+
// TransportLogLevel is the command line flag for the transport logging level
133+
TransportLogLevel = "transport-loglevel"
134+
135+
// LogFile is the command line flag to define the file where application logs will be stored
136+
LogFile = "logfile"
137+
138+
// LogDirectory is the command line flag to define the directory where application logs will be stored.
139+
LogDirectory = "log-directory"
140+
141+
// TraceOutput is the command line flag to set the name of trace output file
142+
TraceOutput = "trace-output"
143+
144+
// OriginCert is the command line flag to define the path for the origin certificate used by cloudflared
145+
OriginCert = "origincert"
146+
147+
// Metrics is the command line flag to define the address of the metrics server
148+
Metrics = "metrics"
149+
150+
// MetricsUpdateFreq is the command line flag to define how frequently tunnel metrics are updated
151+
MetricsUpdateFreq = "metrics-update-freq"
152+
)

cmd/cloudflared/main.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212

1313
"github.com/cloudflare/cloudflared/cmd/cloudflared/access"
1414
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
15+
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
1516
"github.com/cloudflare/cloudflared/cmd/cloudflared/proxydns"
1617
"github.com/cloudflare/cloudflared/cmd/cloudflared/tail"
1718
"github.com/cloudflare/cloudflared/cmd/cloudflared/tunnel"
@@ -105,7 +106,7 @@ func commands(version func(c *cli.Context)) []*cli.Command {
105106
Usage: "specify if you wish to update to the latest beta version",
106107
},
107108
&cli.BoolFlag{
108-
Name: "force",
109+
Name: cfdflags.Force,
109110
Usage: "specify if you wish to force an upgrade to the latest version regardless of the current version",
110111
Hidden: true,
111112
},

cmd/cloudflared/tail/cmd.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ import (
1818
"nhooyr.io/websocket"
1919

2020
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
21+
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
2122
"github.com/cloudflare/cloudflared/credentials"
22-
"github.com/cloudflare/cloudflared/logger"
2323
"github.com/cloudflare/cloudflared/management"
2424
)
2525

@@ -119,13 +119,13 @@ func buildTailCommand(subcommands []*cli.Command) *cli.Command {
119119
Value: "",
120120
},
121121
&cli.StringFlag{
122-
Name: logger.LogLevelFlag,
122+
Name: cfdflags.LogLevel,
123123
Value: "info",
124124
Usage: "Application logging level {debug, info, warn, error, fatal}",
125125
EnvVars: []string{"TUNNEL_LOGLEVEL"},
126126
},
127127
&cli.StringFlag{
128-
Name: credentials.OriginCertFlag,
128+
Name: cfdflags.OriginCert,
129129
Usage: "Path to the certificate generated for your origin when you run cloudflared login.",
130130
EnvVars: []string{"TUNNEL_ORIGIN_CERT"},
131131
Value: credentials.FindDefaultOriginCertPath(),
@@ -169,7 +169,7 @@ func handleValidationError(resp *http.Response, log *zerolog.Logger) {
169169
// logger will be created to emit only against the os.Stderr as to not obstruct with normal output from
170170
// management requests
171171
func createLogger(c *cli.Context) *zerolog.Logger {
172-
level, levelErr := zerolog.ParseLevel(c.String(logger.LogLevelFlag))
172+
level, levelErr := zerolog.ParseLevel(c.String(cfdflags.LogLevel))
173173
if levelErr != nil {
174174
level = zerolog.InfoLevel
175175
}
@@ -183,9 +183,10 @@ func createLogger(c *cli.Context) *zerolog.Logger {
183183
// parseFilters will attempt to parse provided filters to send to with the EventStartStreaming
184184
func parseFilters(c *cli.Context) (*management.StreamingFilters, error) {
185185
var level *management.LogLevel
186-
var events []management.LogEventType
187186
var sample float64
188187

188+
events := make([]management.LogEventType, 0)
189+
189190
argLevel := c.String("level")
190191
argEvents := c.StringSlice("event")
191192
argSample := c.Float64("sample")
@@ -225,7 +226,7 @@ func parseFilters(c *cli.Context) (*management.StreamingFilters, error) {
225226

226227
// getManagementToken will make a call to the Cloudflare API to acquire a management token for the requested tunnel.
227228
func getManagementToken(c *cli.Context, log *zerolog.Logger) (string, error) {
228-
userCreds, err := credentials.Read(c.String(credentials.OriginCertFlag), log)
229+
userCreds, err := credentials.Read(c.String(cfdflags.OriginCert), log)
229230
if err != nil {
230231
return "", err
231232
}
@@ -331,6 +332,7 @@ func Run(c *cli.Context) error {
331332
header["cf-trace-id"] = []string{trace}
332333
}
333334
ctx := c.Context
335+
// nolint: bodyclose
334336
conn, resp, err := websocket.Dial(ctx, u.String(), &websocket.DialOptions{
335337
HTTPHeader: header,
336338
})

0 commit comments

Comments
 (0)