Skip to content

Commit bfdb0c7

Browse files
lmpnjcsf
authored andcommitted
TUN-8855: fix lint issues
## Summary Fix lint issues necessary for a subsequent PR. This is only separate to allow a better code review of the actual changes. Closes TUN-8855
1 parent 45f67c2 commit bfdb0c7

File tree

8 files changed

+53
-62
lines changed

8 files changed

+53
-62
lines changed

cmd/cloudflared/macos_service.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"os"
88

9+
homedir "github.com/mitchellh/go-homedir"
910
"github.com/pkg/errors"
1011
"github.com/urfave/cli/v2"
1112

@@ -17,7 +18,7 @@ const (
1718
launchdIdentifier = "com.cloudflare.cloudflared"
1819
)
1920

20-
func runApp(app *cli.App, graceShutdownC chan struct{}) {
21+
func runApp(app *cli.App, _ chan struct{}) {
2122
app.Commands = append(app.Commands, &cli.Command{
2223
Name: "service",
2324
Usage: "Manages the cloudflared launch agent",
@@ -207,3 +208,15 @@ func uninstallLaunchd(c *cli.Context) error {
207208
}
208209
return err
209210
}
211+
212+
func userHomeDir() (string, error) {
213+
// This returns the home dir of the executing user using OS-specific method
214+
// for discovering the home dir. It's not recommended to call this function
215+
// when the user has root permission as $HOME depends on what options the user
216+
// use with sudo.
217+
homeDir, err := homedir.Dir()
218+
if err != nil {
219+
return "", errors.Wrap(err, "Cannot determine home directory for the user")
220+
}
221+
return homeDir, nil
222+
}

cmd/cloudflared/main.go

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,11 @@ package main
22

33
import (
44
"fmt"
5-
"math/rand"
65
"os"
76
"strings"
87
"time"
98

109
"github.com/getsentry/sentry-go"
11-
homedir "github.com/mitchellh/go-homedir"
12-
"github.com/pkg/errors"
1310
"github.com/urfave/cli/v2"
1411
"go.uber.org/automaxprocs/maxprocs"
1512

@@ -52,10 +49,8 @@ var (
5249
func main() {
5350
// FIXME: TUN-8148: Disable QUIC_GO ECN due to bugs in proper detection if supported
5451
os.Setenv("QUIC_GO_DISABLE_ECN", "1")
55-
56-
rand.Seed(time.Now().UnixNano())
5752
metrics.RegisterBuildInfo(BuildType, BuildTime, Version)
58-
maxprocs.Set()
53+
_, _ = maxprocs.Set()
5954
bInfo := cliutil.GetBuildInfo(BuildType, Version)
6055

6156
// Graceful shutdown channel used by the app. When closed, app must terminate gracefully.
@@ -184,18 +179,6 @@ func action(graceShutdownC chan struct{}) cli.ActionFunc {
184179
})
185180
}
186181

187-
func userHomeDir() (string, error) {
188-
// This returns the home dir of the executing user using OS-specific method
189-
// for discovering the home dir. It's not recommended to call this function
190-
// when the user has root permission as $HOME depends on what options the user
191-
// use with sudo.
192-
homeDir, err := homedir.Dir()
193-
if err != nil {
194-
return "", errors.Wrap(err, "Cannot determine home directory for the user")
195-
}
196-
return homeDir, nil
197-
}
198-
199182
// In order to keep the amount of noise sent to Sentry low, typical network errors can be filtered out here by a substring match.
200183
func captureError(err error) {
201184
errorMessage := err.Error()

cmd/cloudflared/tunnel/cmd.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ var (
126126
routeFailMsg = fmt.Sprintf("failed to provision routing, please create it manually via Cloudflare dashboard or UI; "+
127127
"most likely you already have a conflicting record there. You can also rerun this command with --%s to overwrite "+
128128
"any existing DNS records for this hostname.", overwriteDNSFlag)
129-
deprecatedClassicTunnelErr = fmt.Errorf("Classic tunnels have been deprecated, please use Named Tunnels. (https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/)")
129+
errDeprecatedClassicTunnel = fmt.Errorf("Classic tunnels have been deprecated, please use Named Tunnels. (https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/)")
130130
// TODO: TUN-8756 the list below denotes the flags that do not possess any kind of sensitive information
131131
// however this approach is not maintainble in the long-term.
132132
nonSecretFlagsList = []string{
@@ -326,7 +326,7 @@ func TunnelCommand(c *cli.Context) error {
326326

327327
// Classic tunnel usage is no longer supported
328328
if c.String("hostname") != "" {
329-
return deprecatedClassicTunnelErr
329+
return errDeprecatedClassicTunnel
330330
}
331331

332332
if c.IsSet("proxy-dns") {
@@ -615,8 +615,10 @@ func waitToShutdown(wg *sync.WaitGroup,
615615
log.Debug().Msg("Graceful shutdown signalled")
616616
if gracePeriod > 0 {
617617
// wait for either grace period or service termination
618+
ticker := time.NewTicker(gracePeriod)
619+
defer ticker.Stop()
618620
select {
619-
case <-time.Tick(gracePeriod):
621+
case <-ticker.C:
620622
case <-errC:
621623
}
622624
}
@@ -644,7 +646,7 @@ func waitToShutdown(wg *sync.WaitGroup,
644646

645647
func notifySystemd(waitForSignal *signal.Signal) {
646648
<-waitForSignal.Wait()
647-
daemon.SdNotify(false, "READY=1")
649+
_, _ = daemon.SdNotify(false, "READY=1")
648650
}
649651

650652
func writePidFile(waitForSignal *signal.Signal, pidPathname string, log *zerolog.Logger) {

cmd/cloudflared/tunnel/configuration.go

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,24 +36,11 @@ const (
3636
)
3737

3838
var (
39-
developerPortal = "https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup"
40-
serviceUrl = developerPortal + "/tunnel-guide/local/as-a-service/"
41-
argumentsUrl = developerPortal + "/tunnel-guide/local/local-management/arguments/"
42-
4339
secretFlags = [2]*altsrc.StringFlag{credentialsContentsFlag, tunnelTokenFlag}
4440

4541
configFlags = []string{"autoupdate-freq", "no-autoupdate", "retries", "protocol", "loglevel", "transport-loglevel", "origincert", "metrics", "metrics-update-freq", "edge-ip-version", "edge-bind-address"}
4642
)
4743

48-
func generateRandomClientID(log *zerolog.Logger) (string, error) {
49-
u, err := uuid.NewRandom()
50-
if err != nil {
51-
log.Error().Msgf("couldn't create UUID for client ID %s", err)
52-
return "", err
53-
}
54-
return u.String(), nil
55-
}
56-
5744
func logClientOptions(c *cli.Context, log *zerolog.Logger) {
5845
flags := make(map[string]interface{})
5946
for _, flag := range c.FlagNames() {
@@ -233,13 +220,13 @@ func prepareTunnelConfig(
233220
Observer: observer,
234221
ReportedVersion: info.Version(),
235222
// Note TUN-3758 , we use Int because UInt is not supported with altsrc
236-
Retries: uint(c.Int("retries")),
223+
Retries: uint(c.Int("retries")), // nolint: gosec
237224
RunFromTerminal: isRunningFromTerminal(),
238225
NamedTunnel: namedTunnel,
239226
ProtocolSelector: protocolSelector,
240227
EdgeTLSConfigs: edgeTLSConfigs,
241228
FeatureSelector: featureSelector,
242-
MaxEdgeAddrRetries: uint8(c.Int("max-edge-addr-retries")),
229+
MaxEdgeAddrRetries: uint8(c.Int("max-edge-addr-retries")), // nolint: gosec
243230
RPCTimeout: c.Duration(rpcTimeout),
244231
WriteStreamTimeout: c.Duration(writeStreamTimeout),
245232
DisableQUICPathMTUDiscovery: c.Bool(quicDisablePathMTUDiscovery),

cmd/cloudflared/tunnel/subcommands.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ func fmtConnections(connections []cfapi.Connection, showRecentlyDisconnected boo
441441
sort.Strings(sortedColos)
442442

443443
// Map each colo to its frequency, combine into output string.
444-
var output []string
444+
output := make([]string, 0, len(sortedColos))
445445
for _, coloName := range sortedColos {
446446
output = append(output, fmt.Sprintf("%dx%s", numConnsPerColo[coloName], coloName))
447447
}
@@ -467,10 +467,15 @@ func readyCommand(c *cli.Context) error {
467467
}
468468

469469
requestURL := fmt.Sprintf("http://%s/ready", metricsOpts)
470-
res, err := http.Get(requestURL)
470+
req, err := http.NewRequest(http.MethodGet, requestURL, nil)
471471
if err != nil {
472472
return err
473473
}
474+
res, err := http.DefaultClient.Do(req)
475+
if err != nil {
476+
return err
477+
}
478+
defer res.Body.Close()
474479
if res.StatusCode != 200 {
475480
body, err := io.ReadAll(res.Body)
476481
if err != nil {

connection/protocol.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import (
1414
const (
1515
AvailableProtocolFlagMessage = "Available protocols: 'auto' - automatically chooses the best protocol over time (the default; and also the recommended one); 'quic' - based on QUIC, relying on UDP egress to Cloudflare edge; 'http2' - using Go's HTTP2 library, relying on TCP egress to Cloudflare edge"
1616
// edgeH2muxTLSServerName is the server name to establish h2mux connection with edge (unused, but kept for legacy reference).
17-
edgeH2muxTLSServerName = "cftunnel.com"
17+
_ = "cftunnel.com"
1818
// edgeH2TLSServerName is the server name to establish http2 connection with edge
1919
edgeH2TLSServerName = "h2.cftunnel.com"
2020
// edgeQUICServerName is the server name to establish quic connection with edge.
@@ -24,11 +24,9 @@ const (
2424
ResolveTTL = time.Hour
2525
)
2626

27-
var (
28-
// ProtocolList represents a list of supported protocols for communication with the edge
29-
// in order of precedence for remote percentage fetcher.
30-
ProtocolList = []Protocol{QUIC, HTTP2}
31-
)
27+
// ProtocolList represents a list of supported protocols for communication with the edge
28+
// in order of precedence for remote percentage fetcher.
29+
var ProtocolList = []Protocol{QUIC, HTTP2}
3230

3331
type Protocol int64
3432

@@ -58,7 +56,7 @@ func (p Protocol) String() string {
5856
case QUIC:
5957
return "quic"
6058
default:
61-
return fmt.Sprintf("unknown protocol")
59+
return "unknown protocol"
6260
}
6361
}
6462

@@ -246,11 +244,11 @@ func NewProtocolSelector(
246244
return newRemoteProtocolSelector(fetchedProtocol, ProtocolList, threshold, protocolFetcher, resolveTTL, log), nil
247245
}
248246

249-
return nil, fmt.Errorf("Unknown protocol %s, %s", protocolFlag, AvailableProtocolFlagMessage)
247+
return nil, fmt.Errorf("unknown protocol %s, %s", protocolFlag, AvailableProtocolFlagMessage)
250248
}
251249

252250
func switchThreshold(accountTag string) int32 {
253251
h := fnv.New32a()
254252
_, _ = h.Write([]byte(accountTag))
255-
return int32(h.Sum32() % 100)
253+
return int32(h.Sum32() % 100) // nolint: gosec
256254
}

connection/quic_connection.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,15 @@ func (q *quicConnection) Serve(ctx context.Context) error {
103103
// amount of the grace period, allowing requests to finish before we cancel the context, which will
104104
// make cloudflared exit.
105105
if err := q.serveControlStream(ctx, controlStream); err == nil {
106-
select {
107-
case <-ctx.Done():
108-
case <-time.Tick(q.gracePeriod):
106+
if q.gracePeriod > 0 {
107+
// In Go1.23 this can be removed and replaced with time.Ticker
108+
// see https://pkg.go.dev/time#Tick
109+
ticker := time.NewTicker(q.gracePeriod)
110+
defer ticker.Stop()
111+
select {
112+
case <-ctx.Done():
113+
case <-ticker.C:
114+
}
109115
}
110116
}
111117
cancel()

features/features.go

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,13 @@ const (
1111
FeatureDatagramV3 = "support_datagram_v3"
1212
)
1313

14-
var (
15-
defaultFeatures = []string{
16-
FeatureAllowRemoteConfig,
17-
FeatureSerializedHeaders,
18-
FeatureDatagramV2,
19-
FeatureQUICSupportEOF,
20-
FeatureManagementLogs,
21-
}
22-
)
14+
var defaultFeatures = []string{
15+
FeatureAllowRemoteConfig,
16+
FeatureSerializedHeaders,
17+
FeatureDatagramV2,
18+
FeatureQUICSupportEOF,
19+
FeatureManagementLogs,
20+
}
2321

2422
// Features set by user provided flags
2523
type staticFeatures struct {
@@ -47,7 +45,6 @@ const (
4745

4846
// Remove any duplicates from the slice
4947
func Dedup(slice []string) []string {
50-
5148
// Convert the slice into a set
5249
set := make(map[string]bool, 0)
5350
for _, str := range slice {

0 commit comments

Comments
 (0)