Skip to content

Commit

Permalink
[APP-6156] [APP-6480] [APP-5849] Unify agent subsystems into a single…
Browse files Browse the repository at this point in the history
… binary (#37)
  • Loading branch information
Otterverse authored Oct 21, 2024
1 parent 35667e2 commit 2268a2a
Show file tree
Hide file tree
Showing 33 changed files with 4,030 additions and 202 deletions.
22 changes: 9 additions & 13 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
service:
golangci-lint-version: 1.55.2
golangci-lint-version: 1.60.3
run:
deadline: 900s
modules-download-mode: readonly
Expand All @@ -11,45 +11,39 @@ linters:
- containedctx
- contextcheck
- cyclop
- deadcode
- depguard
- exhaustivestruct
- execinquery
- exportloopref
- exhaustruct
- forcetypeassert
- funlen
- gocognit
- godox
- goerr113
- err113
- gochecknoglobals
- gochecknoinits
- gocyclo
- gofmt
- goimports
- golint
- gomnd
- ifshort
- importas
- interfacebloat
- interfacer
- ireturn
- maintidx
- maligned
- makezero
- mnd
- musttag
- nestif
- nlreturn
- nosnakecase
- nonamedreturns
- nosprintfhostport
- paralleltest
- perfsprint
- prealloc
- revive
- scopelint
- structcheck
- tagliatelle
- testpackage
- thelper # false positives
- varcheck
- varnamelen
- wrapcheck
- wsl
Expand All @@ -62,7 +56,6 @@ linters-settings:
- default
- prefix(github.com/viamrobotics/agent-provisioning)
gofumpt:
lang-version: "1.21"
extra-rules: true
govet:
enable-all: true
Expand All @@ -81,6 +74,9 @@ issues:
- exhaustive
- goconst
- gosec
- path: ^cmd/provisioning-client/
linters:
- forbidigo
exclude-use-default: false
max-per-linter: 0
max-same-issues: 0
10 changes: 5 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ else
PATH_VERSION = v$(TAG_VERSION)
endif

LDFLAGS = "-s -w -X 'github.com/viamrobotics/agent/subsystems/viamagent.Version=${TAG_VERSION}' -X 'github.com/viamrobotics/agent/subsystems/viamagent.GitRevision=${GIT_REVISION}'"
LDFLAGS = "-s -w -X 'github.com/viamrobotics/agent.Version=${TAG_VERSION}' -X 'github.com/viamrobotics/agent.GitRevision=${GIT_REVISION}'"
TAGS = osusergo,netgo


Expand All @@ -33,16 +33,16 @@ arm64:
amd64:
make GOARCH=amd64

bin/viam-agent-$(PATH_VERSION)-$(LINUX_ARCH): go.* *.go */*.go */*/*.go subsystems/viamagent/*.service
go build -o $@ -tags $(TAGS) -ldflags $(LDFLAGS) ./cmd/viam-agent/main.go
bin/viam-agent-$(PATH_VERSION)-$(LINUX_ARCH): go.* *.go */*.go */*/*.go subsystems/viamagent/*.service Makefile
go build -o $@ -trimpath -tags $(TAGS) -ldflags $(LDFLAGS) ./cmd/viam-agent/main.go
test "$(PATH_VERSION)" != "custom" && cp $@ bin/viam-agent-stable-$(LINUX_ARCH) || true

.PHONY: clean
clean:
rm -rf bin/

bin/golangci-lint:
GOBIN=`pwd`/bin go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.55.2
bin/golangci-lint: Makefile
GOBIN=`pwd`/bin go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.60.3

.PHONY: lint
lint: bin/golangci-lint
Expand Down
147 changes: 147 additions & 0 deletions cmd/provisioning-client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package main

import (
"bytes"
"context"
"fmt"
"strings"

"github.com/jessevdk/go-flags"
"github.com/viamrobotics/agent/subsystems/provisioning"
pb "go.viam.com/api/provisioning/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)

func main() {
ctx := context.TODO()

var opts struct {
Address string `description:"Address/port to dial (ex: 'localhost:4772')" long:"address" short:"a"`

SSID string `description:"SSID to set" long:"ssid"`
PSK string `description:"PSK/Password for wifi" long:"psk"`

AppAddr string `default:"https://app.viam.com:443" description:"Cloud address to set in viam.json" long:"appaddr"`
PartID string `description:"PartID to set in viam.json" long:"partID"`
Secret string `description:"Device secret to set in viam.json" long:"secret"`

Status bool `description:"Get device status" long:"status" short:"s"`
Networks bool `description:"List networks" long:"networks" short:"n"`
Help bool `description:"Show this help message" long:"help" short:"h"`
}

parser := flags.NewParser(&opts, flags.IgnoreUnknown)
parser.Usage = "runs as a background service and manages updates and the process lifecycle for viam-server."

_, err := parser.Parse()
if err != nil {
panic(err)
}

if opts.Address == "" || (opts.PartID == "" && opts.SSID == "" && !opts.Networks && !opts.Status) {
opts.Help = true
}

if opts.Help {
var b bytes.Buffer
parser.WriteHelp(&b)

fmt.Println(b.String())
return
}

if opts.PartID != "" || opts.Secret != "" {
if opts.PartID == "" || opts.Secret == "" || opts.AppAddr == "" {
fmt.Println("Error: Must set both Secret and PartID (and optionally AppAddr) at the same time!")
return
}
}

conn, err := grpc.NewClient(opts.Address, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
fmt.Println(err)
}
defer func() {
err := conn.Close()
if err != nil {
fmt.Println(err)
}
}()

client := pb.NewProvisioningServiceClient(conn)

if opts.Status {
GetStatus(ctx, client)
}

if opts.Networks {
GetNetworks(ctx, client)
}

if opts.PartID != "" {
SetDeviceCreds(ctx, client, opts.PartID, opts.Secret, opts.AppAddr)
}

if opts.SSID != "" {
SetWifiCreds(ctx, client, opts.SSID, opts.PSK)
}
}

func GetStatus(ctx context.Context, client pb.ProvisioningServiceClient) {
resp, err := client.GetSmartMachineStatus(ctx, &pb.GetSmartMachineStatusRequest{})
if err != nil {
fmt.Println(err)
return
}

fmt.Printf("Online: %t, Configured: %t, Provisioning: %v, Last: %v, Errors: %s\n",
resp.GetIsOnline(),
resp.GetHasSmartMachineCredentials(),
resp.GetProvisioningInfo(),
resp.GetLatestConnectionAttempt(),
strings.Join(resp.GetErrors(), "\n"),
)
}

func GetNetworks(ctx context.Context, client pb.ProvisioningServiceClient) {
resp, err := client.GetNetworkList(ctx, &pb.GetNetworkListRequest{})
if err != nil {
fmt.Println(err)
return
}

for _, network := range resp.GetNetworks() {
fmt.Printf("SSID: %s, Signal: %d%%, Security: %s\n", network.GetSsid(), network.GetSignal(), network.GetSecurity())
}
}

func SetDeviceCreds(ctx context.Context, client pb.ProvisioningServiceClient, id, secret, appaddr string) {
req := &pb.SetSmartMachineCredentialsRequest{
Cloud: &pb.CloudConfig{
Id: id,
Secret: secret,
AppAddress: appaddr,
},
}

_, err := client.SetSmartMachineCredentials(ctx, req)
if err != nil {
fmt.Println("Error setting device credentials ", err)
return
}
}

func SetWifiCreds(ctx context.Context, client pb.ProvisioningServiceClient, ssid, psk string) {
req := &pb.SetNetworkCredentialsRequest{
Type: provisioning.NetworkTypeWifi,
Ssid: ssid,
Psk: psk,
}

_, err := client.SetNetworkCredentials(ctx, req)
if err != nil {
fmt.Println("Error setting wifi credentials ", err)
return
}
}
44 changes: 26 additions & 18 deletions cmd/viam-agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"github.com/pkg/errors"
"github.com/viamrobotics/agent"
"github.com/viamrobotics/agent/subsystems/provisioning"
"github.com/viamrobotics/agent/subsystems/syscfg"
_ "github.com/viamrobotics/agent/subsystems/syscfg"
"github.com/viamrobotics/agent/subsystems/viamagent"
"github.com/viamrobotics/agent/subsystems/viamserver"
"go.viam.com/rdk/logging"
Expand All @@ -36,16 +36,23 @@ var (

//nolint:gocognit
func main() {
ctx := setupExitSignalHandling()
ctx, cancel := setupExitSignalHandling()

defer func() {
cancel()
activeBackgroundWorkers.Wait()
}()

//nolint:lll
var opts struct {
Config string `default:"/etc/viam.json" description:"Path to config file" long:"config" short:"c"`
Debug bool `description:"Enable debug logging (for agent only)" env:"VIAM_AGENT_DEBUG" long:"debug" short:"d"`
Fast bool `description:"Enable fast start mode" env:"VIAM_AGENT_FAST_START" long:"fast" short:"f"`
Help bool `description:"Show this help message" long:"help" short:"h"`
Version bool `description:"Show version" long:"version" short:"v"`
Install bool `description:"Install systemd service" long:"install"`
DevMode bool `description:"Allow non-root and non-service" env:"VIAM_AGENT_DEVMODE" long:"dev-mode"`
Config string `default:"/etc/viam.json" description:"Path to config file" long:"config" short:"c"`
ProvisioningConfig string `default:"/etc/viam-provisioning.json" description:"Path to provisioning (customization) config file" long:"provisioning" short:"p"`
Debug bool `description:"Enable debug logging (agent only)" env:"VIAM_AGENT_DEBUG" long:"debug" short:"d"`
Fast bool `description:"Enable fast start mode" env:"VIAM_AGENT_FAST_START" long:"fast" short:"f"`
Help bool `description:"Show this help message" long:"help" short:"h"`
Version bool `description:"Show version" long:"version" short:"v"`
Install bool `description:"Install systemd service" long:"install"`
DevMode bool `description:"Allow non-root and non-service" env:"VIAM_AGENT_DEVMODE" long:"dev-mode"`
}

parser := flags.NewParser(&opts, flags.IgnoreUnknown)
Expand All @@ -64,14 +71,12 @@ func main() {

if opts.Version {
//nolint:forbidigo
fmt.Printf("Version: %s\nGit Revision: %s\n", viamagent.GetVersion(), viamagent.GetRevision())
fmt.Printf("Version: %s\nGit Revision: %s\n", agent.GetVersion(), agent.GetRevision())
return
}

if opts.Debug {
globalLogger = logging.NewDebugLogger("viam-agent")
provisioning.Debug = true
syscfg.Debug = true
}

// need to be root to go any further than this
Expand Down Expand Up @@ -112,10 +117,15 @@ func main() {
}
}()

// pass the provisioning path arg to the subsystem
absProvConfigPath, err := filepath.Abs(opts.ProvisioningConfig)
exitIfError(err)
provisioning.ProvisioningConfigFilePath = absProvConfigPath
globalLogger.Infof("provisioning config file path: %s", absProvConfigPath)

// tie the manager config to the viam-server config
absConfigPath, err := filepath.Abs(opts.Config)
exitIfError(err)

viamserver.ConfigFilePath = absConfigPath
provisioning.AppConfigFilePath = absConfigPath
globalLogger.Infof("config file path: %s", absConfigPath)
Expand Down Expand Up @@ -156,7 +166,6 @@ func main() {
globalLogger.Warn("waiting for user provisioning")
if !utils.SelectContextOrWait(ctx, time.Second*10) {
manager.CloseAll()
activeBackgroundWorkers.Wait()
return
}
if err := manager.LoadConfig(absConfigPath); err == nil {
Expand Down Expand Up @@ -209,6 +218,7 @@ func main() {
globalLogger.Error(err)
}
if needRestart {
manager.CloseAll()
globalLogger.Info("updated self, exiting to await restart with new version")
return
}
Expand All @@ -217,11 +227,9 @@ func main() {
manager.StartBackgroundChecks(ctx)
<-ctx.Done()
manager.CloseAll()

activeBackgroundWorkers.Wait()
}

func setupExitSignalHandling() context.Context {
func setupExitSignalHandling() (context.Context, func()) {
ctx, cancel := context.WithCancel(context.Background())
sigChan := make(chan os.Signal, 16)
activeBackgroundWorkers.Add(1)
Expand Down Expand Up @@ -266,7 +274,7 @@ func setupExitSignalHandling() context.Context {
}()

signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGABRT)
return ctx
return ctx, cancel
}

func exitIfError(err error) {
Expand Down
Loading

0 comments on commit 2268a2a

Please sign in to comment.