Skip to content

chore: perform some lint fixes on orb-agent #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
run:
timeout: 5m
modules-download-mode: readonly

output:
formats: colored-line-number

linters:
enable:
- revive
- errcheck
- unused
- staticcheck
- ineffassign
- govet
- gosimple
- bodyclose
- gci
- gofumpt

issues:
exclude-use-default: false
exclude-rules:
- path: /*.go
text: "package-comments: should have a package comment"
linters:
- revive

severity:
default-severity: error

linters-settings:
gci:
sections:
- standard
- default
- prefix(github.com/netboxlabs/orb-agent)
custom-order: true
go-fumpt:
extra-rules: true
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ test-coverage:
@cat .coverage/cover.out.tmp | grep -Ev "cmd" > .coverage/cover.out
@go tool cover -func=.coverage/cover.out | grep total | awk '{print substr($$3, 1, length($$3)-1)}' > .coverage/coverage.txt

.PHONY: lint
lint:
@golangci-lint run ./... --config .github/golangci.yaml

.PHONY: fix-lint
fix-lint:
@golangci-lint run ./... --config .github/golangci.yaml --fix

agent:
docker build --no-cache \
--build-arg GOARCH=$(GOARCH) \
Expand Down
16 changes: 8 additions & 8 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ import (
"github.com/netboxlabs/orb-agent/agent/version"
)

var (
ErrMqttConnection = errors.New("failed to connect to a broker")
)
var ErrMqttConnection = errors.New("failed to connect to a broker")

type Agent interface {
Start(ctx context.Context, cancelFunc context.CancelFunc) error
Expand Down Expand Up @@ -69,10 +67,12 @@ type orbAgent struct {
configManager config.ConfigManager
}

const retryRequestDuration = time.Second
const retryRequestFixedTime = 15
const retryDurationIncrPerAttempts = 10
const retryMaxAttempts = 4
const (
retryRequestDuration = time.Second
retryRequestFixedTime = 15
retryDurationIncrPerAttempts = 10
retryMaxAttempts = 4
)

type GroupInfo struct {
Name string
Expand All @@ -97,7 +97,6 @@ func New(logger *zap.Logger, c config.Config) (Agent, error) {
}

func (a *orbAgent) managePolicies() error {

if a.config.OrbAgent.Policies == nil {
return errors.New("no policies specified")
}
Expand Down Expand Up @@ -222,6 +221,7 @@ func (a *orbAgent) logoffWithHeartbeat(ctx context.Context) {
}
}
}

func (a *orbAgent) Stop(ctx context.Context) {
a.logger.Info("routine call for stop agent", zap.Any("routine", ctx.Value("routine")))
if a.rpcFromCancelFunc != nil {
Expand Down
1 change: 0 additions & 1 deletion agent/agent_prof_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
)

func Test_orbAgent_startBackends(t *testing.T) {

type args struct {
agentCtx context.Context
}
Expand Down
4 changes: 2 additions & 2 deletions agent/backend/devicediscovery/device_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ func (d *deviceDiscoveryBackend) SetCommsClient(agentID string, client *mqtt.Cli
d.mqttClient = client
otelBaseTopic := strings.Replace(baseTopic, "?", "otlp", 1)
d.otlpMetricsTopic = fmt.Sprintf("%s/m/%c", otelBaseTopic, agentID[0])

}

func (d *deviceDiscoveryBackend) Version() (string, error) {
var info Info
err := d.request("status", &info, http.MethodGet, http.NoBody, "application/json", VersionTimeout)
Expand All @@ -103,6 +103,7 @@ func (d *deviceDiscoveryBackend) Version() (string, error) {
}
return info.Version, nil
}

func (d *deviceDiscoveryBackend) Start(ctx context.Context, cancelFunc context.CancelFunc) error {
d.startTime = time.Now()
d.cancelFunc = cancelFunc
Expand Down Expand Up @@ -192,7 +193,6 @@ func (d *deviceDiscoveryBackend) Start(ctx context.Context, cancelFunc context.C
}

return nil

}

func (d *deviceDiscoveryBackend) Stop(ctx context.Context) error {
Expand Down
4 changes: 2 additions & 2 deletions agent/backend/networkdiscovery/network_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ func (d *networkDiscoveryBackend) SetCommsClient(agentID string, client *mqtt.Cl
d.mqttClient = client
otelBaseTopic := strings.Replace(baseTopic, "?", "otlp", 1)
d.otlpMetricsTopic = fmt.Sprintf("%s/m/%c", otelBaseTopic, agentID[0])

}

func (d *networkDiscoveryBackend) Version() (string, error) {
var info Info
err := d.request("status", &info, http.MethodGet, http.NoBody, "application/json", VersionTimeout)
Expand All @@ -103,6 +103,7 @@ func (d *networkDiscoveryBackend) Version() (string, error) {
}
return info.Version, nil
}

func (d *networkDiscoveryBackend) Start(ctx context.Context, cancelFunc context.CancelFunc) error {
d.startTime = time.Now()
d.cancelFunc = cancelFunc
Expand Down Expand Up @@ -192,7 +193,6 @@ func (d *networkDiscoveryBackend) Start(ctx context.Context, cancelFunc context.
}

return nil

}

func (d *networkDiscoveryBackend) Stop(ctx context.Context) error {
Expand Down
1 change: 0 additions & 1 deletion agent/backend/otel/exporter_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ service:
if _, ok := expectedStruct.Processors["transform/policy_data"]; !ok {
t.Error("missing required attributes/policy_data processor", err)
}

})
}
}
14 changes: 8 additions & 6 deletions agent/backend/otel/otel.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,17 @@ import (

var _ backend.Backend = (*openTelemetryBackend)(nil)

const DefaultPath = "otelcol-contrib"
const DefaultHost = "localhost"
const DefaultPort = 4317
const (
DefaultPath = "otelcol-contrib"
DefaultHost = "localhost"
DefaultPort = 4317
)

type openTelemetryBackend struct {
logger *zap.Logger
startTime time.Time

//policies
// policies
policyRepo policies.PolicyRepo
policyConfigDirectory string
agentTags map[string]string
Expand Down Expand Up @@ -64,7 +66,8 @@ type openTelemetryBackend struct {

// Configure initializes the backend with the given configuration
func (o *openTelemetryBackend) Configure(logger *zap.Logger, repo policies.PolicyRepo,
config map[string]interface{}, common config.BackendCommons) error {
config map[string]interface{}, common config.BackendCommons,
) error {
o.logger = logger
o.logger.Info("configuring OpenTelemetry backend")
o.policyRepo = repo
Expand Down Expand Up @@ -135,7 +138,6 @@ func (o *openTelemetryBackend) Version() (string, error) {
o.logger.Info("running opentelemetry-contrib version", zap.String("version", versionOutput))

return versionOutput, nil

}

func (o *openTelemetryBackend) Start(ctx context.Context, cancelFunc context.CancelFunc) (err error) {
Expand Down
3 changes: 2 additions & 1 deletion agent/backend/otel/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import (
"os"

"github.com/go-cmd/cmd"
"github.com/netboxlabs/orb-agent/agent/policies"
"go.uber.org/zap"
"golang.org/x/exp/slices"
"gopkg.in/yaml.v3"

"github.com/netboxlabs/orb-agent/agent/policies"
)

const tempFileNamePattern = "otel-%s-config.yml"
Expand Down
2 changes: 0 additions & 2 deletions agent/backend/pktvisor/pktvisor.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,6 @@ func (p *pktvisorBackend) Version() (string, error) {
}

func (p *pktvisorBackend) Start(ctx context.Context, cancelFunc context.CancelFunc) error {

// this should record the start time whether it's successful or not
// because it is used by the automatic restart system for last attempt
p.startTime = time.Now()
Expand Down Expand Up @@ -319,7 +318,6 @@ func (p *pktvisorBackend) GetCapabilities() (map[string]interface{}, error) {
}

func (p *pktvisorBackend) FullReset(ctx context.Context) error {

// force a stop, which stops scrape as well. if proc is dead, it no ops.
if state, _, _ := p.getProcRunningStatus(); state == backend.Running {
if err := p.Stop(ctx); err != nil {
Expand Down
1 change: 0 additions & 1 deletion agent/backend/pktvisor/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
)

func (p *pktvisorBackend) ApplyPolicy(data policies.PolicyData, updatePolicy bool) error {

if updatePolicy {
// To update a policy it's necessary first remove it and then apply a new version
if err := p.RemovePolicy(data); err != nil {
Expand Down
15 changes: 9 additions & 6 deletions agent/config/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,21 +77,27 @@ func (cc *cloudConfigManager) request(address string, token string, response int
if getErr != nil {
return getErr
}
defer func() {
if err := res.Body.Close(); err != nil {
cc.logger.Error("failed to close response body", zap.Error(err))
}
}()

if (res.StatusCode < 200) || (res.StatusCode > 299) {
body, err := io.ReadAll(res.Body)
if err != nil {
return errors.New(fmt.Sprintf("expected 2xx status code, no or invalid body: %d", res.StatusCode))
return fmt.Errorf("expected 2xx status code, no or invalid body: %d", res.StatusCode)
}
if body[0] == '{' {
var jsonBody map[string]interface{}
err := json.Unmarshal(body, &jsonBody)
if err == nil {
if errMsg, ok := jsonBody["error"]; ok {
return errors.New(fmt.Sprintf("%d %s", res.StatusCode, errMsg))
return fmt.Errorf("%d %s", res.StatusCode, errMsg)
}
}
}
return errors.New(fmt.Sprintf("%d %s", res.StatusCode, body))
return fmt.Errorf("%d %s", res.StatusCode, body)
}

err = json.NewDecoder(res.Body).Decode(&response)
Expand All @@ -102,7 +108,6 @@ func (cc *cloudConfigManager) request(address string, token string, response int
}

func (cc *cloudConfigManager) autoProvision(apiAddress string, token string) (MQTTConfig, error) {

type AgentRes struct {
ID string `json:"id"`
Key string `json:"key"`
Expand Down Expand Up @@ -149,7 +154,6 @@ func (cc *cloudConfigManager) autoProvision(apiAddress string, token string) (MQ
Key: result.Key,
ChannelID: result.ChannelID,
}, nil

}

func (cc *cloudConfigManager) GetConfig() (MQTTConfig, error) {
Expand Down Expand Up @@ -219,7 +223,6 @@ func (cc *cloudConfigManager) GetConfig() (MQTTConfig, error) {

result.Connect = true
return result, nil

}

func (cc *cloudConfigManager) GetContext(ctx context.Context) context.Context {
Expand Down
2 changes: 2 additions & 0 deletions agent/config/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import (
"go.uber.org/zap"
)

// ConfigManager is the interface for configuration manager
type ConfigManager interface {
GetConfig() (MQTTConfig, error)
GetContext(ctx context.Context) context.Context
}

// New creates a new instance of ConfigManager based on the configuration
func New(logger *zap.Logger, c ManagerConfig) ConfigManager {
switch c.Active {
case "local":
Expand Down
11 changes: 11 additions & 0 deletions agent/config/types.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package config

// APIConfig represents the configuration for the API connection
type APIConfig struct {
Address string `mapstructure:"address"`
Token string `mapstructure:"token"`
}

// MQTTConfig represents the configuration for the MQTT connection
type MQTTConfig struct {
Connect bool `mapstructure:"connect"`
Address string `mapstructure:"address"`
Expand All @@ -13,11 +15,13 @@ type MQTTConfig struct {
ChannelID string `mapstructure:"channel_id"`
}

// CloudConfig represents the configuration for the cloud agent
type CloudConfig struct {
AgentName string `mapstructure:"agent_name"`
AutoProvision bool `mapstructure:"auto_provision"`
}

// Cloud represents the cloud ConfigManager configuration
type Cloud struct {
Config CloudConfig `mapstructure:"config"`
API APIConfig `mapstructure:"api"`
Expand All @@ -31,20 +35,24 @@ type Cloud struct {
Tags map[string]string `mapstructure:"tags"`
}

// Local represents the local ConfigManager configuration.
type Local struct {
Config string `mapstructure:"config"`
}

// ManagerBackends represents the configuration for manager backends, including cloud and local.
type ManagerBackends struct {
Cloud Cloud `mapstructure:"orbcloud"`
Local Local `mapstructure:"local"`
}

// ManagerConfig represents the configuration for the Config Manager
type ManagerConfig struct {
Active string `mapstructure:"active"`
Backends ManagerBackends `mapstructure:"backends"`
}

// BackendCommons represents common configuration for backends
type BackendCommons struct {
Otel struct {
Host string `mapstructure:"host"`
Expand All @@ -57,6 +65,8 @@ type BackendCommons struct {
AgentName string `mapstructure:"agent_name"`
}
}

// OrbAgent represents the configuration for the Orb agent
type OrbAgent struct {
Backends map[string]map[string]interface{} `mapstructure:"backends"`
Policies map[string]map[string]interface{} `mapstructure:"policies"`
Expand All @@ -68,6 +78,7 @@ type OrbAgent struct {
ConfigFile string `mapstructure:"config_file"`
}

// Config represents the overall configuration
type Config struct {
Version float64 `mapstructure:"version"`
OrbAgent OrbAgent `mapstructure:"orb"`
Expand Down
1 change: 0 additions & 1 deletion agent/heartbeats.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ const HeartbeatFreq = 50 * time.Second
const RestartTimeMin = 5 * time.Minute

func (a *orbAgent) sendSingleHeartbeat(ctx context.Context, t time.Time, agentsState fleet.State) {

if a.heartbeatsTopic == "" {
a.logger.Debug("heartbeat topic not yet set, skipping")
return
Expand Down
Loading
Loading