Skip to content

Commit aba4339

Browse files
committed
Fix SonarQube string literal duplication issues
Extract repeated string literals into named constants to improve code maintainability and reduce duplication across multiple files: - pkg/certificates/cli.go - pkg/netceptor/external_backend.go - pkg/netceptor/netceptor.go - pkg/workceptor/command.go - pkg/workceptor/controlsvc.go - pkg/workceptor/kubernetes.go - pkg/workceptor/remote_work.go Assisted-by: Claude <noreply@anthropic.com>
1 parent 561d9e5 commit aba4339

File tree

7 files changed

+68
-39
lines changed

7 files changed

+68
-39
lines changed

pkg/certificates/cli.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ import (
1515
"github.com/spf13/viper"
1616
)
1717

18+
const receptorCertificatesAppName = "receptor-certificates"
19+
1820
// InitCA Initialize Certificate Authority.
1921
func InitCA(opts *CertOptions, certOut, keyOut string, osWrapper Oser) error {
2022
ca, err := CreateCA(opts, &RsaWrapper{})
@@ -273,10 +275,10 @@ func init() {
273275
if version > 1 {
274276
return
275277
}
276-
cmdline.RegisterConfigTypeForApp("receptor-certificates",
278+
cmdline.RegisterConfigTypeForApp(receptorCertificatesAppName,
277279
"cert-init", "Initialize PKI CA", InitCAConfig{}, cmdline.Exclusive, cmdline.Section(certSection))
278-
cmdline.RegisterConfigTypeForApp("receptor-certificates",
280+
cmdline.RegisterConfigTypeForApp(receptorCertificatesAppName,
279281
"cert-makereq", "Create certificate request", MakeReqConfig{}, cmdline.Exclusive, cmdline.Section(certSection))
280-
cmdline.RegisterConfigTypeForApp("receptor-certificates",
282+
cmdline.RegisterConfigTypeForApp(receptorCertificatesAppName,
281283
"cert-signreq", "Sign request and produce certificate", SignReqConfig{}, cmdline.Exclusive, cmdline.Section(certSection))
282284
}

pkg/netceptor/external_backend.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import (
1212
"github.com/gorilla/websocket"
1313
)
1414

15+
const errSessionClosed = "session closed: %s"
16+
1517
// ExternalBackend is a backend implementation for the situation when non-Receptor code
1618
// is initiating connections, outside the control of a Receptor-managed accept loop.
1719
type ExternalBackend struct {
@@ -36,7 +38,7 @@ func MessageConnFromNetConn(conn net.Conn) MessageConn {
3638
// WriteMessage writes a message to the connection.
3739
func (mc *netMessageConn) WriteMessage(ctx context.Context, data []byte) error {
3840
if ctx.Err() != nil {
39-
return fmt.Errorf("session closed: %s", ctx.Err())
41+
return fmt.Errorf(errSessionClosed, ctx.Err())
4042
}
4143
buf := mc.framer.SendData(data)
4244
n, err := mc.conn.Write(buf)
@@ -59,7 +61,7 @@ func (mc *netMessageConn) ReadMessage(ctx context.Context, timeout time.Duration
5961
}
6062
for {
6163
if ctx.Err() != nil {
62-
return nil, fmt.Errorf("session closed: %s", ctx.Err())
64+
return nil, fmt.Errorf(errSessionClosed, ctx.Err())
6365
}
6466
if mc.framer.MessageReady() {
6567
break
@@ -108,7 +110,7 @@ func MessageConnFromWebsocketConn(conn *websocket.Conn) MessageConn {
108110
// WriteMessage writes a message to the connection.
109111
func (mc *websocketMessageConn) WriteMessage(ctx context.Context, data []byte) error {
110112
if ctx.Err() != nil {
111-
return fmt.Errorf("session closed: %s", ctx.Err())
113+
return fmt.Errorf(errSessionClosed, ctx.Err())
112114
}
113115

114116
return mc.conn.WriteMessage(websocket.BinaryMessage, data)
@@ -117,7 +119,7 @@ func (mc *websocketMessageConn) WriteMessage(ctx context.Context, data []byte) e
117119
// ReadMessage reads a message from the connection.
118120
func (mc *websocketMessageConn) ReadMessage(ctx context.Context, _ time.Duration) ([]byte, error) {
119121
if ctx.Err() != nil {
120-
return nil, fmt.Errorf("session closed: %s", ctx.Err())
122+
return nil, fmt.Errorf(errSessionClosed, ctx.Err())
121123
}
122124
messageType, data, err := mc.conn.ReadMessage()
123125
if messageType != websocket.BinaryMessage {

pkg/netceptor/netceptor.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"crypto/tls"
88
"encoding/binary"
99
"encoding/json"
10+
"errors"
1011
"fmt"
1112
"io"
1213
"math"
@@ -42,6 +43,8 @@ const defaultMaxForwardingHops = 30
4243
// defaultMaxConnectionIdleTime is the maximum time a connection can go without data before we consider it failed.
4344
const defaultMaxConnectionIdleTime = 2*defaultRouteUpdateTime + 1*time.Second
4445

46+
const errMustProvideName = "must provide a name"
47+
4548
// MainInstance is the global instance of Netceptor instantiated by the command-line main() function.
4649
var MainInstance *Netceptor
4750

@@ -932,7 +935,7 @@ func (s *Netceptor) GetServerTLSConfig(name string) (*tls.Config, error) {
932935
// AddWorkCommand records a work command so it can be included in service announcements.
933936
func (s *Netceptor) AddWorkCommand(command string, secure bool) error {
934937
if command == "" {
935-
return fmt.Errorf("must provide a name")
938+
return errors.New(errMustProvideName)
936939
}
937940
wC := WorkCommand{WorkType: command, Secure: secure}
938941
s.workCommandsLock.Lock()
@@ -945,7 +948,7 @@ func (s *Netceptor) AddWorkCommand(command string, secure bool) error {
945948
// SetServerTLSConfig stores a server TLS config by name.
946949
func (s *Netceptor) SetServerTLSConfig(name string, config *tls.Config) error {
947950
if name == "" {
948-
return fmt.Errorf("must provide a name")
951+
return errors.New(errMustProvideName)
949952
}
950953
s.serverTLSConfigs[name] = config
951954

@@ -984,7 +987,7 @@ func (s *Netceptor) GetClientTLSConfig(name string, expectedHostName string, exp
984987
// SetClientTLSConfig stores a client TLS config by name.
985988
func (s *Netceptor) SetClientTLSConfig(name string, config *tls.Config, pinnedFingerprints [][]byte) error {
986989
if name == "" {
987-
return fmt.Errorf("must provide a name")
990+
return errors.New(errMustProvideName)
988991
}
989992
s.clientTLSConfigs[name] = config
990993
s.clientPinnedFingerprints[name] = pinnedFingerprints

pkg/workceptor/command.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ import (
2424
"github.com/spf13/viper"
2525
)
2626

27-
const errMsgStatusFileUpdate = "Error updating status file %s: %s"
27+
const (
28+
errMsgStatusFileUpdate = "Error updating status file %s: %s"
29+
receptorWorkersAppName = "receptor-workers"
30+
)
2831

2932
type BaseWorkUnitForWorkUnit interface {
3033
CancelContext()
@@ -537,12 +540,12 @@ func init() {
537540
if version > 1 {
538541
return
539542
}
540-
cmdline.RegisterConfigTypeForApp("receptor-workers",
543+
cmdline.RegisterConfigTypeForApp(receptorWorkersAppName,
541544
"work-signing", "Private key to sign work submissions", SigningKeyPrivateCfg{}, cmdline.Singleton, cmdline.Section(workersSection))
542-
cmdline.RegisterConfigTypeForApp("receptor-workers",
545+
cmdline.RegisterConfigTypeForApp(receptorWorkersAppName,
543546
"work-verification", "Public key to verify work submissions", VerifyingKeyPublicCfg{}, cmdline.Singleton, cmdline.Section(workersSection))
544-
cmdline.RegisterConfigTypeForApp("receptor-workers",
547+
cmdline.RegisterConfigTypeForApp(receptorWorkersAppName,
545548
"work-command", "Run a worker using an external command", CommandWorkerCfg{}, cmdline.Section(workersSection))
546-
cmdline.RegisterConfigTypeForApp("receptor-workers",
549+
cmdline.RegisterConfigTypeForApp(receptorWorkersAppName,
547550
"command-runner", "Wrapper around a process invocation", commandRunnerCfg{}, cmdline.Hidden)
548551
}

pkg/workceptor/controlsvc.go

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ type workceptorCommand struct {
2424
params map[string]interface{}
2525
}
2626

27+
const (
28+
errFieldMissing = "field %s missing"
29+
)
30+
31+
const (
32+
cmdCancel = "cancel"
33+
cmdRelease = "release"
34+
cmdForceRelease = "force-release"
35+
cmdStatus = "status"
36+
cmdList = "list"
37+
)
38+
2739
func (t *workceptorCommandType) InitFromString(params string) (controlsvc.ControlCommand, error) {
2840
tokens := strings.Split(params, " ")
2941
if len(tokens) == 0 {
@@ -44,11 +56,11 @@ func (t *workceptorCommandType) InitFromString(params string) (controlsvc.Contro
4456
if len(tokens) > 3 {
4557
c.params["params"] = strings.Join(tokens[3:], " ")
4658
}
47-
case "list":
59+
case cmdList:
4860
if len(tokens) > 1 {
4961
c.params["unitid"] = tokens[1]
5062
}
51-
case "status", "cancel", "release", "force-release":
63+
case cmdStatus, cmdCancel, cmdRelease, cmdForceRelease:
5264
if len(tokens) < 2 {
5365
return nil, fmt.Errorf("work %s requires a unit ID", c.subcommand)
5466
}
@@ -82,7 +94,7 @@ func (t *workceptorCommandType) InitFromString(params string) (controlsvc.Contro
8294
func strFromMap(config map[string]interface{}, name string) (string, error) {
8395
value, ok := config[name]
8496
if !ok {
85-
return "", fmt.Errorf("field %s missing", name)
97+
return "", fmt.Errorf(errFieldMissing, name)
8698
}
8799
valueStr, ok := value.(string)
88100
if !ok {
@@ -96,7 +108,7 @@ func strFromMap(config map[string]interface{}, name string) (string, error) {
96108
func intFromMap(config map[string]interface{}, name string) (int64, error) {
97109
value, ok := config[name]
98110
if !ok {
99-
return 0, fmt.Errorf("field %s missing", name)
111+
return 0, fmt.Errorf(errFieldMissing, name)
100112
}
101113
valueInt, ok := value.(int64)
102114
if ok {
@@ -120,7 +132,7 @@ func intFromMap(config map[string]interface{}, name string) (int64, error) {
120132
func boolFromMap(config map[string]interface{}, name string) (bool, error) {
121133
value, ok := config[name]
122134
if !ok {
123-
return false, fmt.Errorf("field %s missing", name)
135+
return false, fmt.Errorf(errFieldMissing, name)
124136
}
125137
valueBoolStr, ok := value.(string)
126138
if !ok {
@@ -163,7 +175,7 @@ func (t *workceptorCommandType) InitFromJSON(config map[string]interface{}) (con
163175
if err != nil {
164176
return nil, err
165177
}
166-
case "status", "cancel", "release", "force-release":
178+
case cmdStatus, cmdCancel, cmdRelease, cmdForceRelease:
167179
c.params["unitid"], err = strFromMap(config, "unitid")
168180
if err != nil {
169181
return nil, err
@@ -172,7 +184,7 @@ func (t *workceptorCommandType) InitFromJSON(config map[string]interface{}) (con
172184
if err == nil {
173185
c.params["signature"] = signature
174186
}
175-
case "list":
187+
case cmdList:
176188
unitID, err := strFromMap(config, "unitid")
177189
if err == nil {
178190
c.params["unitid"] = unitID
@@ -327,7 +339,7 @@ func (c *workceptorCommand) ControlFunc(ctx context.Context, nc controlsvc.Netce
327339
}
328340

329341
return cfr, nil
330-
case "list":
342+
case cmdList:
331343
var unitList []string
332344
targetUnitID, ok := c.params["unitid"].(string)
333345
if ok {
@@ -346,7 +358,7 @@ func (c *workceptorCommand) ControlFunc(ctx context.Context, nc controlsvc.Netce
346358
}
347359

348360
return cfr, nil
349-
case "status":
361+
case cmdStatus:
350362
unitid, err := strFromMap(c.params, "unitid")
351363
if err != nil {
352364
return nil, err
@@ -357,7 +369,7 @@ func (c *workceptorCommand) ControlFunc(ctx context.Context, nc controlsvc.Netce
357369
}
358370

359371
return cfr, nil
360-
case "cancel", "release", "force-release":
372+
case cmdCancel, cmdRelease, cmdForceRelease:
361373
unitid, err := strFromMap(c.params, "unitid")
362374
if err != nil {
363375
return nil, err
@@ -369,7 +381,7 @@ func (c *workceptorCommand) ControlFunc(ctx context.Context, nc controlsvc.Netce
369381
cfr := make(map[string]interface{})
370382
var pendingMsg string
371383
var completeMsg string
372-
if c.subcommand == "cancel" {
384+
if c.subcommand == cmdCancel {
373385
pendingMsg = "cancel pending"
374386
completeMsg = "cancelled"
375387
} else {
@@ -388,10 +400,10 @@ func (c *workceptorCommand) ControlFunc(ctx context.Context, nc controlsvc.Netce
388400
if err != nil {
389401
return nil, err
390402
}
391-
if c.subcommand == "cancel" {
403+
if c.subcommand == cmdCancel {
392404
err = unit.Cancel()
393405
} else {
394-
err = unit.Release(c.subcommand == "force-release")
406+
err = unit.Release(c.subcommand == cmdForceRelease)
395407
}
396408
if err != nil && !IsPending(err) {
397409
return nil, err

pkg/workceptor/kubernetes.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,11 @@ var ErrPodFailed = fmt.Errorf("pod failed to start")
179179
// ErrImagePullBackOff is returned when the image for the container in the Pod cannot be pulled.
180180
var ErrImagePullBackOff = fmt.Errorf("container failed to start")
181181

182-
const WorkerContainerName = "worker"
182+
const (
183+
WorkerContainerName = "worker"
184+
errOpenStdout = "Error opening stdout file: %s"
185+
statusPodRunning = "Pod Running"
186+
)
183187

184188
// podRunningAndReady is a completion criterion for pod ready to be attached to.
185189
func podRunningAndReady(kw KubeUnit) func(event watch.Event) (bool, error) {
@@ -765,7 +769,7 @@ func (kw *KubeUnit) CreatePod(env map[string]string) error {
765769
} else if err != nil { // any other error besides ErrPodCompleted
766770
stdout, err2 := NewStdoutWriter(FileSystem{}, kw.UnitDir())
767771
if err2 != nil {
768-
errMsg := fmt.Sprintf("Error opening stdout file: %s", err2)
772+
errMsg := fmt.Sprintf(errOpenStdout, err2)
769773
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
770774
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
771775

@@ -962,7 +966,7 @@ func (kw *KubeUnit) RunWorkUsingLogger() {
962966
// open stdout writer that writes to work unit's data directory
963967
stdout, err := NewStdoutWriter(FileSystem{}, kw.UnitDir())
964968
if err != nil {
965-
errMsg := fmt.Sprintf("Error opening stdout file: %s", err)
969+
errMsg := fmt.Sprintf(errOpenStdout, err)
966970
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
967971
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
968972

@@ -989,7 +993,7 @@ func (kw *KubeUnit) RunWorkUsingLogger() {
989993
streamWait.Add(2)
990994

991995
if skipStdin {
992-
kw.UpdateBasicStatus(WorkStateRunning, "Pod Running", stdout.Size())
996+
kw.UpdateBasicStatus(WorkStateRunning, statusPodRunning, stdout.Size())
993997
streamWait.Done()
994998
} else {
995999
retryCount := kw.GetKubeRetryCount()
@@ -1125,7 +1129,7 @@ func (kw *KubeUnit) RunWorkUsingLogger() {
11251129
close(stdinErrChan) // signal STDOUT goroutine to stop
11261130
} else {
11271131
if stdin.Error() == io.EOF {
1128-
kw.UpdateBasicStatus(WorkStateRunning, "Pod Running", stdout.Size())
1132+
kw.UpdateBasicStatus(WorkStateRunning, statusPodRunning, stdout.Size())
11291133
} else {
11301134
// this is probably not possible...
11311135
errMsg := fmt.Sprintf("Error reading stdin: %s", stdin.Error())
@@ -1421,7 +1425,7 @@ func (kw *KubeUnit) runWorkUsingTCP() {
14211425
// Open stdout writer
14221426
stdout, err := NewStdoutWriter(FileSystem{}, kw.UnitDir())
14231427
if err != nil {
1424-
errMsg := fmt.Sprintf("Error opening stdout file: %s", err)
1428+
errMsg := fmt.Sprintf(errOpenStdout, err)
14251429
kw.GetWorkceptor().nc.GetLogger().Error(errMsg) //nolint:govet
14261430
kw.UpdateBasicStatus(WorkStateFailed, errMsg, 0)
14271431
cancel()
@@ -1465,7 +1469,7 @@ func (kw *KubeUnit) runWorkUsingTCP() {
14651469
case <-stdin.Done():
14661470
err := stdin.Error()
14671471
if err == io.EOF {
1468-
kw.UpdateBasicStatus(WorkStateRunning, "Pod Running", stdout.Size())
1472+
kw.UpdateBasicStatus(WorkStateRunning, statusPodRunning, stdout.Size())
14691473
} else {
14701474
kw.UpdateBasicStatus(WorkStateFailed, fmt.Sprintf("Error reading stdin: %s", err), stdout.Size())
14711475
cancel()

pkg/workceptor/remote_work.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ import (
2222
"github.com/ansible/receptor/pkg/utils"
2323
)
2424

25-
const errMsgRemoteExtraDataMissing = "remote ExtraData missing"
25+
const (
26+
errMsgRemoteExtraDataMissing = "remote ExtraData missing"
27+
errRemoteRead = "read error reading from %s: %s"
28+
)
2629

2730
// remoteUnit implements the WorkUnit interface for the Receptor remote worker plugin.
2831
type remoteUnit struct {
@@ -205,7 +208,7 @@ func (rw *remoteUnit) StartRemoteUnit(ctx context.Context, conn net.Conn, reader
205208
}
206209
response, err := utils.ReadStringContext(ctx, reader, '\n')
207210
if err != nil {
208-
return fmt.Errorf("read error reading from %s: %s", red.RemoteNode, err)
211+
return fmt.Errorf(errRemoteRead, red.RemoteNode, err)
209212
}
210213
submitIDRegex := regexp.MustCompile(`with ID ([a-zA-Z0-9]+)\.`)
211214
match := submitIDRegex.FindSubmatch([]byte(response))
@@ -237,7 +240,7 @@ func (rw *remoteUnit) StartRemoteUnit(ctx context.Context, conn net.Conn, reader
237240
}
238241
response, err = utils.ReadStringContext(ctx, reader, '\n')
239242
if err != nil {
240-
return fmt.Errorf("read error reading from %s: %s", red.RemoteNode, err)
243+
return fmt.Errorf(errRemoteRead, red.RemoteNode, err)
241244
}
242245
resultErrorRegex := regexp.MustCompile("ERROR: (.*)")
243246
match = resultErrorRegex.FindSubmatch([]byte(response))
@@ -286,7 +289,7 @@ func (rw *remoteUnit) cancelOrReleaseRemoteUnit(ctx context.Context, conn net.Co
286289
}
287290
response, err := utils.ReadStringContext(ctx, reader, '\n')
288291
if err != nil {
289-
return fmt.Errorf("read error reading from %s: %s", red.RemoteNode, err)
292+
return fmt.Errorf(errRemoteRead, red.RemoteNode, err)
290293
}
291294
if response[:5] == "ERROR" {
292295
return fmt.Errorf("error cancelling remote unit: %s", response[6:])

0 commit comments

Comments
 (0)