add linters (#23)

- switchTrue
      - importShadow
      - httpNoBody
      - paramTypeCombine
      - emptyStringTest
      - builtinShadow
      - exposedSyncMutex
      - importas

Signed-off-by: SammyOina <sammyoina@gmail.com>
This commit is contained in:
Sammy Kerata Oina
2023-11-24 20:59:42 +03:00
committed by GitHub
parent 5adf0349a3
commit 18508796c1
20 changed files with 103 additions and 86 deletions
+15
View File
@@ -8,11 +8,25 @@ issues:
max-same-issues: 10
linters-settings:
importas:
no-unaliased: true
no-extra-aliases: false
alias:
- pkg: github.com/absmach/magistrala/logger
alias: mglog
gocritic:
enabled-checks:
- captLocal
- dupImport
- singleCaseSwitch
- switchTrue
- importShadow
- httpNoBody
- paramTypeCombine
- emptyStringTest
- builtinShadow
- exposedSyncMutex
disabled-checks:
- appendAssign
enabled-tags:
@@ -35,6 +49,7 @@ linters-settings:
linters:
disable-all: true
enable:
- importas
- gocritic
- gosimple
- errcheck
+2 -2
View File
@@ -200,8 +200,8 @@ func decodeAttestationResponse(_ context.Context, grpcResponse interface{}) (int
// Run implements the Run method of the agent.AgentServiceClient interface.
func (c grpcClient) Run(ctx context.Context, request *agent.RunRequest, _ ...grpc.CallOption) (*agent.RunResponse, error) {
ctx, close := context.WithTimeout(ctx, c.timeout)
defer close()
ctx, cancel := context.WithTimeout(ctx, c.timeout)
defer cancel()
res, err := c.run(ctx, &runReq{Computation: request.Computation})
if err != nil {
+3 -3
View File
@@ -11,19 +11,19 @@ import (
"fmt"
"time"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/ultravioletrs/cocos/agent"
)
var _ agent.Service = (*loggingMiddleware)(nil)
type loggingMiddleware struct {
logger logger.Logger
logger mglog.Logger
svc agent.Service
}
// LoggingMiddleware adds logging facilities to the core service.
func LoggingMiddleware(svc agent.Service, logger logger.Logger) agent.Service {
func LoggingMiddleware(svc agent.Service, logger mglog.Logger) agent.Service {
return &loggingMiddleware{logger, svc}
}
+3 -3
View File
@@ -14,7 +14,7 @@ import (
"slices"
"time"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/messaging"
"github.com/ultravioletrs/cocos/pkg/socket"
)
@@ -74,7 +74,7 @@ const (
var _ Service = (*agentService)(nil)
// New instantiates the agent service implementation.
func New(ctx context.Context, logger logger.Logger, publisher messaging.Publisher) Service {
func New(ctx context.Context, logger mglog.Logger, publisher messaging.Publisher) Service {
svc := &agentService{
sm: NewStateMachine(logger),
publisher: publisher,
@@ -235,7 +235,7 @@ func (as *agentService) publishEvent(ctx context.Context, subtopic, body string)
}
}
func run(ctx context.Context, algoContent []byte, dataContent []byte) ([]byte, error) {
func run(ctx context.Context, algoContent, dataContent []byte) ([]byte, error) {
listener, err := socket.StartUnixSocketServer(socketPath)
if err != nil {
return nil, fmt.Errorf("error creating stdout pipe: %v", err)
+14 -8
View File
@@ -7,7 +7,7 @@ import (
"fmt"
"sync"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
)
type state int
@@ -35,16 +35,16 @@ const (
// StateMachine represents the state machine.
type StateMachine struct {
sync.Mutex
mu sync.Mutex
State state
EventChan chan event
Transitions map[state]map[event]state
StateFunctions map[state]func()
logger logger.Logger
logger mglog.Logger
}
// NewStateMachine creates a new StateMachine.
func NewStateMachine(logger logger.Logger) *StateMachine {
func NewStateMachine(logger mglog.Logger) *StateMachine {
sm := &StateMachine{
State: idle,
EventChan: make(chan event),
@@ -81,9 +81,9 @@ func (sm *StateMachine) Start(ctx context.Context) {
case event := <-sm.EventChan:
nextState, valid := sm.Transitions[sm.GetState()][event]
if valid {
sm.Lock()
sm.mu.Lock()
sm.State = nextState
sm.Unlock()
sm.mu.Unlock()
sm.logger.Debug(fmt.Sprintf("Transition: %v -> %v\n", sm.GetState(), nextState))
} else {
sm.logger.Error(fmt.Sprintf("Invalid transition: %v -> ???\n", sm.GetState()))
@@ -104,8 +104,14 @@ func (sm *StateMachine) SendEvent(event event) {
}
func (sm *StateMachine) GetState() state {
sm.Lock()
sm.mu.Lock()
state := sm.State
sm.Unlock()
sm.mu.Unlock()
return state
}
func (sm *StateMachine) SetState(state state) {
sm.mu.Lock()
sm.State = state
sm.mu.Unlock()
}
+5 -9
View File
@@ -7,7 +7,7 @@ import (
"fmt"
"testing"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
)
func TestStateMachineTransitions(t *testing.T) {
@@ -26,16 +26,14 @@ func TestStateMachineTransitions(t *testing.T) {
for _, testCase := range testCases {
t.Run(fmt.Sprintf("Transition from %v to %v", testCase.fromState, testCase.expected), func(t *testing.T) {
sm := NewStateMachine(logger.NewMock())
sm := NewStateMachine(mglog.NewMock())
done := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
go func() {
sm.Start(ctx)
close(done)
}()
sm.Lock()
sm.State = testCase.fromState
sm.Unlock()
sm.SetState(testCase.fromState)
sm.SendEvent(testCase.event)
@@ -50,13 +48,11 @@ func TestStateMachineTransitions(t *testing.T) {
}
func TestStateMachineInvalidTransition(t *testing.T) {
sm := NewStateMachine(logger.NewMock())
sm := NewStateMachine(mglog.NewMock())
ctx, cancel := context.WithCancel(context.Background())
go sm.Start(ctx)
sm.Lock()
sm.State = idle
sm.Unlock()
sm.SetState(idle)
sm.SendEvent(dataReceived)
+3 -3
View File
@@ -8,7 +8,7 @@ import (
"log"
"os"
mflog "github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/messaging"
"github.com/absmach/magistrala/pkg/messaging/brokers"
"github.com/absmach/magistrala/pkg/uuid"
@@ -51,7 +51,7 @@ func main() {
log.Fatalf("failed to load %s configuration : %s", svcName, err)
}
logger, err := mflog.New(os.Stdout, cfg.LogLevel)
logger, err := mglog.New(os.Stdout, cfg.LogLevel)
if err != nil {
log.Fatalf(err.Error())
}
@@ -106,7 +106,7 @@ func main() {
}
}
func newService(ctx context.Context, logger mflog.Logger, tracer trace.Tracer, publisher messaging.Publisher) agent.Service {
func newService(ctx context.Context, logger mglog.Logger, tracer trace.Tracer, publisher messaging.Publisher) agent.Service {
svc := agent.New(ctx, logger, publisher)
svc = api.LoggingMiddleware(svc, logger)
+9 -9
View File
@@ -7,7 +7,7 @@ import (
"log"
"os"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/ultravioletrs/cocos/cli"
@@ -32,7 +32,7 @@ func main() {
log.Fatalf("failed to load %s configuration : %s", svcName, err)
}
logger, err := logger.New(os.Stdout, cfg.LogLevel)
logger, err := mglog.New(os.Stdout, cfg.LogLevel)
if err != nil {
log.Fatalf("Error creating logger: %s", err)
}
@@ -48,9 +48,9 @@ func main() {
}
defer agentGRPCClient.Close()
sdk := sdk.NewAgentSDK(logger, agentClient)
agentSDK := sdk.NewAgentSDK(logger, agentClient)
cli.SetSDK(sdk)
cli.SetSDK(agentSDK)
rootCmd := &cobra.Command{
Use: "cocos-cli [command]",
@@ -81,11 +81,11 @@ func main() {
}
// Root Commands
rootCmd.AddCommand(cli.NewAlgorithmsCmd(sdk))
rootCmd.AddCommand(cli.NewDatasetsCmd(sdk))
rootCmd.AddCommand(cli.NewResultsCmd(sdk))
rootCmd.AddCommand(cli.NewRunCmd(sdk))
rootCmd.AddCommand(cli.NewAttestationCmd(sdk))
rootCmd.AddCommand(cli.NewAlgorithmsCmd(agentSDK))
rootCmd.AddCommand(cli.NewDatasetsCmd(agentSDK))
rootCmd.AddCommand(cli.NewResultsCmd(agentSDK))
rootCmd.AddCommand(cli.NewRunCmd(agentSDK))
rootCmd.AddCommand(cli.NewAttestationCmd(agentSDK))
if err := rootCmd.Execute(); err != nil {
logger.Error(fmt.Sprintf("Command execution failed: %s", err))
+4 -4
View File
@@ -10,7 +10,7 @@ import (
"os"
"strings"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/messaging/brokers"
"github.com/absmach/magistrala/pkg/uuid"
"github.com/ultravioletrs/cocos/agent"
@@ -60,7 +60,7 @@ func main() {
log.Fatalf("failed to load %s configuration : %s", svcName, err)
}
logger, err := logger.New(os.Stdout, cfg.LogLevel)
logger, err := mglog.New(os.Stdout, cfg.LogLevel)
if err != nil {
log.Fatalf(err.Error())
}
@@ -154,8 +154,8 @@ func main() {
}
}
func newService(agent agent.AgentServiceClient, logger logger.Logger, tracer trace.Tracer, qemuCfg qemu.Config) manager.Service {
svc := manager.New(agent, qemuCfg)
func newService(agentClient agent.AgentServiceClient, logger mglog.Logger, tracer trace.Tracer, qemuCfg qemu.Config) manager.Service {
svc := manager.New(agentClient, qemuCfg)
svc = api.LoggingMiddleware(svc, logger)
counter, latency := internal.MakeMetrics(svcName, "api")
+4 -4
View File
@@ -33,20 +33,20 @@ func NewProvider(ctx context.Context, svcName, jaegerurl, instanceID string) (*t
return nil, errNoSvcName
}
url, err := url.Parse(jaegerurl)
jurl, err := url.Parse(jaegerurl)
if err != nil {
return nil, err
}
var exporter *otlptrace.Exporter
switch url.Scheme {
switch jurl.Scheme {
case "http":
exporter, err = otlptracehttp.New(ctx, otlptracehttp.WithEndpoint(url.Host), otlptracehttp.WithURLPath(url.Path), otlptracehttp.WithInsecure())
exporter, err = otlptracehttp.New(ctx, otlptracehttp.WithEndpoint(jurl.Host), otlptracehttp.WithURLPath(jurl.Path), otlptracehttp.WithInsecure())
if err != nil {
return nil, err
}
case "https":
exporter, err = otlptracehttp.New(ctx, otlptracehttp.WithEndpoint(url.Host), otlptracehttp.WithURLPath(url.Path))
exporter, err = otlptracehttp.New(ctx, otlptracehttp.WithEndpoint(jurl.Host), otlptracehttp.WithURLPath(jurl.Path))
if err != nil {
return nil, err
}
+2 -2
View File
@@ -8,11 +8,11 @@ import (
"net"
"time"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/digitalocean/go-libvirt"
)
func Connect(logger logger.Logger) *libvirt.Libvirt {
func Connect(logger mglog.Logger) *libvirt.Libvirt {
// This dials libvirt on the local machine, but you can substitute the first
// two parameters with "tcp", "<ip address>:<port>" to connect to libvirt on
// a remote machine.
+19 -19
View File
@@ -10,12 +10,12 @@ import (
"regexp"
"strings"
"github.com/digitalocean/go-libvirt"
golibvirt "github.com/digitalocean/go-libvirt"
)
var re = regexp.MustCompile(`'([^']*)'`)
func CreateDomain(ctx context.Context, libvirt *libvirt.Libvirt, poolXML, volXML, domXML string) (string, error) {
func CreateDomain(ctx context.Context, libvirt *golibvirt.Libvirt, poolXML, volXML, domXML string) (string, error) {
wd, err := os.Getwd()
if err != nil {
return "", err
@@ -47,78 +47,78 @@ func CreateDomain(ctx context.Context, libvirt *libvirt.Libvirt, poolXML, volXML
return dom.Name, nil
}
func createDomain(libvirtConn *libvirt.Libvirt, poolXML string, volXML string, domXML string) (libvirt.Domain, error) {
func createDomain(libvirtConn *golibvirt.Libvirt, poolXML, volXML, domXML string) (golibvirt.Domain, error) {
pool, err := libvirtConn.StoragePoolCreateXML(poolXML, 0)
_ = pool
if err != nil {
lvErr := err.(libvirt.Error)
lvErr := err.(golibvirt.Error)
if lvErr.Code == 9 {
name, err := entityName(lvErr.Message)
if err != nil {
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
pool, err = libvirtConn.StoragePoolLookupByName(name)
if err != nil {
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
goto pool_exists
}
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
pool_exists:
_, err = libvirtConn.StorageVolCreateXML(pool, volXML, 0)
if err != nil {
lvErr := err.(libvirt.Error)
lvErr := err.(golibvirt.Error)
if lvErr.Code == 90 {
name, err := entityName(lvErr.Message)
if err != nil {
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
_, err = libvirtConn.StorageVolLookupByName(pool, name)
if err != nil {
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
goto vol_exists
}
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
vol_exists:
dom, err := libvirtConn.DomainDefineXMLFlags(domXML, 0)
if err != nil {
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
err = libvirtConn.DomainCreate(dom)
if err != nil {
lvErr := err.(libvirt.Error)
lvErr := err.(golibvirt.Error)
if lvErr.Code == 55 {
return dom, nil
}
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
// extra flags; not used yet, so callers should always pass 0
current, err := libvirtConn.DomainSnapshotCurrent(dom, 0)
if err != nil {
lvErr := err.(libvirt.Error)
lvErr := err.(golibvirt.Error)
if lvErr.Code == 72 {
return dom, nil
}
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
err = libvirtConn.DomainRevertToSnapshot(current, uint32(libvirt.DomainSnapshotRevertRunning))
err = libvirtConn.DomainRevertToSnapshot(current, uint32(golibvirt.DomainSnapshotRevertRunning))
if err != nil {
return libvirt.Domain{}, err
return golibvirt.Domain{}, err
}
return dom, nil
@@ -133,7 +133,7 @@ func entityName(msg string) (string, error) {
return match[1], nil
}
func readXMLFile(filename string, defaultFilename string) (string, error) {
func readXMLFile(filename, defaultFilename string) (string, error) {
if filename == "" {
filename = "./xml/" + defaultFilename
}
+2 -2
View File
@@ -8,7 +8,7 @@ import (
"net"
"time"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/ultravioletrs/cocos/internal/server"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
@@ -29,7 +29,7 @@ type serviceRegister func(srv *grpc.Server)
var _ server.Server = (*Server)(nil)
func New(ctx context.Context, cancel context.CancelFunc, name string, config server.Config, registerService serviceRegister, logger logger.Logger) server.Server {
func New(ctx context.Context, cancel context.CancelFunc, name string, config server.Config, registerService serviceRegister, logger mglog.Logger) server.Server {
listenFullAddress := fmt.Sprintf("%s:%s", config.Host, config.Port)
return &Server{
+2 -2
View File
@@ -8,7 +8,7 @@ import (
"net/http"
"time"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/ultravioletrs/cocos/internal/server"
)
@@ -25,7 +25,7 @@ type Server struct {
var _ server.Server = (*Server)(nil)
func New(ctx context.Context, cancel context.CancelFunc, name string, config server.Config, handler http.Handler, logger logger.Logger) server.Server {
func New(ctx context.Context, cancel context.CancelFunc, name string, config server.Config, handler http.Handler, logger mglog.Logger) server.Server {
listenFullAddress := fmt.Sprintf("%s:%s", config.Host, config.Port)
httpServer := &http.Server{Addr: listenFullAddress, Handler: handler}
return &Server{
+3 -3
View File
@@ -9,7 +9,7 @@ import (
"os/signal"
"syscall"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
)
type Server interface {
@@ -30,7 +30,7 @@ type BaseServer struct {
Name string
Address string
Config Config
Logger logger.Logger
Logger mglog.Logger
Protocol string
}
@@ -49,7 +49,7 @@ func stopAllServer(servers ...Server) error {
return nil
}
func StopHandler(ctx context.Context, cancel context.CancelFunc, logger logger.Logger, svcName string, servers ...Server) error {
func StopHandler(ctx context.Context, cancel context.CancelFunc, logger mglog.Logger, svcName string, servers ...Server) error {
var err error
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGABRT)
+2 -2
View File
@@ -60,8 +60,8 @@ func decodeRunResponse(_ context.Context, grpcResponse interface{}) (interface{}
}
func (client grpcClient) Run(ctx context.Context, req *manager.RunRequest, _ ...grpc.CallOption) (*manager.RunResponse, error) {
ctx, close := context.WithTimeout(ctx, client.timeout)
defer close()
ctx, cancel := context.WithTimeout(ctx, client.timeout)
defer cancel()
runReq := runReq{
Computation: req.GetComputation(),
+3 -3
View File
@@ -11,19 +11,19 @@ import (
"fmt"
"time"
log "github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/ultravioletrs/cocos/manager"
)
var _ manager.Service = (*loggingMiddleware)(nil)
type loggingMiddleware struct {
logger log.Logger
logger mglog.Logger
svc manager.Service
}
// LoggingMiddleware adds logging facilities to the core service.
func LoggingMiddleware(svc manager.Service, logger log.Logger) manager.Service {
func LoggingMiddleware(svc manager.Service, logger mglog.Logger) manager.Service {
return &loggingMiddleware{logger, svc}
}
+3 -3
View File
@@ -6,7 +6,7 @@ import (
"context"
"errors"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/messaging"
)
@@ -14,7 +14,7 @@ const agentTopic = "channels.agent.>"
var errUnexpectedEvent = errors.New("unexpected event from agent")
func NewAgentEventNotifier(ctx context.Context, pubsub messaging.PubSub, logger logger.Logger) error {
func NewAgentEventNotifier(ctx context.Context, pubsub messaging.PubSub, logger mglog.Logger) error {
if err := pubsub.Subscribe(ctx, messaging.SubscriberConfig{
ID: "manager",
Topic: agentTopic,
@@ -27,7 +27,7 @@ func NewAgentEventNotifier(ctx context.Context, pubsub messaging.PubSub, logger
}
type eventHandler struct {
logger logger.Logger
logger mglog.Logger
}
func (ev *eventHandler) Handle(msg *messaging.Message) error {
+2 -2
View File
@@ -38,9 +38,9 @@ type managerService struct {
var _ Service = (*managerService)(nil)
// New instantiates the manager service implementation.
func New(agent agent.AgentServiceClient, qemuCfg qemu.Config) Service {
func New(agentClient agent.AgentServiceClient, qemuCfg qemu.Config) Service {
return &managerService{
agent: agent,
agent: agentClient,
qemuCfg: qemuCfg,
}
}
+3 -3
View File
@@ -6,7 +6,7 @@ import (
"context"
"encoding/json"
"github.com/absmach/magistrala/logger"
mglog "github.com/absmach/magistrala/logger"
"github.com/ultravioletrs/cocos/agent"
)
@@ -14,10 +14,10 @@ var _ agent.Service = (*agentSDK)(nil)
type agentSDK struct {
client agent.AgentServiceClient
logger logger.Logger
logger mglog.Logger
}
func NewAgentSDK(log logger.Logger, agentClient agent.AgentServiceClient) *agentSDK {
func NewAgentSDK(log mglog.Logger, agentClient agent.AgentServiceClient) *agentSDK {
return &agentSDK{
client: agentClient,
logger: log,