diff --git a/.golangci.yml b/.golangci.yml index 9e855ff725adce897a8c096986bebf2450f7bb0f..9b743a6ea6330ad14659f5117ba01bb2a9987a20 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -25,15 +25,17 @@ output: uniq-by-line: true path-prefix: "" -# custom settings for linters -linters-settings: - gocyclo: - min-complexity: 15 - golint: - min-confidence: 0.8 +issues: + exclude-use-default: false + max-issues-per-linter: 0 + max-same-issues: 0 linters: # enable the specific needed linters + # see here for full list: https://golangci-lint.run/usage/linters/ + # linters to consider: gosimple, containedctx, contextcheck, depguard, errchkjson, errname, exhaustive, exhaustruct, forbidigo, + # gochecknoinits, gocognit, goconst, gocritic, gofumpt, gomnd, gosec, importas, lll, nestif, nilerr, nlreturn, noctx, nolintlint, + # nosnakecase, paralleltest, prealloc, structcheck, testpackage, tparallel, unparam, wastedassign, wrapcheck, wsl disable-all: true enable: - gofmt @@ -46,7 +48,28 @@ linters: - revive - whitespace - deadcode -issues: - exclude-use-default: false - max-issues-per-linter: 0 - max-same-issues: 0 + - errcheck + - ineffassign + - varcheck + - bidichk + - durationcheck + - errorlint + - exportloopref + - grouper + - makezero + - misspell + - nilnil + - predeclared + - godot + +# custom settings for linters +linters-settings: + gocyclo: + min-complexity: 15 + golint: + min-confidence: 0.8 + errcheck: + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions: true diff --git a/cli/adapter/PndAdapter.go b/cli/adapter/PndAdapter.go index 4c7f8b212d5e5e8152a67ab80cbd89fa32a25f21..0cf7996831ddf2db56a67f5865247d362592e63f 100644 --- a/cli/adapter/PndAdapter.go +++ b/cli/adapter/PndAdapter.go @@ -16,7 +16,7 @@ import ( ) // PndAdapter is an API adapter to reflect the NetworkDomain -// interface +// interface. type PndAdapter struct { id uuid.UUID endpoint string @@ -35,12 +35,12 @@ func NewPndAdapter(id, endpoint string) (*PndAdapter, error) { }, nil } -// AddSbi adds an SBI to the PND Adapter. Currently not implemented +// AddSbi adds an SBI to the PND Adapter. Currently not implemented. func (p *PndAdapter) AddSbi(s southbound.SouthboundInterface) error { return &errors.ErrNotYetImplemented{} } -// RemoveSbi removes an SBI from the PND Adapter. Currently not implemented +// RemoveSbi removes an SBI from the PND Adapter. Currently not implemented. func (p *PndAdapter) RemoveSbi(uuid.UUID) error { return &errors.ErrNotYetImplemented{} } @@ -85,7 +85,7 @@ func (p *PndAdapter) GetFlattenedDevices(ctx context.Context) (*ppb.GetFlattened return resp, nil } -// RemoveDevice removes a device from the controller +// RemoveDevice removes a device from the controller. func (p *PndAdapter) RemoveDevice(ctx context.Context, did uuid.UUID) (*ppb.DeleteOndResponse, error) { resp, err := api.DeleteDevice(ctx, p.endpoint, p.id.String(), did.String()) if err != nil { @@ -94,7 +94,7 @@ func (p *PndAdapter) RemoveDevice(ctx context.Context, did uuid.UUID) (*ppb.Dele return resp, nil } -// RemovePnd removes a PND from the controller +// RemovePnd removes a PND from the controller. func (p *PndAdapter) RemovePnd(ctx context.Context, pid uuid.UUID) (*core.DeletePndResponse, error) { resp, err := api.DeletePnd(ctx, p.endpoint, pid.String()) if err != nil { @@ -105,7 +105,7 @@ func (p *PndAdapter) RemovePnd(ctx context.Context, pid uuid.UUID) (*core.Delete // ChangeOND sends an API call to the controller requesting the creation of // a change from the provided Operation, path and value. The Change is marked -// as Pending and times out after the specified timeout period +// as Pending and times out after the specified timeout period. func (p *PndAdapter) ChangeOND(ctx context.Context, duid uuid.UUID, operation ppb.ApiOperation, path string, value ...string) (*ppb.SetPathListResponse, error) { var v string if len(value) != 0 { @@ -119,7 +119,7 @@ func (p *PndAdapter) ChangeOND(ctx context.Context, duid uuid.UUID, operation pp } // Request sends an API call to the controller requesting the specified path -// for the specified device +// for the specified device. func (p *PndAdapter) Request(ctx context.Context, did uuid.UUID, path string) (*ppb.GetPathResponse, error) { resp, err := api.GetPath(ctx, p.endpoint, p.id.String(), did.String(), path) if err != nil { @@ -129,7 +129,7 @@ func (p *PndAdapter) Request(ctx context.Context, did uuid.UUID, path string) (* } // SubscribeONDPath sends an API call to the controller requesting to subscribe -// to a specific path of a specifc device +// to a specific path of a specifc device. func (p *PndAdapter) SubscribeONDPath(ctx context.Context, did uuid.UUID, slist *ppb.SubscriptionList) (ppb.PndService_SubscribePathClient, error) { resp, err := api.SubscribePath(ctx, p.endpoint, p.id.String(), did.String(), slist) if err != nil { @@ -169,7 +169,7 @@ func (p *PndAdapter) RequestAll(ctx context.Context, path string) ([]proto.Messa } // ContainsDevice sends an API call to the controller checking if a device -// with the given UUID is present. Not implemented, always returns false +// with the given UUID is present. Not implemented, always returns false. func (p *PndAdapter) ContainsDevice(uuid.UUID) bool { return false } @@ -185,7 +185,7 @@ func (p *PndAdapter) GetSbi(ctx context.Context, sid string) (*ppb.GetSbiRespons } // GetSBIs sends an API call to the controller requesting the -// registered SBIs. Not implemented, always returns nil +// registered SBIs. Not implemented, always returns nil. func (p *PndAdapter) GetSBIs(ctx context.Context) (*ppb.GetSbiListResponse, error) { resp, err := api.GetSBIs(ctx, p.endpoint, p.id.String()) if err != nil { @@ -194,18 +194,18 @@ func (p *PndAdapter) GetSBIs(ctx context.Context) (*ppb.GetSbiListResponse, erro return resp, nil } -// ID returns the PND Adapter's UUID +// ID returns the PND Adapter's UUID. func (p *PndAdapter) ID() uuid.UUID { return p.id } -// Endpoint returns the PND Adapter's endpoint +// Endpoint returns the PND Adapter's endpoint. func (p *PndAdapter) Endpoint() string { return p.endpoint } // PendingChanges sends an API call to the controller requesting -// the UUIDs of all pending changes +// the UUIDs of all pending changes. func (p *PndAdapter) PendingChanges(ctx context.Context) ([]*ppb.Change, error) { resp, err := api.GetChanges(ctx, p.endpoint, p.id.String()) if err != nil { @@ -215,7 +215,7 @@ func (p *PndAdapter) PendingChanges(ctx context.Context) ([]*ppb.Change, error) } // CommittedChanges sends an API call to the controller requesting -// the UUIDs of all committed changes +// the UUIDs of all committed changes. func (p *PndAdapter) CommittedChanges(ctx context.Context) ([]*ppb.Change, error) { resp, err := api.GetChanges(ctx, p.endpoint, p.id.String()) if err != nil { @@ -225,7 +225,7 @@ func (p *PndAdapter) CommittedChanges(ctx context.Context) ([]*ppb.Change, error } // ConfirmedChanges sends an API call to the controller requesting -// the UUIDs of all confirmed changes +// the UUIDs of all confirmed changes. func (p *PndAdapter) ConfirmedChanges(ctx context.Context) ([]*ppb.Change, error) { resp, err := api.GetChanges(ctx, p.endpoint, p.id.String()) if err != nil { @@ -235,7 +235,7 @@ func (p *PndAdapter) ConfirmedChanges(ctx context.Context) ([]*ppb.Change, error } // GetChange sends an API call to the controller requesting one or more changes -// for the specific PND +// for the specific PND. func (p *PndAdapter) GetChange(ctx context.Context, identifier ...string) (*ppb.GetChangeResponse, error) { resp, err := api.GetChange(ctx, p.endpoint, p.id.String(), identifier...) if err != nil { @@ -244,7 +244,7 @@ func (p *PndAdapter) GetChange(ctx context.Context, identifier ...string) (*ppb. return resp, nil } -// Commit sends an API call to the controller committing the specified change +// Commit sends an API call to the controller committing the specified change. func (p *PndAdapter) Commit(ctx context.Context, cuid uuid.UUID) (*ppb.SetChangeListResponse, error) { resp, err := api.Commit(ctx, p.endpoint, p.id.String(), cuid.String()) if err != nil { @@ -253,7 +253,7 @@ func (p *PndAdapter) Commit(ctx context.Context, cuid uuid.UUID) (*ppb.SetChange return resp, nil } -// Confirm sends an API call to the controller confirming the specified change +// Confirm sends an API call to the controller confirming the specified change. func (p *PndAdapter) Confirm(ctx context.Context, cuid uuid.UUID) (*ppb.SetChangeListResponse, error) { resp, err := api.Confirm(ctx, p.endpoint, p.id.String(), cuid.String()) if err != nil { diff --git a/cli/cmd/change.go b/cli/cmd/change.go index 07eadbeef9e81a79c5983b4bc54a1a0b2d58d274..6f7eafc86627c857f97e9d0e3a6973853655220b 100644 --- a/cli/cmd/change.go +++ b/cli/cmd/change.go @@ -35,7 +35,7 @@ import ( "github.com/spf13/cobra" ) -// changeCmd represents the change command +// changeCmd represents the change command. var changeCmd = &cobra.Command{ Use: "change", Short: "manage changes of the specified PND", diff --git a/cli/cmd/changeCommit.go b/cli/cmd/changeCommit.go index 2c271e9ca6ca58d397e8cd5f09819f7c3c12c1b4..49e035eed2141b1324c441b9383a6534b45cb0f8 100644 --- a/cli/cmd/changeCommit.go +++ b/cli/cmd/changeCommit.go @@ -37,7 +37,7 @@ import ( "github.com/spf13/cobra" ) -// commitCmd represents the commit command +// commitCmd represents the commit command. var commitCmd = &cobra.Command{ Use: "commit [uuid]", Args: cobra.ExactArgs(1), diff --git a/cli/cmd/changeConfirm.go b/cli/cmd/changeConfirm.go index cdc69f8764ee7a308a9dfc5171188d5ad961e82d..249738c6e8550fbff5eacd5359a90b2404276c0a 100644 --- a/cli/cmd/changeConfirm.go +++ b/cli/cmd/changeConfirm.go @@ -37,7 +37,7 @@ import ( "github.com/spf13/cobra" ) -// confirmCmd represents the confirm command +// confirmCmd represents the confirm command. var confirmCmd = &cobra.Command{ Use: "confirm [uuid]", Args: cobra.ExactArgs(1), diff --git a/cli/cmd/changeGet.go b/cli/cmd/changeGet.go index 6495b1e3f85ba5e4c3dae7913878031f2b8ae373..a7c1aa331ab6ab0a408f011303d96b15efae573e 100644 --- a/cli/cmd/changeGet.go +++ b/cli/cmd/changeGet.go @@ -37,7 +37,7 @@ import ( "google.golang.org/protobuf/encoding/protojson" ) -// confirmCmd represents the confirm command +// confirmCmd represents the confirm command. var getCmd = &cobra.Command{ Use: "get [uuid]", Args: cobra.ExactArgs(1), diff --git a/cli/cmd/changeList.go b/cli/cmd/changeList.go index eb2c111e396cd9ba4e41b018425df56b654a99aa..d5b0ea11e877663e38d199f08c2a0ecff570aa7f 100644 --- a/cli/cmd/changeList.go +++ b/cli/cmd/changeList.go @@ -36,7 +36,7 @@ import ( "github.com/spf13/cobra" ) -// changeListCmd represents the list command +// changeListCmd represents the list command. var changeListCmd = &cobra.Command{ Use: "list", Aliases: []string{"ls"}, @@ -64,7 +64,7 @@ var changeListCmd = &cobra.Command{ data = append(data, []string{ch.String(), "pending"}) } for _, ch := range committed { - data = append(data, []string{ch.String(), "commited"}) + data = append(data, []string{ch.String(), "committed"}) } spinner.Success() diff --git a/cli/cmd/device.go b/cli/cmd/device.go index 8d72c373c79a6f3f02d2eb2cf6dee65eda630ae4..41a9cd51c8ee4686039216ce447ba8b30b163345 100644 --- a/cli/cmd/device.go +++ b/cli/cmd/device.go @@ -41,7 +41,7 @@ var password string //var duid string -// deviceCmd represents the device command +// deviceCmd represents the device command. var deviceCmd = &cobra.Command{ Use: "device", Aliases: []string{"dev"}, diff --git a/cli/cmd/deviceCreate.go b/cli/cmd/deviceCreate.go index d8380a581c2d27ecd75f6451b7efff6351934161..9b064025d9048b92d1d3d35a167f69d409707f74 100644 --- a/cli/cmd/deviceCreate.go +++ b/cli/cmd/deviceCreate.go @@ -40,7 +40,7 @@ import ( tpb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/transport" ) -// deviceCreateCmd represents the create command +// deviceCreateCmd represents the create command. var deviceCreateCmd = &cobra.Command{ Use: "create", Short: "creates a device on the controller", diff --git a/cli/cmd/deviceDelete.go b/cli/cmd/deviceDelete.go index f5cc844e6ea5e81d641eb4399812b3dc635891a4..fce779b73711e8e9d210ddf96e360c5e8800894b 100644 --- a/cli/cmd/deviceDelete.go +++ b/cli/cmd/deviceDelete.go @@ -38,7 +38,7 @@ import ( "github.com/spf13/cobra" ) -// deviceDeleteCmd represents the delete command +// deviceDeleteCmd represents the delete command. var deviceDeleteCmd = &cobra.Command{ Use: "delete [uuid] [path]", Args: cobra.ExactArgs(2), @@ -69,7 +69,7 @@ The device UUID and request path must be specified as a positional arguments.`, if r.Status == ppb.Status_STATUS_OK { spinner.Success("A change for path deletion for Device: ", did.String(), "has been created -> Change ID: ", r.GetId()) } else { - spinner.Fail("An error occured while creating a path deletion request for Device with ID: ", r.GetId(), r.GetStatus()) + spinner.Fail("An error occurred while creating a path deletion request for Device with ID: ", r.GetId(), r.GetStatus()) } } return nil diff --git a/cli/cmd/deviceGet.go b/cli/cmd/deviceGet.go index 240eff0501ed99cb73cb1593f7fbdd1db8414c04..dc47ec9a2f25b75d5042813fd58e7e08fee357d2 100644 --- a/cli/cmd/deviceGet.go +++ b/cli/cmd/deviceGet.go @@ -39,7 +39,7 @@ import ( "google.golang.org/protobuf/encoding/protojson" ) -// deviceGetCmd represents the get command +// deviceGetCmd represents the get command. var deviceGetCmd = &cobra.Command{ Use: "get [uuid] [path]", Args: cobra.ExactArgs(2), diff --git a/cli/cmd/deviceList.go b/cli/cmd/deviceList.go index e1c50d3a6030de6846e1b6933f2285bd15ef62ea..870332ecb6ed37e15ac4de0bb05113d39e93c893 100644 --- a/cli/cmd/deviceList.go +++ b/cli/cmd/deviceList.go @@ -37,7 +37,7 @@ import ( "github.com/spf13/cobra" ) -// deviceListCmd represents the listDevice command +// deviceListCmd represents the listDevice command. var deviceListCmd = &cobra.Command{ Use: "list", Aliases: []string{"ls"}, diff --git a/cli/cmd/deviceRemove.go b/cli/cmd/deviceRemove.go index af1346fbade09be3b97a48b6ea410f5646c62fd6..591ee7ad463faea978e05bed329e43677433a94e 100644 --- a/cli/cmd/deviceRemove.go +++ b/cli/cmd/deviceRemove.go @@ -38,7 +38,7 @@ import ( "github.com/spf13/cobra" ) -// deviceRemoveCmd represents the remove command +// deviceRemoveCmd represents the remove command. var deviceRemoveCmd = &cobra.Command{ Use: "remove [uuid]", Aliases: []string{"rm"}, diff --git a/cli/cmd/deviceSet.go b/cli/cmd/deviceSet.go index baaae3419af7b1d27184396830c2c1bc65c662e1..60a7fccb9865d7376c1b5b6f187a782c2d755895 100644 --- a/cli/cmd/deviceSet.go +++ b/cli/cmd/deviceSet.go @@ -44,7 +44,7 @@ var replace bool var file string var forcePush bool -// deviceSetCmd represents the set command +// deviceSetCmd represents the set command. var deviceSetCmd = &cobra.Command{ Use: "set [uuid] [path] [value]", Args: cobra.RangeArgs(2, 3), diff --git a/cli/cmd/deviceShow.go b/cli/cmd/deviceShow.go index 12b08b7269fbb435d4e83556122789a16d4a222a..51be7acf7736292f3ed737b002a7f98d24118780 100644 --- a/cli/cmd/deviceShow.go +++ b/cli/cmd/deviceShow.go @@ -36,7 +36,7 @@ import ( "github.com/spf13/cobra" ) -// deviceShowCmd represents the show command +// deviceShowCmd represents the show command. var deviceShowCmd = &cobra.Command{ Use: "show", Args: cobra.ExactArgs(1), diff --git a/cli/cmd/deviceSubscribe.go b/cli/cmd/deviceSubscribe.go index e3718790bf9d233ca9389048ae629148b785d4ac..1297891fee8ccc93a7521e49522b8d1eb5839e40 100644 --- a/cli/cmd/deviceSubscribe.go +++ b/cli/cmd/deviceSubscribe.go @@ -32,6 +32,7 @@ POSSIBILITY OF SUCH DAMAGE. package cmd import ( + "errors" "io" "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/pnd" @@ -41,7 +42,7 @@ import ( "github.com/spf13/cobra" ) -// deviceGetCmd represents the get command +// deviceGetCmd represents the get command. var deviceSubscribeCmd = &cobra.Command{ Use: "subscribe [uuid] [path]", Args: cobra.ExactArgs(2), @@ -79,7 +80,8 @@ The device UUID and requested paths must be specified as a positional arguments. subscribeResponse, err := subClient.Recv() if err != nil { if err != nil { - if err == io.EOF { + + if errors.Is(err, io.EOF) { break } log.Error(err) diff --git a/cli/cmd/list.go b/cli/cmd/list.go index ad2295ca2f1ccdbab76f10a6d1a8fb12896a9c09..62216bc03c4a3fdf37fecd022344b3839b90bc09 100644 --- a/cli/cmd/list.go +++ b/cli/cmd/list.go @@ -40,7 +40,7 @@ import ( //TODO: this requires us to make getDevices in grpc.go of gosdn public and we //also need to implement GetSBI() -// pndCmd represents the pnd command +// pndCmd represents the pnd command. var listCmd = &cobra.Command{ Use: "list", Aliases: []string{"ls"}, diff --git a/cli/cmd/login.go b/cli/cmd/login.go index 0596b6852f351fdfbe35a97bae8a0a5abef74280..c6909d96dd0620cdd7c4a083aaf170841f9d83cc 100644 --- a/cli/cmd/login.go +++ b/cli/cmd/login.go @@ -40,7 +40,7 @@ import ( "github.com/spf13/viper" ) -// loginCmd represents the login command +// loginCmd represents the login command. var loginCmd = &cobra.Command{ Use: "login", Short: "Logs in for further actions", diff --git a/cli/cmd/logout.go b/cli/cmd/logout.go index 2aeb75e9abafa490aed3ea3d27b3f6d5c05c018f..997b035aaef9979073c94e7a8815454a3657dbcc 100644 --- a/cli/cmd/logout.go +++ b/cli/cmd/logout.go @@ -40,7 +40,7 @@ import ( "github.com/spf13/viper" ) -// logoutCmd represents the logout command +// logoutCmd represents the logout command. var logoutCmd = &cobra.Command{ Use: "logout", Short: "Logs the current user out", diff --git a/cli/cmd/pnd.go b/cli/cmd/pnd.go index 8c42fa66d960cae88c76fb1c0f83ae1f5adc83ef..82ee3470fa43bd4f24747f0630d8bd40d21ef962 100644 --- a/cli/cmd/pnd.go +++ b/cli/cmd/pnd.go @@ -35,7 +35,7 @@ import ( "github.com/spf13/cobra" ) -// pndCmd represents the pnd command +// pndCmd represents the pnd command. var pndCmd = &cobra.Command{ Use: "pnd", Short: "The pnd command contains all sub-commands for PND management", diff --git a/cli/cmd/pndCreate.go b/cli/cmd/pndCreate.go index 4ff4f8c378c793db7eaaf4a01059673ccd1c165b..ac5c05556eaf12c19d0ef9f3d3485dc2e61f6fa0 100644 --- a/cli/cmd/pndCreate.go +++ b/cli/cmd/pndCreate.go @@ -39,7 +39,7 @@ import ( "github.com/spf13/viper" ) -// pndCreateCmd represents the create command +// pndCreateCmd represents the create command. var pndCreateCmd = &cobra.Command{ Use: "create [description]", Args: cobra.ExactArgs(0), diff --git a/cli/cmd/pndGet.go b/cli/cmd/pndGet.go index 735018a6f0077c51b07a5ba0c305d08d9b1c2954..1c2c0a4d6ca1bad19b05b811a03c43f396286d23 100644 --- a/cli/cmd/pndGet.go +++ b/cli/cmd/pndGet.go @@ -37,7 +37,7 @@ import ( "github.com/spf13/viper" ) -// pndGetCmd represents the get command +// pndGetCmd represents the get command. var pndGetCmd = &cobra.Command{ Use: "get", Args: cobra.ExactArgs(1), diff --git a/cli/cmd/pndList.go b/cli/cmd/pndList.go index b0e46360a28d79173aad457d701fda00b91a1110..8e77bbb30bea376aad5c47ccc770180d3a4ef6cc 100644 --- a/cli/cmd/pndList.go +++ b/cli/cmd/pndList.go @@ -38,7 +38,7 @@ import ( "github.com/spf13/cobra" ) -// pndListCmd represents the listPND command +// pndListCmd represents the listPND command. var pndListCmd = &cobra.Command{ Use: "list", Aliases: []string{"ls"}, diff --git a/cli/cmd/pndRemove.go b/cli/cmd/pndRemove.go index 98fb573ee900a245d8e39e6312876a9e01d25d06..9b4eafca334f35733af1af290c40420ddcf84d72 100644 --- a/cli/cmd/pndRemove.go +++ b/cli/cmd/pndRemove.go @@ -38,7 +38,7 @@ import ( "github.com/spf13/cobra" ) -// pndRemoveCmd represents the remove command +// pndRemoveCmd represents the remove command. var pndRemoveCmd = &cobra.Command{ Use: "remove", Aliases: []string{"rm"}, diff --git a/cli/cmd/pndUse.go b/cli/cmd/pndUse.go index f3f77d7970d321bda990c5f658e19093ad4fc6ba..64a1656ba87bb3ce03f67d22990eb73f694d96c6 100644 --- a/cli/cmd/pndUse.go +++ b/cli/cmd/pndUse.go @@ -39,7 +39,7 @@ import ( "github.com/spf13/viper" ) -// pndUseCmd represents the pnd command +// pndUseCmd represents the pnd command. var pndUseCmd = &cobra.Command{ Use: "use [uuid]", Args: cobra.ExactArgs(1), diff --git a/cli/cmd/prompt.go b/cli/cmd/prompt.go index 57c72b695099ec99afc9fe81b02fb1dbabfee8e0..ffc0dd8ca84820667808593ee8d102c75e570b71 100644 --- a/cli/cmd/prompt.go +++ b/cli/cmd/prompt.go @@ -46,7 +46,7 @@ import ( "github.com/spf13/viper" ) -// PromptCompleter provides completion for a device +// PromptCompleter provides completion for a device. type PromptCompleter struct { yangSchemaCompleterMap map[uuid.UUID]*completer.YangSchemaCompleter currentSuggestions []prompt.Suggest @@ -55,14 +55,14 @@ type PromptCompleter struct { history []string } -// NewPromptCompleter returns a new promptCompleter +// NewPromptCompleter returns a new promptCompleter. func NewPromptCompleter() *PromptCompleter { return &PromptCompleter{ yangSchemaCompleterMap: make(map[uuid.UUID]*completer.YangSchemaCompleter), } } -// Run starts the interactive completion +// Run starts the interactive completion. func (pc *PromptCompleter) Run() { title, _ := pterm.DefaultBigText.WithLetters( pterm.NewLettersFromString("go"), @@ -347,7 +347,7 @@ var exitCmd = &cobra.Command{ }, } -// deviceListCmd represents the listDevice command +// deviceListCmd represents the listDevice command. var promptCmd = &cobra.Command{ Use: "prompt", Short: "The prompt command runs the CLI in an interactive shell.", diff --git a/cli/cmd/root.go b/cli/cmd/root.go index f64c570325085908932d9457966d004d1685a541..8e2e8a30f5b1b47eed00af10f75a9a1d9f813d22 100644 --- a/cli/cmd/root.go +++ b/cli/cmd/root.go @@ -31,6 +31,7 @@ POSSIBILITY OF SUCH DAMAGE. package cmd import ( + "errors" "fmt" "os" @@ -55,7 +56,7 @@ var userToken string var pndAdapter *adapter.PndAdapter -// rootCmd represents the base command when called without any subcommands +// rootCmd represents the base command when called without any subcommands. var rootCmd = &cobra.Command{ Use: "gosdnc", Short: "goSDN CLI", @@ -108,7 +109,7 @@ func initConfig() { // If a config file is found, read it in. if err := viper.ReadInConfig(); err != nil { - if _, ok := err.(viper.ConfigFileNotFoundError); ok { + if ok := errors.As(err, &viper.ConfigFileNotFoundError{}); ok { // create folder if it does not exist if err := os.MkdirAll(defaultPath, 0777); err != nil { log.Error("Config directory not found and was unable to create, error: ", err) diff --git a/cli/cmd/userCreate.go b/cli/cmd/userCreate.go index 8246187e14801a449082564858fcf8e4a5c132a9..f233acaf81e021c16198cf91b2d6a98d5df6fa02 100644 --- a/cli/cmd/userCreate.go +++ b/cli/cmd/userCreate.go @@ -39,7 +39,7 @@ import ( "github.com/spf13/viper" ) -// loginCmd represents the login command +// loginCmd represents the login command. var userCreateCmd = &cobra.Command{ Use: "userCreate", Short: "Creates a user with provided data", diff --git a/cli/cmd/userDelete.go b/cli/cmd/userDelete.go index 5efe1f925c97b064f7dffd80be96c5891b9c5cf4..160ed5f49260bb15662e7c08f7e4411b17ec8e85 100644 --- a/cli/cmd/userDelete.go +++ b/cli/cmd/userDelete.go @@ -38,7 +38,7 @@ import ( "github.com/spf13/viper" ) -// loginCmd represents the login command +// loginCmd represents the login command. var userDeleteCmd = &cobra.Command{ Use: "userDelete", Short: "Deletes a user with provided data", diff --git a/cli/cmd/userGet.go b/cli/cmd/userGet.go index 5fcacd84e1457a3e64c3b23eb3fa8378c78ea945..f235141dc04f50ec9b2eef8007c7c11c5ad402c0 100644 --- a/cli/cmd/userGet.go +++ b/cli/cmd/userGet.go @@ -39,7 +39,7 @@ import ( "github.com/spf13/viper" ) -// loginCmd represents the login command +// loginCmd represents the login command. var userGetCmd = &cobra.Command{ Use: "userGet", Short: "Requests one user", diff --git a/cli/cmd/userGetAll.go b/cli/cmd/userGetAll.go index e0719ef78706ee47a1c2679fa812ad73cca7843e..cc9fa09734915861c6149b268d35c66bce5d6eb8 100644 --- a/cli/cmd/userGetAll.go +++ b/cli/cmd/userGetAll.go @@ -38,7 +38,7 @@ import ( "github.com/spf13/viper" ) -// loginCmd represents the login command +// loginCmd represents the login command. var userGetAllCmd = &cobra.Command{ Use: "userGetAll", Short: "Requests all the available users", diff --git a/cli/cmd/userUpdate.go b/cli/cmd/userUpdate.go index b9a2bd1ff509e4331620d4796698b69658dba2c2..dc1d5d48a86bfde6e341270846c049705216f5f1 100644 --- a/cli/cmd/userUpdate.go +++ b/cli/cmd/userUpdate.go @@ -39,7 +39,7 @@ import ( "github.com/spf13/viper" ) -// loginCmd represents the login command +// loginCmd represents the login command. var userUpdateCmd = &cobra.Command{ Use: "userUpdate", Short: "Updates a user with provided data", diff --git a/cli/cmd/utils.go b/cli/cmd/utils.go index 27478a991306410ea83e34c76728139d5a07cc76..e6858699fb54afaff5a849cbcf97cb1225f94564 100644 --- a/cli/cmd/utils.go +++ b/cli/cmd/utils.go @@ -53,7 +53,7 @@ func checkIPPort(string) error { return nil } -// sliceContains checks if a slice contains the given item +// sliceContains checks if a slice contains the given item. func sliceContains[T comparable](slice []T, toCompare T) bool { for _, sliceEntry := range slice { if sliceEntry == toCompare { diff --git a/cli/completer/yangSchemaCompleter.go b/cli/completer/yangSchemaCompleter.go index 9eed2efa376bfc3a0c253186c42ed88d74dd6d92..fe47412d5bb6f17a6a3354e89ac2837187e513ad 100644 --- a/cli/completer/yangSchemaCompleter.go +++ b/cli/completer/yangSchemaCompleter.go @@ -12,14 +12,14 @@ import ( ) var ( - // YangSchemaCompletionSeperator is the seperator for yang schemas + // YangSchemaCompletionSeperator is the separator for yang schemas. YangSchemaCompletionSeperator = string([]byte{' ', '/'}) ) // The idea of path suggestions for a SBI's YANG schema is heavily inspired by // gnmic (https://github.com/karimra/gnmic) -// YangSchemaCompleter represents the YangSchemaCompleter +// YangSchemaCompleter represents the YangSchemaCompleter. type YangSchemaCompleter struct { Cache map[string]*yang.Entry Entry *yang.Entry @@ -106,7 +106,7 @@ func promptFromYangEntry(e *yang.Entry) []prompt.Suggest { return []prompt.Suggest{} } -// Complete provides the actual completion +// Complete provides the actual completion. func (c *YangSchemaCompleter) Complete(d prompt.Document) []prompt.Suggest { p := d.GetWordBeforeCursor() diff --git a/controller/api/apiIntegration_test.go b/controller/api/apiIntegration_test.go index a97a54820db061d3e85f91105982bb903c2547cb..39829243fb344712ce5f020a007939d77bea196a 100644 --- a/controller/api/apiIntegration_test.go +++ b/controller/api/apiIntegration_test.go @@ -2,6 +2,7 @@ package api import ( "context" + "errors" "testing" "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/pnd" @@ -31,9 +32,7 @@ func TestApiIntegration(t *testing.T) { t.Run(tt.name, func(t *testing.T) { defer viper.Reset() if err := Init(context.TODO(), testAPIEndpoint); (err != nil) != tt.wantErr { - switch err.(type) { - case viper.ConfigFileNotFoundError: - default: + if errors.As(err, &viper.ConfigFileNotFoundError{}) { t.Errorf("gosdn cli init error = %v, wantErr %v", err, tt.wantErr) return } diff --git a/controller/api/auth.go b/controller/api/auth.go index 02d1331d9706ce257182946a2c5b22a1157c3627..3aaee47eafd4f823c4bf2eab0dd16bfb29544d5b 100644 --- a/controller/api/auth.go +++ b/controller/api/auth.go @@ -8,7 +8,7 @@ import ( nbi "code.fbi.h-da.de/danet/gosdn/controller/northbound/client" ) -// Login logs a user in +// Login logs a user in. func Login(ctx context.Context, addr, username, pwd string) (*apb.LoginResponse, error) { authClient, err := nbi.AuthClient(addr, dialOptions...) if err != nil { @@ -23,7 +23,7 @@ func Login(ctx context.Context, addr, username, pwd string) (*apb.LoginResponse, return authClient.Login(ctx, r) } -// Logout logs a user out +// Logout logs a user out. func Logout(ctx context.Context, addr, username string) (*apb.LogoutResponse, error) { authClient, err := nbi.AuthClient(addr, dialOptions...) if err != nil { diff --git a/controller/api/change.go b/controller/api/change.go index 57b82608554a78c6dd892557b300df9cdd6ee4c1..2d5ad6e2ef8a024ed05d018fbb408c5d8599ded9 100644 --- a/controller/api/change.go +++ b/controller/api/change.go @@ -9,7 +9,7 @@ import ( nbi "code.fbi.h-da.de/danet/gosdn/controller/northbound/client" ) -// GetChanges requests all pending and unconfirmed changes from the controller +// GetChanges requests all pending and unconfirmed changes from the controller. func GetChanges(ctx context.Context, addr, pnd string) (*ppb.GetChangeListResponse, error) { client, err := nbi.PndClient(addr, dialOptions...) if err != nil { @@ -22,7 +22,7 @@ func GetChanges(ctx context.Context, addr, pnd string) (*ppb.GetChangeListRespon return client.GetChangeList(ctx, req) } -// GetChange requests one or more changes from the controller +// GetChange requests one or more changes from the controller. func GetChange(ctx context.Context, addr string, pnd string, args ...string) (*ppb.GetChangeResponse, error) { client, err := nbi.PndClient(addr, dialOptions...) if err != nil { @@ -53,7 +53,7 @@ func Commit(ctx context.Context, addr, pnd string, cuids ...string) (*ppb.SetCha } // Confirm sends a Confirm request for one or multiple changes to the -// controller +// controller. func Confirm(ctx context.Context, addr, pnd string, cuids ...string) (*ppb.SetChangeListResponse, error) { changes := make([]*ppb.SetChange, len(cuids)) for i, arg := range cuids { @@ -65,7 +65,7 @@ func Confirm(ctx context.Context, addr, pnd string, cuids ...string) (*ppb.SetCh return CommitConfirm(ctx, addr, pnd, changes) } -// CommitConfirm confirms a commit +// CommitConfirm confirms a commit. func CommitConfirm(ctx context.Context, addr, pnd string, changes []*ppb.SetChange) (*ppb.SetChangeListResponse, error) { client, err := nbi.PndClient(addr, dialOptions...) if err != nil { @@ -94,7 +94,7 @@ func ChangeRequest(ctx context.Context, addr, did, pid, path, value string, op p return SendChangeRequest(ctx, addr, pid, req) } -// SendChangeRequest sends a change request +// SendChangeRequest sends a change request. func SendChangeRequest(ctx context.Context, addr, pid string, req *ppb.ChangeRequest) (*ppb.SetPathListResponse, error) { pndClient, err := nbi.PndClient(addr, dialOptions...) if err != nil { diff --git a/controller/api/device.go b/controller/api/device.go index b18ed039621931d87a1cbd1a9beed8edf9a7974a..27db2d3dff64d9b226a225c62db336f843d9be7c 100644 --- a/controller/api/device.go +++ b/controller/api/device.go @@ -2,6 +2,7 @@ package api import ( "context" + "errors" "io" "time" @@ -71,7 +72,7 @@ func GetDevice(ctx context.Context, addr, pid string, did string) (*ppb.GetOndRe return pndClient.GetOnd(ctx, req) } -// GetSbiSchemaTree gets the sbi tree for a sbi +// GetSbiSchemaTree gets the sbi tree for a sbi. func GetSbiSchemaTree(ctx context.Context, addr string, pid, sid uuid.UUID) (map[string]*yang.Entry, error) { sbiClient, err := nbi.SbiClient(addr, dialOptions...) if err != nil { @@ -96,7 +97,7 @@ func GetSbiSchemaTree(ctx context.Context, addr string, pid, sid uuid.UUID) (map for { payload, err := sClient.Recv() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { break } log.Error(err) @@ -135,7 +136,7 @@ func GetFlattenedDevices(ctx context.Context, addr, pid string) (*ppb.GetFlatten return pndClient.GetFlattenedOndList(ctx, req) } -// GetPath requests a specific path +// GetPath requests a specific path. func GetPath(ctx context.Context, addr, pid, did, path string) (*ppb.GetPathResponse, error) { pndClient, err := nbi.PndClient(addr, dialOptions...) if err != nil { @@ -152,7 +153,7 @@ func GetPath(ctx context.Context, addr, pid, did, path string) (*ppb.GetPathResp return pndClient.GetPath(ctx, req) } -// SubscribePath subscribes to paths on a device +// SubscribePath subscribes to paths on a device. func SubscribePath(ctx context.Context, addr, pid, did string, slist *ppb.SubscriptionList) (ppb.PndService_SubscribePathClient, error) { log.Println("subscribePath called") pndClient, err := nbi.PndClient(addr, dialOptions...) @@ -170,7 +171,7 @@ func SubscribePath(ctx context.Context, addr, pid, did string, slist *ppb.Subscr return pndClient.SubscribePath(ctx, req) } -// DeleteDevice deletes a device +// DeleteDevice deletes a device. func DeleteDevice(ctx context.Context, addr, pid, did string) (*ppb.DeleteOndResponse, error) { pndClient, err := nbi.PndClient(addr, dialOptions...) if err != nil { diff --git a/controller/api/grpc.go b/controller/api/grpc.go index b4927635df7e0a7c081c7b5b0b051ee6e222fac8..f1f9491d60e3e7d011ba6f1c72b99149baebf41c 100644 --- a/controller/api/grpc.go +++ b/controller/api/grpc.go @@ -38,7 +38,7 @@ func Init(ctx context.Context, addr string) error { return viper.WriteConfig() } -// GetIds requests all UUID information from the controller +// GetIds requests all UUID information from the controller. func GetIds(ctx context.Context, addr string) ([]*ppb.PrincipalNetworkDomain, error) { resp, err := GetAllCore(ctx, addr) if err != nil { @@ -47,7 +47,7 @@ func GetIds(ctx context.Context, addr string) ([]*ppb.PrincipalNetworkDomain, er return resp.Pnd, nil } -// GetAllCore requests all PNDs +// GetAllCore requests all PNDs. func GetAllCore(ctx context.Context, addr string) (*pb.GetPndListResponse, error) { coreClient, err := nbi.CoreClient(addr, dialOptions...) if err != nil { diff --git a/controller/api/initialise_test.go b/controller/api/initialise_test.go index a2df244b30185ec7d0c74a37b63cfaaf4412ba42..c70086f10e7db630e5f2f1f77eba2704c62fa50e 100644 --- a/controller/api/initialise_test.go +++ b/controller/api/initialise_test.go @@ -93,7 +93,9 @@ func bootstrapUnitTest() { sbiStore = nucleus.NewMemorySbiStore() userService = rbacImpl.NewUserService(rbacImpl.NewMemoryUserStore(), eventService) roleService = rbacImpl.NewRoleService(rbacImpl.NewMemoryRoleStore(), eventService) - clearAndCreateAuthTestSetup() + if err := clearAndCreateAuthTestSetup(); err != nil { + log.Fatal(err) + } previousHostname := "previousHostname" intendedHostname := "intendedHostname" diff --git a/controller/api/pnd.go b/controller/api/pnd.go index a6c9eb0ac0e9c3eb57d88db980c702fd9ebf7b9e..0aaa0a8a1f51b8ad2955a55371ef3a8f1695d75a 100644 --- a/controller/api/pnd.go +++ b/controller/api/pnd.go @@ -10,7 +10,7 @@ import ( ) // AddPnd takes a name, description and SBI UUID to create a new -// PrincipalNetworkDomain on the controller +// PrincipalNetworkDomain on the controller. func AddPnd(ctx context.Context, addr, name, description, sbi string) (*pb.CreatePndListResponse, error) { coreClient, err := nbi.CoreClient(addr, dialOptions...) if err != nil { diff --git a/controller/api/role.go b/controller/api/role.go index cef73197238fa77d13a81d9a561a9ea3ea20ee2b..2f7d517ffd550e8cbc13eb0e693a666ebeac1906 100644 --- a/controller/api/role.go +++ b/controller/api/role.go @@ -9,7 +9,7 @@ import ( "github.com/google/uuid" ) -// CreateRoles creates roles with provided data +// CreateRoles creates roles with provided data. func CreateRoles(ctx context.Context, addr string, roles []*apb.Role) (*apb.CreateRolesResponse, error) { roleClient, err := nbi.RoleClient(addr, dialOptions...) if err != nil { @@ -24,7 +24,7 @@ func CreateRoles(ctx context.Context, addr string, roles []*apb.Role) (*apb.Crea return roleClient.CreateRoles(ctx, r) } -// GetRole returns one requested role found by name +// GetRole returns one requested role found by name. func GetRole(ctx context.Context, addr, name string, uuid uuid.UUID) (*apb.GetRoleResponse, error) { roleClient, err := nbi.RoleClient(addr, dialOptions...) if err != nil { @@ -40,7 +40,7 @@ func GetRole(ctx context.Context, addr, name string, uuid uuid.UUID) (*apb.GetRo return roleClient.GetRole(ctx, r) } -// GetRoles returns all available roles +// GetRoles returns all available roles. func GetRoles(ctx context.Context, addr string) (*apb.GetRolesResponse, error) { roleClient, err := nbi.RoleClient(addr, dialOptions...) if err != nil { @@ -54,7 +54,7 @@ func GetRoles(ctx context.Context, addr string) (*apb.GetRolesResponse, error) { return roleClient.GetRoles(ctx, r) } -// UpdateRoles updates the procided roles +// UpdateRoles updates the procided roles. func UpdateRoles(ctx context.Context, addr string, roles []*apb.Role) (*apb.UpdateRolesResponse, error) { roleClient, err := nbi.RoleClient(addr, dialOptions...) if err != nil { @@ -69,7 +69,7 @@ func UpdateRoles(ctx context.Context, addr string, roles []*apb.Role) (*apb.Upda return roleClient.UpdateRoles(ctx, r) } -// DeletePermissionForRole deletes the provided permissions from one role found by name +// DeletePermissionForRole deletes the provided permissions from one role found by name. func DeletePermissionForRole(ctx context.Context, addr, name string, permissionsToDelete []string) (*apb.DeletePermissionsForRoleResponse, error) { roleClient, err := nbi.RoleClient(addr, dialOptions...) if err != nil { @@ -85,7 +85,7 @@ func DeletePermissionForRole(ctx context.Context, addr, name string, permissions return roleClient.DeletePermissionsForRole(ctx, r) } -// DeleteRoles deletes all the provided roles with their permissions +// DeleteRoles deletes all the provided roles with their permissions. func DeleteRoles(ctx context.Context, addr string, roleName []string) (*apb.DeleteRolesResponse, error) { roleClient, err := nbi.RoleClient(addr, dialOptions...) if err != nil { diff --git a/controller/api/role_test.go b/controller/api/role_test.go index 785ae3128e3c36d770bd67208492d27cb8aaccb4..64fb7caef9c67d071fde3109a616895c6fc7c1c5 100644 --- a/controller/api/role_test.go +++ b/controller/api/role_test.go @@ -7,6 +7,7 @@ import ( apb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/rbac" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) func TestCreateRoles(t *testing.T) { @@ -264,7 +265,10 @@ func TestUpdateRoles(t *testing.T) { } func TestDeletePermissionForRole(t *testing.T) { - clearAndCreateAuthTestSetup() + if err := clearAndCreateAuthTestSetup(); err != nil { + log.Error(err) + t.Fail() + } type args struct { ctx context.Context @@ -365,7 +369,10 @@ func TestDeleteRoles(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - clearAndCreateAuthTestSetup() + if err := clearAndCreateAuthTestSetup(); err != nil { + log.Error(err) + t.Fail() + } got, err := DeleteRoles(tt.args.ctx, tt.args.addr, tt.args.roleName) if (err != nil) != tt.wantErr { diff --git a/controller/api/user.go b/controller/api/user.go index f5f49ea4d6fc44a8dea527cc72db2556163b03d5..484ebe3b789ec92ce9031b257271706010f31354 100644 --- a/controller/api/user.go +++ b/controller/api/user.go @@ -10,7 +10,7 @@ import ( "github.com/google/uuid" ) -// CreateUsers creates users with provided data +// CreateUsers creates users with provided data. func CreateUsers(ctx context.Context, addr string, users []*apb.User) (*apb.CreateUsersResponse, error) { userClient, err := nbi.UserClient(addr, dialOptions...) if err != nil { @@ -25,7 +25,7 @@ func CreateUsers(ctx context.Context, addr string, users []*apb.User) (*apb.Crea return userClient.CreateUsers(ctx, r) } -//GetUser returns one requested user found by name +//GetUser returns one requested user found by name. func GetUser(ctx context.Context, addr, name string, uuid uuid.UUID) (*apb.GetUserResponse, error) { userClient, err := nbi.UserClient(addr, dialOptions...) if err != nil { @@ -41,7 +41,7 @@ func GetUser(ctx context.Context, addr, name string, uuid uuid.UUID) (*apb.GetUs return userClient.GetUser(ctx, r) } -// GetAllUsers return all the available users +// GetAllUsers return all the available users. func GetAllUsers(ctx context.Context, addr string) (*apb.GetUsersResponse, error) { userClient, err := nbi.UserClient(addr, dialOptions...) if err != nil { @@ -55,7 +55,7 @@ func GetAllUsers(ctx context.Context, addr string) (*apb.GetUsersResponse, error return userClient.GetUsers(ctx, r) } -// UpdateUsers updates all provided users +// UpdateUsers updates all provided users. func UpdateUsers(ctx context.Context, addr string, users []*apb.User) (*apb.UpdateUsersResponse, error) { userClient, err := nbi.UserClient(addr, dialOptions...) if err != nil { @@ -70,7 +70,7 @@ func UpdateUsers(ctx context.Context, addr string, users []*apb.User) (*apb.Upda return userClient.UpdateUsers(ctx, r) } -// DeleteUsers deletes all provided users +// DeleteUsers deletes all provided users. func DeleteUsers(ctx context.Context, addr string, userNames []string) (*apb.DeleteUsersResponse, error) { userClient, err := nbi.UserClient(addr, dialOptions...) if err != nil { diff --git a/controller/cmd/root.go b/controller/cmd/root.go index 6149c2aff7eac3b269bfe8679ab733b111b0d4bc..7276344020865de5d146d98f63f781005cbe905d 100644 --- a/controller/cmd/root.go +++ b/controller/cmd/root.go @@ -52,7 +52,7 @@ var csbiOrchestrator string var pluginFolder string var security string -// rootCmd represents the base command when called without any subcommands +// rootCmd represents the base command when called without any subcommands. var rootCmd = &cobra.Command{ Use: "gosdn", Short: "starts the gosdn controller", diff --git a/controller/config/config.go b/controller/config/config.go index 55161e10c7a598d4aca9ba4ac755ac7ad8f3c4c4..a5b70bc3cd64de6866686752d3fbf2d2d9d66200 100644 --- a/controller/config/config.go +++ b/controller/config/config.go @@ -23,7 +23,7 @@ const ( jwtSecretKey = "jwtSecret" gNMISubscriptionsFilePathKey = "gNMISubscriptionsPath" - // RabbitMQ Broker + // RabbitMQ Broker. amqpPrefixKey = "amqpPrefix" amqpUserKey = "amqpUser" amqpPasswordKey = "amqpPassword" @@ -31,52 +31,52 @@ const ( amqpPortKey = "amqpPort" ) -// BasePndUUID is an uuid for the base PND +// BasePndUUID is an uuid for the base PND. var BasePndUUID uuid.UUID -// BaseSouthBoundType is the type of the base SBI +// BaseSouthBoundType is the type of the base SBI. var BaseSouthBoundType int32 -// BaseSouthBoundUUID is an uuid for the base SBI +// BaseSouthBoundUUID is an uuid for the base SBI. var BaseSouthBoundUUID uuid.UUID -// ChangeTimeout is the default timeout for a change +// ChangeTimeout is the default timeout for a change. var ChangeTimeout time.Duration -// LogLevel ist the default log level +// LogLevel ist the default log level. var LogLevel logrus.Level -// DatabaseConnection holds the credentials and address of the used database +// DatabaseConnection holds the credentials and address of the used database. var DatabaseConnection string -// FilesystemPathToStores determines in which folder the stores should be saved +// FilesystemPathToStores determines in which folder the stores should be saved. var FilesystemPathToStores = "stores_testing" -// JWTDuration determines how long a jwt is valid +// JWTDuration determines how long a jwt is valid. var JWTDuration time.Duration -// JWTSecret determines the scret that is used to sign tokens +// JWTSecret determines the scret that is used to sign tokens. var JWTSecret string -// AMQPPrefix is the amqp prefix +// AMQPPrefix is the amqp prefix. var AMQPPrefix string -// AMQPUser is the amqp user +// AMQPUser is the amqp user. var AMQPUser string -// AMQPPassword is the amqp user password +// AMQPPassword is the amqp user password. var AMQPPassword string -// AMQPHost is the amqp host +// AMQPHost is the amqp host. var AMQPHost string -// AMQPPort is the amqp port +// AMQPPort is the amqp port. var AMQPPort string -// GNMISubscriptionsFilePath is the path to the file used for automated subscriptions +// GNMISubscriptionsFilePath is the path to the file used for automated subscriptions. var GNMISubscriptionsFilePath string -// Init gets called on module import +// Init gets called on module import. func Init() { err := InitializeConfig() if err != nil { @@ -84,7 +84,7 @@ func Init() { } } -// InitializeConfig loads the configuration +// InitializeConfig loads the configuration. func InitializeConfig() error { var err error @@ -122,7 +122,7 @@ func InitializeConfig() error { FilesystemPathToStores = "stores" } - JWTDuration, err = getDurationFromViper(jwtDurationKey, time.Hour) + JWTDuration, err = getDurationFromViper(jwtDurationKey, "h") if err != nil { JWTDuration = defaultJWTDuration } @@ -192,14 +192,15 @@ func setLogLevel() { } } -func getDurationFromViper(viperKey string, unit time.Duration) (time.Duration, error) { - duration := viper.GetDuration(viperKey) +func getDurationFromViper(viperKey, unit string) (time.Duration, error) { + durationString := viper.GetString(viperKey) - if duration > 0 { - return duration * unit, nil + duration, err := time.ParseDuration(durationString + unit) + if err != nil { + return 0, err } - return 0, viper.ConfigParseError{} + return duration, nil } func loadAMQPConfig() { diff --git a/controller/config/environment.go b/controller/config/environment.go index 9e916e7c1c6d1f6c6e69b5590d31555b13b6fdb4..e2d2285aec38be482a338f7866fa96792790ca54 100644 --- a/controller/config/environment.go +++ b/controller/config/environment.go @@ -9,11 +9,11 @@ import ( type Environment int64 const ( - // Development is used for local development + // Development is used for local development. Development Environment = iota - // Production is used for production deployments + // Production is used for production deployments. Production - // Testing is used for tests + // Testing is used for tests. Testing ) diff --git a/controller/config/gnmiSubscriptionConfig.go b/controller/config/gnmiSubscriptionConfig.go index 53e1b32571f9793cfe2596fe018a04ca45357351..dc8ede429fd7e9579d92e9b6e28efb8a620d98b4 100644 --- a/controller/config/gnmiSubscriptionConfig.go +++ b/controller/config/gnmiSubscriptionConfig.go @@ -15,7 +15,7 @@ const ( var gnmiSubscriptionPaths [][]string // ReadGnmiSubscriptionPaths reads the paths the watcher should subscribe to provided in a file. -func ReadGnmiSubscriptionPaths() error { +func ReadGnmiSubscriptionPaths() (err error) { var filePath string if GNMISubscriptionsFilePath != "" { @@ -34,7 +34,12 @@ func ReadGnmiSubscriptionPaths() error { return err } - defer f.Close() + defer func() { + if ferr := f.Close(); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() scanner := bufio.NewScanner(f) diff --git a/controller/controller.go b/controller/controller.go index a79d4cea9bdbcd6480636b9abf32bbd429007135..822c8439a8c0732deab6b6595e02de9561d13844 100644 --- a/controller/controller.go +++ b/controller/controller.go @@ -47,7 +47,7 @@ import ( var coreLock sync.RWMutex var coreOnce sync.Once -// Core is the representation of the controller's core +// Core is the representation of the controller's core. type Core struct { pndStore networkdomain.PndStore userService rbac.UserService @@ -67,7 +67,7 @@ type Core struct { var c *Core -// initialize does start-up housekeeping like reading controller config files +// initialize does start-up housekeeping like reading controller config files. func initialize() error { err := config.InitializeConfig() if err != nil { @@ -187,7 +187,7 @@ func startGrpc() error { return nil } -// createPrincipalNetworkDomain initializes the controller with an initial PND +// createPrincipalNetworkDomain initializes the controller with an initial PND. func createPrincipalNetworkDomain() error { basePnd, err := c.pndStore.Get(store.Query{ID: config.BasePndUUID}) if err != nil { @@ -295,7 +295,7 @@ func ensureDefaultUserExists() error { return nil } -// Run calls initialize to start the controller +// Run calls initialize to start the controller. func Run(ctx context.Context) error { var initError error coreOnce.Do(func() { diff --git a/controller/initialise_test.go b/controller/initialise_test.go index b5e8b80a39748a03f029fcaed388c7bd6b71957e..d76a591b9e9b67bf0c809d7ea96c7b3ca3613720 100644 --- a/controller/initialise_test.go +++ b/controller/initialise_test.go @@ -12,7 +12,7 @@ import ( const apiEndpoint = "http://localhost:8080" -// UUIDs for test cases +// UUIDs for test cases. var mdid uuid.UUID var defaultPndID uuid.UUID var cuid uuid.UUID diff --git a/controller/interfaces/change/change.go b/controller/interfaces/change/change.go index 40e8cc90ecbba6985a92989ecfeb81f09f265597..72dd99905a2aeabe15bad22649ef3ca53e3f3fe3 100644 --- a/controller/interfaces/change/change.go +++ b/controller/interfaces/change/change.go @@ -11,7 +11,7 @@ import ( // Change is an intended change to an OND. It is unique and immutable. // It has a cuid, a timestamp, and holds both the previous and the new // state. It keeps track if the state is committed and confirmed. A callback -// exists to acess the proper transport for the changed OND +// exists to acess the proper transport for the changed OND. type Change interface { ID() uuid.UUID Commit() error diff --git a/controller/interfaces/device/device.go b/controller/interfaces/device/device.go index 8de21b4c63daafc50debb83b05135c758fda1855..4becb471c87ff3a4be43e3c63582209b8a4225c7 100644 --- a/controller/interfaces/device/device.go +++ b/controller/interfaces/device/device.go @@ -11,7 +11,7 @@ import ( ) // Device represents an Orchestrated Network Device (OND) which is managed by -// nucleus +// nucleus. type Device interface { ID() uuid.UUID GetModel() ygot.GoStruct @@ -24,7 +24,7 @@ type Device interface { GetModelAsString() (string, error) } -// Details contains details of a device used by the cSBI mechanism +// Details contains details of a device used by the cSBI mechanism. type Details struct { ID string Address string @@ -62,7 +62,7 @@ func (ld *LoadedDevice) SetConvertFunction(cf func(LoadedDevice) (Device, error) } // ConvertToDevice calls the LoadedDevice's convert function and converts the -// LoadedDevice into a Device +// LoadedDevice into a Device. func (ld LoadedDevice) ConvertToDevice() (Device, error) { return ld.convertFunc(ld) } diff --git a/controller/interfaces/event/service.go b/controller/interfaces/event/service.go index 49cf8f6bc09711ecbfbd382b703a156bed675c6c..73f3c97d2dc3a30e45804671fc6bbc827017d0e5 100644 --- a/controller/interfaces/event/service.go +++ b/controller/interfaces/event/service.go @@ -2,7 +2,7 @@ package event import "code.fbi.h-da.de/danet/gosdn/controller/event" -// Service is the event service +// Service is the event service. type Service interface { PublishEvent(topic string, event event.Event) error CloseConnection() diff --git a/controller/interfaces/rbac/rbacService.go b/controller/interfaces/rbac/rbacService.go index 74c938ac2dda460305c04cda61eaf4afa50bacd2..eddfbfce11efd9775a5ca018831997e65ae9d6d9 100644 --- a/controller/interfaces/rbac/rbacService.go +++ b/controller/interfaces/rbac/rbacService.go @@ -13,7 +13,7 @@ type UserService interface { GetAll() ([]User, error) } -// LoadedUser represents a User that was loaded +// LoadedUser represents a User that was loaded. type LoadedUser struct { ID string `json:"_id" bson:"_id"` UserName string `json:"username"` @@ -32,7 +32,7 @@ type RoleService interface { GetAll() ([]Role, error) } -// LoadedRole represents a Role that was loaded +// LoadedRole represents a Role that was loaded. type LoadedRole struct { ID string `json:"_id" bson:"_id"` RoleName string `json:"rolename"` diff --git a/controller/interfaces/rbac/role.go b/controller/interfaces/rbac/role.go index 41ab642f9ba4f0e781307e6f0888503a1280dd22..d08884215ccaee7231554df76ed946298c65eea8 100644 --- a/controller/interfaces/rbac/role.go +++ b/controller/interfaces/rbac/role.go @@ -2,7 +2,7 @@ package rbac import "github.com/google/uuid" -// Role represents a role with permissions +// Role represents a role with permissions. type Role interface { ID() uuid.UUID Name() string diff --git a/controller/interfaces/rbac/user.go b/controller/interfaces/rbac/user.go index 37b4f9021d15d9d7f3f0ff0b22860219e861f1b6..0cec5417b5bb991ce448c53bee34461742043d30 100644 --- a/controller/interfaces/rbac/user.go +++ b/controller/interfaces/rbac/user.go @@ -2,7 +2,7 @@ package rbac import "github.com/google/uuid" -// User represents an User which is managed by rbac +// User represents an User which is managed by rbac. type User interface { ID() uuid.UUID Name() string diff --git a/controller/interfaces/southbound/sbi.go b/controller/interfaces/southbound/sbi.go index 3c6911265d93fa72fdf5bdab242c0ff2e8590678..2667d5051f960ead7e1b17005c931b9557ad9756 100644 --- a/controller/interfaces/southbound/sbi.go +++ b/controller/interfaces/southbound/sbi.go @@ -11,7 +11,7 @@ import ( ) // SouthboundInterface provides an -// interface for SBI implementations +// interface for SBI implementations. type SouthboundInterface interface { // nolint // SetNode injects SBI specific model // representation to the transport. diff --git a/controller/interfaces/transport/transport.go b/controller/interfaces/transport/transport.go index 2822639fad82fee21a03ecde9e50ed147062694c..2be9f287f0aeb5b0a97fc26caf7a35261727f571 100644 --- a/controller/interfaces/transport/transport.go +++ b/controller/interfaces/transport/transport.go @@ -10,7 +10,7 @@ import ( ) // Transport provides an interface for Transport implementations -// like RESTCONF or gnmi +// like RESTCONF or gnmi. type Transport interface { Get(ctx context.Context, params ...string) (interface{}, error) Set(ctx context.Context, payload change.Payload, path string, schema *ytypes.Schema) error @@ -24,13 +24,13 @@ type Transport interface { } type ( - // HandleSubscribeResponse is the callback function to handle subcription responses + // HandleSubscribeResponse is the callback function to handle subcription responses. HandleSubscribeResponse func(*gpb.SubscribeResponse, *SubscriptionInformation) ) // SubscriptionInformation contains additional information used for internal subscriptions // for distinguishing from which device the information is from, to stop subscriptions and -// error handling +// error handling. type SubscriptionInformation struct { PndID string DeviceID string diff --git a/controller/northbound/client/core.go b/controller/northbound/client/core.go index eccdb2a6a37f926c78c51c17eae8e1f3267e72f0..1f2e18b17f8268b468ababd90b1d09fc8a39c818 100644 --- a/controller/northbound/client/core.go +++ b/controller/northbound/client/core.go @@ -7,7 +7,7 @@ import ( // CoreClient returns a client for the gRPC Core service. It takes // the address of the gRPC endpoint and optional grpc.DialOption -// as argument +// as argument. func CoreClient(addr string, opts ...grpc.DialOption) (pb.CoreServiceClient, error) { conn, err := grpc.Dial(addr, opts...) if err != nil { diff --git a/controller/northbound/client/pnd.go b/controller/northbound/client/pnd.go index 12a513ad01fa1b575f78e38411ef148565eb6c6f..c392566ea18f750a11c0d17df78a54872dc168c9 100644 --- a/controller/northbound/client/pnd.go +++ b/controller/northbound/client/pnd.go @@ -7,7 +7,7 @@ import ( // PndClient returns a client for the gRPC PND service. It takes // the address of the gRPC endpoint and optional grpc.DialOption -// as argument +// as argument. func PndClient(addr string, opts ...grpc.DialOption) (ppb.PndServiceClient, error) { conn, err := grpc.Dial(addr, opts...) if err != nil { diff --git a/controller/northbound/client/rbac.go b/controller/northbound/client/rbac.go index d6b6c1eaa039663c0b2497d4c9efe73b52740d7f..c5f9a97007367435620a00a19160b7f837359df9 100644 --- a/controller/northbound/client/rbac.go +++ b/controller/northbound/client/rbac.go @@ -7,7 +7,7 @@ import ( // AuthClient returns a client for the gRPC Auth service. It takes // the address of the gRPC endpoint and optional grpc.DialOption -// as argument +// as argument. func AuthClient(addr string, opts ...grpc.DialOption) (apb.AuthServiceClient, error) { conn, err := grpc.Dial(addr, opts...) if err != nil { @@ -18,7 +18,7 @@ func AuthClient(addr string, opts ...grpc.DialOption) (apb.AuthServiceClient, er // UserClient returns a client for the gRPC User service. It takes // the address of the gRPC endpoint and optional grpc.DialOption -// as argument +// as argument. func UserClient(addr string, opts ...grpc.DialOption) (apb.UserServiceClient, error) { conn, err := grpc.Dial(addr, opts...) if err != nil { @@ -29,7 +29,7 @@ func UserClient(addr string, opts ...grpc.DialOption) (apb.UserServiceClient, er // RoleClient returns a client for the gRPC Role service. It takes // the address of the gRPC endpoint and optional grpc.DialOption -// as argument +// as argument. func RoleClient(addr string, opts ...grpc.DialOption) (apb.RoleServiceClient, error) { conn, err := grpc.Dial(addr, opts...) if err != nil { diff --git a/controller/northbound/client/sbi.go b/controller/northbound/client/sbi.go index 43ebcb3fc0c11a23cd46472ddac0bd68a312e5c5..c89d58006e4dd56258644b24d6081ef55c610d55 100644 --- a/controller/northbound/client/sbi.go +++ b/controller/northbound/client/sbi.go @@ -7,7 +7,7 @@ import ( // SbiClient returns a client for the gRPC SBI service. It takes // the address of the gRPC endpoint and optional grpc.DialOption -// as argument +// as argument. func SbiClient(addr string, opts ...grpc.DialOption) (spb.SbiServiceClient, error) { conn, err := grpc.Dial(addr, opts...) if err != nil { diff --git a/controller/northbound/server/auth.go b/controller/northbound/server/auth.go index 18eccd0c438b54eeb1d9866d8eae6dd1b9655b3c..e7459f7b5ddee7e9b051ff613938f32e4e8b0d50 100644 --- a/controller/northbound/server/auth.go +++ b/controller/northbound/server/auth.go @@ -32,7 +32,7 @@ func NewAuthServer(jwtManager *rbac.JWTManager, userService rbacInterfaces.UserS } } -// Login logs a user in +// Login logs a user in. func (s AuthServer) Login(ctx context.Context, request *apb.LoginRequest) (*apb.LoginResponse, error) { labels := prometheus.Labels{"service": "auth", "rpc": "post"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -74,7 +74,7 @@ func (s AuthServer) Login(ctx context.Context, request *apb.LoginRequest) (*apb. }, nil } -// Logout logs a user out +// Logout logs a user out. func (s AuthServer) Logout(ctx context.Context, request *apb.LogoutRequest) (*apb.LogoutResponse, error) { labels := prometheus.Labels{"service": "auth", "rpc": "post"} start := metrics.StartHook(labels, grpcRequestsTotal) diff --git a/controller/northbound/server/auth_interceptor.go b/controller/northbound/server/auth_interceptor.go index 11338596bbb311850260f1c610809ed1f5f895cc..30ffa2ea982be33282ab3db1c86cfe2f6e22d06e 100644 --- a/controller/northbound/server/auth_interceptor.go +++ b/controller/northbound/server/auth_interceptor.go @@ -16,7 +16,7 @@ import ( "google.golang.org/grpc/status" ) -// AuthInterceptor provides an AuthInterceptor +// AuthInterceptor provides an AuthInterceptor. type AuthInterceptor struct { jwtManager *rbac.JWTManager userService rbacInterfaces.UserService @@ -36,7 +36,7 @@ func NewAuthInterceptor( } } -// Unary returns a unary interceptor function to authenticate and authorize unary RPC calls +// Unary returns a unary interceptor function to authenticate and authorize unary RPC calls. func (auth *AuthInterceptor) Unary() grpc.UnaryServerInterceptor { return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { switch req.(type) { @@ -57,7 +57,7 @@ func (auth *AuthInterceptor) Unary() grpc.UnaryServerInterceptor { } } -// Stream returns a server interceptor function to authorize stream RPC calls +// Stream returns a server interceptor function to authorize stream RPC calls. func (auth *AuthInterceptor) Stream() grpc.StreamServerInterceptor { return func( srv interface{}, diff --git a/controller/northbound/server/auth_interceptor_test.go b/controller/northbound/server/auth_interceptor_test.go index 045774ba57b49e928c149d3fe6227a683c035a68..023f9e0e48f0083f7a73964eb559453b88ff0b61 100644 --- a/controller/northbound/server/auth_interceptor_test.go +++ b/controller/northbound/server/auth_interceptor_test.go @@ -41,7 +41,9 @@ func getTestAuthInterceptorServer(t *testing.T) (*AuthInterceptor, *UserServer, r := NewRoleServer(jwtManager, roleService) sbiServer := NewSbiServer(pndStore) - clearAndCreateAuthTestSetup(userService, roleService) + if err := clearAndCreateAuthTestSetup(userService, roleService); err != nil { + t.Fatal(err) + } return s, u, r, sbiServer } @@ -88,7 +90,11 @@ func TestAuthInterceptor_Unary(t *testing.T) { if err != nil { t.Fatal(err) } - defer conn.Close() + defer func() { + if err := conn.Close(); err != nil { + log.Fatal(err) + } + }() client := apb.NewUserServiceClient(conn) @@ -175,7 +181,11 @@ func TestAuthInterceptor_Stream(t *testing.T) { if err != nil { t.Fatal(err) } - defer conn.Close() + defer func() { + if err := conn.Close(); err != nil { + log.Fatal(err) + } + }() client := spb.NewSbiServiceClient(conn) diff --git a/controller/northbound/server/core.go b/controller/northbound/server/core.go index 451be03548f3d559e850c256e15e9b23c09d49c4..388b3ad8f94ddd4e2ed478f4d419aa36655b5f49 100644 --- a/controller/northbound/server/core.go +++ b/controller/northbound/server/core.go @@ -14,7 +14,7 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -// CoreServer represents a core server +// CoreServer represents a core server. type CoreServer struct { pb.UnimplementedCoreServiceServer pndStore networkdomain.PndStore @@ -27,7 +27,7 @@ func NewCoreServer(pndStore networkdomain.PndStore) *CoreServer { } } -// GetPnd returns a existing pnd +// GetPnd returns a existing pnd. func (s CoreServer) GetPnd(ctx context.Context, request *pb.GetPndRequest) (*pb.GetPndResponse, error) { labels := prometheus.Labels{"service": "core", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -55,7 +55,7 @@ func (s CoreServer) GetPnd(ctx context.Context, request *pb.GetPndRequest) (*pb. }, nil } -// GetPndList returns all existing pnds +// GetPndList returns all existing pnds. func (s CoreServer) GetPndList(ctx context.Context, request *pb.GetPndListRequest) (*pb.GetPndListResponse, error) { labels := prometheus.Labels{"service": "core", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -80,7 +80,7 @@ func (s CoreServer) GetPndList(ctx context.Context, request *pb.GetPndListReques }, nil } -// CreatePndList creates a pnd list +// CreatePndList creates a pnd list. func (s CoreServer) CreatePndList(ctx context.Context, request *pb.CreatePndListRequest) (*pb.CreatePndListResponse, error) { labels := prometheus.Labels{"service": "core", "rpc": "set"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -100,7 +100,7 @@ func (s CoreServer) CreatePndList(ctx context.Context, request *pb.CreatePndList }, nil } -// DeletePnd deletes an existing pnd +// DeletePnd deletes an existing pnd. func (s CoreServer) DeletePnd(ctx context.Context, request *pb.DeletePndRequest) (*pb.DeletePndResponse, error) { labels := prometheus.Labels{"service": "core", "rpc": "set"} start := metrics.StartHook(labels, grpcRequestsTotal) diff --git a/controller/northbound/server/csbi.go b/controller/northbound/server/csbi.go index 00a68aea1517bec97371a9dfc7eadcdbfdf14abf..77cb9b7fb0becefcf2bac234c52ab8bc8b2cfe3b 100644 --- a/controller/northbound/server/csbi.go +++ b/controller/northbound/server/csbi.go @@ -19,7 +19,7 @@ import ( "google.golang.org/grpc/status" ) -// CsbiServer represents a csbi server +// CsbiServer represents a csbi server. type CsbiServer struct { cpb.UnimplementedCsbiServiceServer pndStore networkdomain.PndStore @@ -32,7 +32,7 @@ func NewCsbiServer(pndStore networkdomain.PndStore) *CsbiServer { } } -// Hello is used for tests +// Hello is used for tests. func (s CsbiServer) Hello(ctx context.Context, syn *cpb.Syn) (*cpb.Ack, error) { labels := prometheus.Labels{"service": "csbi", "rpc": "hello"} start := metrics.StartHook(labels, grpcRequestsTotal) diff --git a/controller/northbound/server/nbi.go b/controller/northbound/server/nbi.go index e174165920a7cca18c15f3709d631f92b71c97a3..211b30bcfba4a2c4a439e7f8008f101ab4bf688f 100644 --- a/controller/northbound/server/nbi.go +++ b/controller/northbound/server/nbi.go @@ -29,7 +29,7 @@ type NorthboundInterface struct { Device *DeviceServer } -// NewNBI receives a PndStore and returns a new gRPC *NorthboundInterface +// NewNBI receives a PndStore and returns a new gRPC *NorthboundInterface. func NewNBI( pnds networkdomain.PndStore, users rbacInterfaces.UserService, diff --git a/controller/northbound/server/pnd.go b/controller/northbound/server/pnd.go index c0dc0367df4bfbc86129db3ec91dd39e63c0a104..3805364c171aecda96454fa7e62bfb300c8506a1 100644 --- a/controller/northbound/server/pnd.go +++ b/controller/northbound/server/pnd.go @@ -23,7 +23,7 @@ import ( "google.golang.org/grpc/status" ) -// PndServer implements a pnd server +// PndServer implements a pnd server. type PndServer struct { ppb.UnimplementedPndServiceServer pndStore networkdomain.PndStore @@ -36,7 +36,7 @@ func NewPndServer(pndStore networkdomain.PndStore) *PndServer { } } -// GetOnd gets a specific ond +// GetOnd gets a specific ond. func (p PndServer) GetOnd(ctx context.Context, request *ppb.GetOndRequest) (*ppb.GetOndResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -75,7 +75,7 @@ func (p PndServer) GetOnd(ctx context.Context, request *ppb.GetOndRequest) (*ppb }, nil } -// GetOndList returns a list of existing onds +// GetOndList returns a list of existing onds. func (p PndServer) GetOndList(ctx context.Context, request *ppb.GetOndListRequest) (*ppb.GetOndListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -116,7 +116,7 @@ func (p PndServer) GetOndList(ctx context.Context, request *ppb.GetOndListReques }, nil } -// GetFlattenedOndList returns a list of existing onds +// GetFlattenedOndList returns a list of existing onds. func (p PndServer) GetFlattenedOndList(ctx context.Context, request *ppb.GetOndListRequest) (*ppb.GetFlattenedOndListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -217,7 +217,7 @@ func genGnmiNotification(path *gnmi.Path, val any) (*gnmi.Notification, error) { }, nil } -// GetSbi gets a specific sbi +// GetSbi gets a specific sbi. func (p PndServer) GetSbi(ctx context.Context, request *ppb.GetSbiRequest) (*ppb.GetSbiResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -257,7 +257,7 @@ func (p PndServer) GetSbi(ctx context.Context, request *ppb.GetSbiRequest) (*ppb }, nil } -// GetSbiList gets all existing sbis +// GetSbiList gets all existing sbis. func (p PndServer) GetSbiList(ctx context.Context, request *ppb.GetSbiListRequest) (*ppb.GetSbiListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -318,7 +318,7 @@ func stringArrayToUUIDs(sid []string) ([]uuid.UUID, error) { return UUIDs, nil } -// GetPath gets a path on a ond +// GetPath gets a path on a ond. func (p PndServer) GetPath(ctx context.Context, request *ppb.GetPathRequest) (*ppb.GetPathResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -371,7 +371,7 @@ func (p PndServer) GetPath(ctx context.Context, request *ppb.GetPathRequest) (*p }, nil } -// GetChange gets a specific change of a ond +// GetChange gets a specific change of a ond. func (p PndServer) GetChange(ctx context.Context, request *ppb.GetChangeRequest) (*ppb.GetChangeResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -402,7 +402,7 @@ func (p PndServer) GetChange(ctx context.Context, request *ppb.GetChangeRequest) }, nil } -// GetChangeList gets all existing changes +// GetChangeList gets all existing changes. func (p PndServer) GetChangeList(ctx context.Context, request *ppb.GetChangeListRequest) (*ppb.GetChangeListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -479,7 +479,7 @@ func fillChanges(pnd networkdomain.NetworkDomain, all bool, cuid ...string) ([]* return changes, nil } -// SetOndList updates the list of onds +// SetOndList updates the list of onds. func (p PndServer) SetOndList(ctx context.Context, request *ppb.SetOndListRequest) (*ppb.SetOndListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "set"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -521,7 +521,7 @@ func (p PndServer) SetOndList(ctx context.Context, request *ppb.SetOndListReques }, nil } -// SetChangeList sets a list of changes +// SetChangeList sets a list of changes. func (p PndServer) SetChangeList(ctx context.Context, request *ppb.SetChangeListRequest) (*ppb.SetChangeListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "set"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -573,7 +573,7 @@ func (p PndServer) SetChangeList(ctx context.Context, request *ppb.SetChangeList }, nil } -// SetPathList sets a list of paths +// SetPathList sets a list of paths. func (p PndServer) SetPathList(ctx context.Context, request *ppb.SetPathListRequest) (*ppb.SetPathListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "set"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -614,7 +614,7 @@ func (p PndServer) SetPathList(ctx context.Context, request *ppb.SetPathListRequ }, nil } -// SetSbiList sets a list of sbis +// SetSbiList sets a list of sbis. func (p PndServer) SetSbiList(ctx context.Context, request *ppb.SetSbiListRequest) (*ppb.SetSbiListResponse, error) { labels := prometheus.Labels{"service": "pnd", "rpc": "set"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -670,7 +670,7 @@ func filterSbiType(sbiType ppb.SbiType) spb.Type { return spbType } -// DeleteOnd deletes a ond +// DeleteOnd deletes a ond. func (p PndServer) DeleteOnd(ctx context.Context, request *ppb.DeleteOndRequest) (*ppb.DeleteOndResponse, error) { pid, err := uuid.Parse(request.Pid) if err != nil { @@ -698,7 +698,7 @@ func (p PndServer) DeleteOnd(ctx context.Context, request *ppb.DeleteOndRequest) }, nil } -// SubscribePath subscribes to specifc paths of an ond +// SubscribePath subscribes to specifc paths of an ond. func (p PndServer) SubscribePath(request *ppb.SubscribePathRequest, stream ppb.PndService_SubscribePathServer) error { pid, err := uuid.Parse(request.Pid) if err != nil { diff --git a/controller/northbound/server/sbi.go b/controller/northbound/server/sbi.go index a8358dd23f6521bffc7ff7afcaed810363afdd37..32374d5265155ec4ef6c0595c245e367910e8b8b 100644 --- a/controller/northbound/server/sbi.go +++ b/controller/northbound/server/sbi.go @@ -2,6 +2,7 @@ package server import ( "bytes" + "errors" "io" spb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/southbound" @@ -23,7 +24,7 @@ const ( MB ) -// SbiServer represents a sbi server +// SbiServer represents a sbi server. type SbiServer struct { spb.UnimplementedSbiServiceServer pndStore networkdomain.PndStore @@ -36,7 +37,7 @@ func NewSbiServer(pndStore networkdomain.PndStore) *SbiServer { } } -// GetSchema returns the schema of a sbi +// GetSchema returns the schema of a sbi. func (s SbiServer) GetSchema(request *spb.GetSchemaRequest, stream spb.SbiService_GetSchemaServer) error { labels := prometheus.Labels{"service": "pnd", "rpc": "get schema"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -68,7 +69,7 @@ func (s SbiServer) GetSchema(request *spb.GetSchemaRequest, stream spb.SbiServic for { n, err := schema.Read(buffer) if err != nil { - if err != io.EOF { + if errors.Is(err, io.EOF) { log.Println(err) } break diff --git a/controller/northbound/server/test_util_test.go b/controller/northbound/server/test_util_test.go index 1456c90e0271e427922a6dad4ef52fd9ce708937..fea44b5cfb7239515eaa897930355aaa62e30019 100644 --- a/controller/northbound/server/test_util_test.go +++ b/controller/northbound/server/test_util_test.go @@ -161,7 +161,7 @@ func createTestRoles(roleService rbacInterfaces.RoleService) error { } // This is needed as a workaround for a bug where the output of the getUser test falsely was -// that it failed while actually passing. Apparantely, this can happen when loggers write +// that it failed while actually passing. Apparently, this can happen when loggers write // the output of test cases. // Solution found here: https://github.com/gotestyourself/gotestsum/issues/141#issuecomment-686243110 func patchLogger(t *testing.T) { diff --git a/controller/northbound/server/topology.go b/controller/northbound/server/topology.go index e833576bc1dba36ac6b0d02127c0c50c2413dfcd..60e43fa9c1df174e55ad14b7d50235233ebc1afa 100644 --- a/controller/northbound/server/topology.go +++ b/controller/northbound/server/topology.go @@ -37,7 +37,7 @@ func NewTopologyServer( } } -// AddLink adds a new link to the topology +// AddLink adds a new link to the topology. func (t *TopologyServer) AddLink(ctx context.Context, request *topopb.AddLinkRequest) (*topopb.AddLinkResponse, error) { sourceNode, sourcePort, err := t.ensureNodeAndPortExists(request.Link.SourceNode, request.Link.SourcePort) if err != nil { @@ -68,7 +68,7 @@ func (t *TopologyServer) AddLink(ctx context.Context, request *topopb.AddLinkReq }, nil } -// GetTopology returns the current topology in the form of all links +// GetTopology returns the current topology in the form of all links. func (t *TopologyServer) GetTopology(ctx context.Context, request *topopb.GetTopologyRequest) (*topopb.GetTopologyResponse, error) { topo, err := t.topologyService.GetAll() if err != nil { @@ -115,7 +115,7 @@ func (t *TopologyServer) GetTopology(ctx context.Context, request *topopb.GetTop }, nil } -// DeleteLink deletes a link +// DeleteLink deletes a link. func (t *TopologyServer) DeleteLink(ctx context.Context, request *topopb.DeleteLinkRequest) (*topopb.DeleteLinkResponse, error) { linkID, err := uuid.Parse(request.Id) if err != nil { diff --git a/controller/northbound/server/user.go b/controller/northbound/server/user.go index f7a4ce57c18d152b414a0a4787a960146f0522de..3288087fd768ece35405e6f63a82096de102e1a8 100644 --- a/controller/northbound/server/user.go +++ b/controller/northbound/server/user.go @@ -37,7 +37,7 @@ func NewUserServer(jwtManager *rbac.JWTManager, userService rbacInterfaces.UserS } } -// CreateUsers creates new users, can be 1 or more +// CreateUsers creates new users, can be 1 or more. func (u UserServer) CreateUsers(ctx context.Context, request *apb.CreateUsersRequest) (*apb.CreateUsersResponse, error) { labels := prometheus.Labels{"service": "auth", "rpc": "post"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -106,7 +106,7 @@ func (u UserServer) GetUser(ctx context.Context, request *apb.GetUserRequest) (* }, nil } -// GetUsers returns all availbale users +// GetUsers returns all availbale users. func (u UserServer) GetUsers(ctx context.Context, request *apb.GetUsersRequest) (*apb.GetUsersResponse, error) { labels := prometheus.Labels{"service": "auth", "rpc": "get"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -133,7 +133,7 @@ func (u UserServer) GetUsers(ctx context.Context, request *apb.GetUsersRequest) }, nil } -// UpdateUsers updates the user data of one or more users provided in the request +// UpdateUsers updates the user data of one or more users provided in the request. func (u UserServer) UpdateUsers(ctx context.Context, request *apb.UpdateUsersRequest) (*apb.UpdateUsersResponse, error) { labels := prometheus.Labels{"service": "auth", "rpc": "post"} start := metrics.StartHook(labels, grpcRequestsTotal) @@ -166,7 +166,7 @@ func (u UserServer) UpdateUsers(ctx context.Context, request *apb.UpdateUsersReq }, nil } -// DeleteUsers deletes one or more users provided in the request +// DeleteUsers deletes one or more users provided in the request. func (u UserServer) DeleteUsers(ctx context.Context, request *apb.DeleteUsersRequest) (*apb.DeleteUsersResponse, error) { labels := prometheus.Labels{"service": "auth", "rpc": "delete"} start := metrics.StartHook(labels, grpcRequestsTotal) diff --git a/controller/nucleus/change.go b/controller/nucleus/change.go index 935360ca57c77ff157f40168cff8c0c44dfc78da..feae600c8cbfd8b5e5b951e625f1ee1f0d9d3f64 100644 --- a/controller/nucleus/change.go +++ b/controller/nucleus/change.go @@ -56,7 +56,7 @@ func NewChange(device uuid.UUID, currentState ygot.GoStruct, change ygot.GoStruc // Change is an intended change to an OND. It is unique and immutable. // It has a cuid, a timestamp, and holds both the previous and the new // state. It keeps track if the state is committed and confirmed. A callback -// exists to acess the proper transport for the changed OND +// exists to acess the proper transport for the changed OND. type Change struct { cuid uuid.UUID duid uuid.UUID @@ -72,7 +72,7 @@ type Change struct { stateManagerCancel context.CancelFunc } -// ID returns the Change's UUID +// ID returns the Change's UUID. func (c *Change) ID() uuid.UUID { return c.cuid } @@ -81,7 +81,7 @@ func (c *Change) ID() uuid.UUID { // and starts the timeout-timer for the Change. If the timer expires // the change is rolled back. func (c *Change) Commit() error { - //TODO: check if already commited + //TODO: check if already committed c.stateIn <- ppb.ChangeState_CHANGE_STATE_COMMITTED select { case err := <-c.errChan: @@ -103,7 +103,7 @@ func (c *Change) Confirm() error { } } -// Age returns the passed time since the Change was created +// Age returns the passed time since the Change was created. func (c *Change) Age() time.Duration { return time.Since(c.timestamp) } @@ -132,7 +132,7 @@ func stateManager(ctx context.Context, ch *Change, timeout time.Duration) (chan< stateIn := make(chan ppb.ChangeState) stateOut := make(chan ppb.ChangeState) // A Goroutine, which is created while a new Change is initialized acts as - // the reciever for errorChan + // the receiver for errorChan errChan := make(chan error) // create ticker and make it wait for 1 week // workaround for delayed ticker start and ugly housekeeping diff --git a/controller/nucleus/clientConfig.go b/controller/nucleus/clientConfig.go index c88b951fc03fcb5be59a0fad54fa44aab749bbe5..de6be1a9f6ecd93801ba6dd2554f184535ded752 100644 --- a/controller/nucleus/clientConfig.go +++ b/controller/nucleus/clientConfig.go @@ -2,7 +2,7 @@ package nucleus // ClientConfig contains SBI client // configuration parameters -// Deprecated in favor of spf viper +// Deprecated in favor of spf viper. type ClientConfig struct { Identifier string `toml:"identifier"` Endpoint string `toml:"endpoint"` diff --git a/controller/nucleus/database/mongo-connection.go b/controller/nucleus/database/mongo-connection.go index c021965088d2ff365772e84a5cd701643fa9fa29..96520f53d4a206d96cde8ffa5bca0d819cd83bd9 100644 --- a/controller/nucleus/database/mongo-connection.go +++ b/controller/nucleus/database/mongo-connection.go @@ -11,13 +11,13 @@ import ( ) const ( - // Timeout operations after N seconds + // Timeout operations after N seconds. connectTimeout = 5 // DatabaseName is the name of the mongoDB database used. DatabaseName = "gosdn" ) -// GetMongoConnection Retrieves a client to the MongoDB +// GetMongoConnection Retrieves a client to the MongoDB. func GetMongoConnection() (*mongo.Client, context.Context, context.CancelFunc) { mongoConnection := config.DatabaseConnection client, err := mongo.NewClient(options.Client().ApplyURI(mongoConnection)) diff --git a/controller/nucleus/databaseDeviceStore.go b/controller/nucleus/databaseDeviceStore.go index 4fe9af32e1dbcddd0a5fe2767b6415858404522d..a7664706c391a2de8e0e4593cc71b360dea40a8b 100644 --- a/controller/nucleus/databaseDeviceStore.go +++ b/controller/nucleus/databaseDeviceStore.go @@ -15,12 +15,12 @@ import ( log "github.com/sirupsen/logrus" ) -// DatabaseDeviceStore is used to store Devices +// DatabaseDeviceStore is used to store Devices. type DatabaseDeviceStore struct { storeName string } -// NewDatabaseDeviceStore returns a DeviceStore +// NewDatabaseDeviceStore returns a DeviceStore. func NewDatabaseDeviceStore(pndUUID uuid.UUID) device.Store { return &DatabaseDeviceStore{ storeName: fmt.Sprintf("device-store-%s.json", pndUUID.String()), @@ -48,13 +48,15 @@ func (s *DatabaseDeviceStore) Get(query store.Query) (device.LoadedDevice, error return loadedDevice, nil } -func (s *DatabaseDeviceStore) getByID(idOfDevice uuid.UUID) (device.LoadedDevice, error) { - var loadedDevice device.LoadedDevice - +func (s *DatabaseDeviceStore) getByID(idOfDevice uuid.UUID) (loadedDevice device.LoadedDevice, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) - + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) result := collection.FindOne(ctx, bson.D{primitive.E{Key: "_id", Value: idOfDevice.String()}}) @@ -62,7 +64,7 @@ func (s *DatabaseDeviceStore) getByID(idOfDevice uuid.UUID) (device.LoadedDevice return loadedDevice, errors.ErrCouldNotFind{ID: idOfDevice} } - err := result.Decode(&loadedDevice) + err = result.Decode(&loadedDevice) if err != nil { log.Printf("Failed marshalling %v", err) return loadedDevice, errors.ErrCouldNotMarshall{Identifier: idOfDevice, Type: loadedDevice, Err: err} @@ -71,13 +73,15 @@ func (s *DatabaseDeviceStore) getByID(idOfDevice uuid.UUID) (device.LoadedDevice return loadedDevice, nil } -func (s *DatabaseDeviceStore) getByName(nameOfDevice string) (device.LoadedDevice, error) { - var loadedDevice device.LoadedDevice - +func (s *DatabaseDeviceStore) getByName(nameOfDevice string) (loadedDevice device.LoadedDevice, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) - + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) result := collection.FindOne(ctx, bson.D{primitive.E{Key: "name", Value: nameOfDevice}}) @@ -85,7 +89,7 @@ func (s *DatabaseDeviceStore) getByName(nameOfDevice string) (device.LoadedDevic return loadedDevice, errors.ErrCouldNotFind{Name: nameOfDevice} } - err := result.Decode(&loadedDevice) + err = result.Decode(&loadedDevice) if err != nil { log.Printf("Failed marshalling %v", err) return loadedDevice, errors.ErrCouldNotMarshall{Identifier: nameOfDevice, Type: loadedDevice, Err: err} @@ -95,12 +99,16 @@ func (s *DatabaseDeviceStore) getByName(nameOfDevice string) (device.LoadedDevic } // GetAll returns all stored devices. -func (s *DatabaseDeviceStore) GetAll() ([]device.LoadedDevice, error) { - var loadedDevices []device.LoadedDevice - +func (s *DatabaseDeviceStore) GetAll() (loadedDevices []device.LoadedDevice, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() + db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -108,7 +116,12 @@ func (s *DatabaseDeviceStore) GetAll() ([]device.LoadedDevice, error) { if err != nil { return nil, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedDevices) if err != nil { @@ -121,12 +134,17 @@ func (s *DatabaseDeviceStore) GetAll() ([]device.LoadedDevice, error) { } // Add adds a device to the device store. -func (s *DatabaseDeviceStore) Add(deviceToAdd device.Device) error { +func (s *DatabaseDeviceStore) Add(deviceToAdd device.Device) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.storeName). InsertOne(ctx, deviceToAdd) if err != nil { @@ -138,12 +156,17 @@ func (s *DatabaseDeviceStore) Add(deviceToAdd device.Device) error { } // Update updates a existing device. -func (s *DatabaseDeviceStore) Update(deviceToUpdate device.Device) error { +func (s *DatabaseDeviceStore) Update(deviceToUpdate device.Device) (err error) { var updatedLoadedDevice device.LoadedDevice client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() update := bson.D{primitive.E{Key: "$set", Value: deviceToUpdate}} @@ -154,7 +177,7 @@ func (s *DatabaseDeviceStore) Update(deviceToUpdate device.Device) error { ReturnDocument: &after, } - err := client.Database(database.DatabaseName). + err = client.Database(database.DatabaseName). Collection(s.storeName). FindOneAndUpdate( ctx, bson.M{"_id": deviceToUpdate.ID().String()}, update, &opt). @@ -169,14 +192,19 @@ func (s *DatabaseDeviceStore) Update(deviceToUpdate device.Device) error { } // Delete deletes a device from the device store. -func (s *DatabaseDeviceStore) Delete(deviceToDelete device.Device) error { +func (s *DatabaseDeviceStore) Delete(deviceToDelete device.Device) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) - _, err := collection.DeleteOne(ctx, bson.D{primitive.E{Key: deviceToDelete.ID().String()}}) + _, err = collection.DeleteOne(ctx, bson.D{primitive.E{Key: deviceToDelete.ID().String()}}) if err != nil { return errors.ErrCouldNotDelete{Identifier: deviceToDelete.ID(), Type: deviceToDelete, Err: err} } diff --git a/controller/nucleus/databasePndStore.go b/controller/nucleus/databasePndStore.go index 62d9b29e5022a86aa6c69ffc2464394c82948531..6a8ca96036f1b4884c2001840620f8c528f90db2 100644 --- a/controller/nucleus/databasePndStore.go +++ b/controller/nucleus/databasePndStore.go @@ -1,6 +1,8 @@ package nucleus import ( + "fmt" + "code.fbi.h-da.de/danet/gosdn/controller/interfaces/device" "code.fbi.h-da.de/danet/gosdn/controller/interfaces/networkdomain" @@ -17,7 +19,7 @@ import ( "google.golang.org/grpc/credentials/insecure" ) -// DatabasePndStore is used to store PrincipalNetworkDomains +// DatabasePndStore is used to store PrincipalNetworkDomains. type DatabasePndStore struct { pndStoreName string pendingChannels map[uuid.UUID]chan device.Details @@ -26,13 +28,17 @@ type DatabasePndStore struct { // Get takes a PrincipalNetworkDomain's UUID or name and returns the PrincipalNetworkDomain. If the requested // PrincipalNetworkDomain does not exist an error is returned. -func (s *DatabasePndStore) Get(query store.Query) (networkdomain.NetworkDomain, error) { +func (s *DatabasePndStore) Get(query store.Query) (newPnd networkdomain.NetworkDomain, err error) { var loadedPND LoadedPnd client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) - + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.pndStoreName) result := collection.FindOne(ctx, bson.D{primitive.E{Key: "_id", Value: query.ID.String()}}) @@ -40,7 +46,7 @@ func (s *DatabasePndStore) Get(query store.Query) (networkdomain.NetworkDomain, return nil, errors.ErrCouldNotFind{ID: query.ID} } - err := result.Decode(&loadedPND) + err = result.Decode(&loadedPND) if err != nil { log.Printf("Failed marshalling %v", err) @@ -52,7 +58,7 @@ func (s *DatabasePndStore) Get(query store.Query) (networkdomain.NetworkDomain, return nil, err } - newPnd, err := NewPND( + newPnd, err = NewPND( loadedPND.Name, loadedPND.Description, uuid.MustParse(loadedPND.ID), @@ -67,13 +73,18 @@ func (s *DatabasePndStore) Get(query store.Query) (networkdomain.NetworkDomain, } // GetAll returns all stored pnds. -func (s *DatabasePndStore) GetAll() ([]networkdomain.NetworkDomain, error) { +func (s *DatabasePndStore) GetAll() (pnds []networkdomain.NetworkDomain, err error) { var loadedPnds []LoadedPnd - var pnds []networkdomain.NetworkDomain client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() + db := client.Database(database.DatabaseName) collection := db.Collection(s.pndStoreName) @@ -81,7 +92,12 @@ func (s *DatabasePndStore) GetAll() ([]networkdomain.NetworkDomain, error) { if err != nil { return nil, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedPnds) if err != nil { @@ -114,12 +130,17 @@ func (s *DatabasePndStore) GetAll() ([]networkdomain.NetworkDomain, error) { } // Add adds a pnd to the pnd store. -func (s *DatabasePndStore) Add(pndToAdd networkdomain.NetworkDomain) error { +func (s *DatabasePndStore) Add(pndToAdd networkdomain.NetworkDomain) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.pndStoreName). InsertOne(ctx, pndToAdd) if err != nil { @@ -131,14 +152,18 @@ func (s *DatabasePndStore) Add(pndToAdd networkdomain.NetworkDomain) error { // Delete deletes a pnd. // It also deletes all assosicated devices and sbis. -func (s *DatabasePndStore) Delete(pndToDelete networkdomain.NetworkDomain) error { +func (s *DatabasePndStore) Delete(pndToDelete networkdomain.NetworkDomain) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) - + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.pndStoreName) - _, err := collection.DeleteOne(ctx, bson.D{primitive.E{Key: pndToDelete.ID().String()}}) + _, err = collection.DeleteOne(ctx, bson.D{primitive.E{Key: pndToDelete.ID().String()}}) if err != nil { return errors.ErrCouldNotDelete{Identifier: pndToDelete.ID(), Type: pndToDelete, Err: err} } @@ -149,7 +174,7 @@ func (s *DatabasePndStore) Delete(pndToDelete networkdomain.NetworkDomain) error } // PendingChannels holds channels used communicate with pending -// cSBI deployments +// cSBI deployments. func (s *DatabasePndStore) PendingChannels(id uuid.UUID, parseErrors ...error) (chan device.Details, error) { ch, ok := s.pendingChannels[id] if !ok { @@ -158,12 +183,12 @@ func (s *DatabasePndStore) PendingChannels(id uuid.UUID, parseErrors ...error) ( return ch, nil } -// AddPendingChannel adds a pending channel to the map +// AddPendingChannel adds a pending channel to the map. func (s *DatabasePndStore) AddPendingChannel(id uuid.UUID, ch chan device.Details) { s.pendingChannels[id] = ch } -// RemovePendingChannel removes a pending channel from the map +// RemovePendingChannel removes a pending channel from the map. func (s *DatabasePndStore) RemovePendingChannel(id uuid.UUID) { delete(s.pendingChannels, id) } diff --git a/controller/nucleus/databaseSbiStore.go b/controller/nucleus/databaseSbiStore.go index b472b834e26d824c49e190bbcc7b564a2019d78a..77e4d4d332b37ffc00d3e048829360ac440838e7 100644 --- a/controller/nucleus/databaseSbiStore.go +++ b/controller/nucleus/databaseSbiStore.go @@ -1,6 +1,8 @@ package nucleus import ( + "fmt" + "code.fbi.h-da.de/danet/gosdn/controller/interfaces/southbound" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/database" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors" @@ -12,18 +14,23 @@ import ( log "github.com/sirupsen/logrus" ) -// DatabaseSbiStore is used to store SouthboundInterfaces +// DatabaseSbiStore is used to store SouthboundInterfaces. type DatabaseSbiStore struct { sbiStoreName string } // Add adds a SBI. -func (s *DatabaseSbiStore) Add(sbiToAdd southbound.SouthboundInterface) error { +func (s *DatabaseSbiStore) Add(sbiToAdd southbound.SouthboundInterface) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.sbiStoreName). InsertOne(ctx, sbiToAdd) if err != nil { @@ -38,12 +45,17 @@ func (s *DatabaseSbiStore) Add(sbiToAdd southbound.SouthboundInterface) error { } // Delete deletes an SBI. -func (s *DatabaseSbiStore) Delete(sbiToDelete southbound.SouthboundInterface) error { +func (s *DatabaseSbiStore) Delete(sbiToDelete southbound.SouthboundInterface) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.sbiStoreName). DeleteOne(ctx, bson.D{primitive.E{Key: "_id", Value: sbiToDelete.ID().String()}}) if err != nil { @@ -55,12 +67,15 @@ func (s *DatabaseSbiStore) Delete(sbiToDelete southbound.SouthboundInterface) er // Get takes a SouthboundInterface's UUID or name and returns the SouthboundInterface. If the requested // SouthboundInterface does not exist an error is returned. -func (s *DatabaseSbiStore) Get(query store.Query) (southbound.LoadedSbi, error) { - var loadedSbi southbound.LoadedSbi - +func (s *DatabaseSbiStore) Get(query store.Query) (loadedSbi southbound.LoadedSbi, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() log.Debugf("SBI-Search-ID: %+v\n", query.ID.String()) @@ -71,7 +86,7 @@ func (s *DatabaseSbiStore) Get(query store.Query) (southbound.LoadedSbi, error) return loadedSbi, errors.ErrCouldNotFind{ID: query.ID} } - err := result.Decode(&loadedSbi) + err = result.Decode(&loadedSbi) if err != nil { log.Printf("Failed marshalling %v", err) @@ -81,13 +96,16 @@ func (s *DatabaseSbiStore) Get(query store.Query) (southbound.LoadedSbi, error) return loadedSbi, nil } -// GetAll returns all SBIs -func (s *DatabaseSbiStore) GetAll() ([]southbound.LoadedSbi, error) { - var loadedSbis []southbound.LoadedSbi - +// GetAll returns all SBIs. +func (s *DatabaseSbiStore) GetAll() (loadedSbis []southbound.LoadedSbi, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.sbiStoreName) @@ -95,7 +113,12 @@ func (s *DatabaseSbiStore) GetAll() ([]southbound.LoadedSbi, error) { if err != nil { return nil, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedSbis) if err != nil { diff --git a/controller/nucleus/device.go b/controller/nucleus/device.go index bd3795d783305f17aa1920c228110e7332d1fb11..ae4057eccd389a94aeeadb4559150444e7234b3e 100644 --- a/controller/nucleus/device.go +++ b/controller/nucleus/device.go @@ -16,7 +16,7 @@ import ( "google.golang.org/protobuf/proto" ) -// NewDevice creates a Device +// NewDevice creates a Device. func NewDevice(name string, uuidInput uuid.UUID, opt *tpb.TransportOption, sbi southbound.SouthboundInterface) (device.Device, error) { t, err := NewTransport(opt, sbi) if err != nil { @@ -71,7 +71,7 @@ func NewDevice(name string, uuidInput uuid.UUID, opt *tpb.TransportOption, sbi s }, nil } -// CommonDevice represents an OND +// CommonDevice represents an OND. type CommonDevice struct { // UUID represents the Devices UUID UUID uuid.UUID @@ -91,57 +91,57 @@ type CommonDevice struct { transportOptions *tpb.TransportOption } -// ID returns the UUID of the Device +// ID returns the UUID of the Device. func (d *CommonDevice) ID() uuid.UUID { return d.UUID } -// GetModel returns the ygot representation of the Device +// GetModel returns the ygot representation of the Device. func (d *CommonDevice) GetModel() ygot.GoStruct { return d.Model } -// CreateModelCopy returns a copy of the ygot representation of the Device +// CreateModelCopy returns a copy of the ygot representation of the Device. func (d *CommonDevice) CreateModelCopy() (ygot.ValidatedGoStruct, error) { return createValidatedCopy(d) } -// Transport returns the Transport of the device +// Transport returns the Transport of the device. func (d *CommonDevice) Transport() transport.Transport { return d.transport } -// Name returns the name of the device +// Name returns the name of the device. func (d *CommonDevice) Name() string { return d.name } -// SBI returns the sbi of the Device +// SBI returns the sbi of the Device. func (d *CommonDevice) SBI() southbound.SouthboundInterface { return d.sbi } -// SetTransport sets the Device's Transport +// SetTransport sets the Device's Transport. func (d *CommonDevice) SetTransport(t transport.Transport) { d.transport = t } -// SetName sets the Device's name +// SetName sets the Device's name. func (d *CommonDevice) SetName(n string) { d.name = n } -// SetSBI sets the Device's SBI +// SetSBI sets the Device's SBI. func (d *CommonDevice) SetSBI(sbi southbound.SouthboundInterface) { d.sbi = sbi } -// ProcessResponse processes a response for the Device +// ProcessResponse processes a response for the Device. func (d *CommonDevice) ProcessResponse(resp proto.Message) error { return d.transport.ProcessResponse(resp, d.Model, d.sbi.Schema()) } -// IsTransportValid returns a boolean if the transport of a device is valid +// IsTransportValid returns a boolean if the transport of a device is valid. func (d *CommonDevice) IsTransportValid() bool { if d.transportOptions != nil && d.transportOptions.Address != "" { return true @@ -155,37 +155,37 @@ type CsbiDevice struct { CommonDevice } -// ID returns the UUID of the Device +// ID returns the UUID of the Device. func (d *CsbiDevice) ID() uuid.UUID { return d.UUID } -// GetModel returns the ygot representation of the Device +// GetModel returns the ygot representation of the Device. func (d *CsbiDevice) GetModel() ygot.GoStruct { return d.Model } -// CreateModelCopy returns a copy of the ygot representation of the Device +// CreateModelCopy returns a copy of the ygot representation of the Device. func (d *CsbiDevice) CreateModelCopy() (ygot.ValidatedGoStruct, error) { return createValidatedCopy(d) } -// Transport returns the Transport of the device +// Transport returns the Transport of the device. func (d *CsbiDevice) Transport() transport.Transport { return d.transport } -// Name returns the name of the device +// Name returns the name of the device. func (d *CsbiDevice) Name() string { return d.name } -// SBI returns the sbi of the Device +// SBI returns the sbi of the Device. func (d *CsbiDevice) SBI() southbound.SouthboundInterface { return d.sbi } -// ProcessResponse processes a response for the Device +// ProcessResponse processes a response for the Device. func (d *CsbiDevice) ProcessResponse(resp proto.Message) error { // TODO: callback to send response to caller return d.transport.ProcessResponse(resp, d.Model, d.sbi.Schema()) @@ -209,7 +209,7 @@ func createValidatedCopy(d device.Device) (ygot.ValidatedGoStruct, error) { return validatedCpy, nil } -// IsTransportValid returns a boolean if the transport of a device is valid +// IsTransportValid returns a boolean if the transport of a device is valid. func (d *CsbiDevice) IsTransportValid() bool { if d.transportOptions != nil && d.transportOptions.Address != "" { return true @@ -218,7 +218,7 @@ func (d *CsbiDevice) IsTransportValid() bool { return false } -// MarshalJSON implements the MarshalJSON interface to store a device as JSON +// MarshalJSON implements the MarshalJSON interface to store a device as JSON. func (d *CommonDevice) MarshalJSON() ([]byte, error) { var transportType string var transportAddress string @@ -279,7 +279,7 @@ func (d *CommonDevice) MarshalJSON() ([]byte, error) { }) } -// MarshalBSON implements the MarshalBSON interface to store a device as BSON +// MarshalBSON implements the MarshalBSON interface to store a device as BSON. func (d *CommonDevice) MarshalBSON() ([]byte, error) { var transportType string var transportAddress string @@ -332,7 +332,7 @@ func (d *CommonDevice) MarshalBSON() ([]byte, error) { }) } -// GetModelAsString returns the YANG model of a device as string +// GetModelAsString returns the YANG model of a device as string. func (d *CommonDevice) GetModelAsString() (string, error) { modelAsString, err := ygot.EmitJSON(d.Model, d.getYgotEmitJSONConfig()) if err != nil { diff --git a/controller/nucleus/deviceFilesystemStore.go b/controller/nucleus/deviceFilesystemStore.go index b6777b7c2711e3834195aa03f1d4554bd8d1c81e..ec10e84682ab6684ff39e6bdc8c1d95dde6eb747 100644 --- a/controller/nucleus/deviceFilesystemStore.go +++ b/controller/nucleus/deviceFilesystemStore.go @@ -9,9 +9,10 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors" "code.fbi.h-da.de/danet/gosdn/controller/store" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) -// FilesystemDeviceStore is the filesystem implementation of the device store +// FilesystemDeviceStore is the filesystem implementation of the device store. type FilesystemDeviceStore struct { pndUUID uuid.UUID fileMutex sync.Mutex @@ -22,7 +23,9 @@ type FilesystemDeviceStore struct { func NewFilesystemDeviceStore(pndUUID uuid.UUID) device.Store { deviceFilenameForUUID := store.GetStoreFilenameForUUID(pndUUID, store.DeviceFilenameSuffix) - store.EnsureFilesystemStorePathExists(deviceFilenameForUUID) + if err := store.EnsureFilesystemStorePathExists(deviceFilenameForUUID); err != nil { + log.Error(err) + } return &FilesystemDeviceStore{ pathToDeviceFile: store.GetCompletePathToFileStore(deviceFilenameForUUID), fileMutex: sync.Mutex{}, diff --git a/controller/nucleus/deviceFilesystemStore_test.go b/controller/nucleus/deviceFilesystemStore_test.go index 520a30a520901d75ad4e0cedf3197e97433717f5..0e1337a99a02e361182d9c524eb48a41ebbd337e 100644 --- a/controller/nucleus/deviceFilesystemStore_test.go +++ b/controller/nucleus/deviceFilesystemStore_test.go @@ -1,7 +1,6 @@ package nucleus import ( - "log" "os" "path/filepath" "testing" @@ -11,10 +10,13 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/interfaces/device" "code.fbi.h-da.de/danet/gosdn/controller/store" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) func ensureDeviceFilesForTestAreRemoved() { - store.EnsureFilesystemStorePathExists(store.DeviceFilenameSuffix) + if err := store.EnsureFilesystemStorePathExists(store.DeviceFilenameSuffix); err != nil { + log.Error(err) + } wildcartFilename := "*-" + store.DeviceFilenameSuffix path := store.GetCompletePathToFileStore(wildcartFilename) diff --git a/controller/nucleus/deviceService.go b/controller/nucleus/deviceService.go index 55338bbbbd93c3563d99f2a2065bff3252ae06f6..7e2e00c8a3fde190d87bfba43e697d53d0d8b5b2 100644 --- a/controller/nucleus/deviceService.go +++ b/controller/nucleus/deviceService.go @@ -13,6 +13,7 @@ import ( "github.com/openconfig/ygot/ygot" tpb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/transport" + log "github.com/sirupsen/logrus" ) const ( @@ -21,7 +22,7 @@ const ( ) // DeviceService provides a device service implementation. -// This services provides abstraction between the user (e.g a PND) and the matching store (e.g. deviceStore) +// This services provides abstraction between the user (e.g a PND) and the matching store (e.g. deviceStore). type DeviceService struct { deviceStore device.Store sbiService southbound.Service @@ -79,7 +80,9 @@ func (s *DeviceService) Add(deviceToAdd device.Device) error { return err } - s.eventService.PublishEvent(DeviceEventTopic, event.NewAddEvent(deviceToAdd.ID())) + if err := s.eventService.PublishEvent(DeviceEventTopic, event.NewAddEvent(deviceToAdd.ID())); err != nil { + log.Error(err) + } return nil } @@ -108,7 +111,9 @@ func (s *DeviceService) UpdateModel(deviceToUpdate device.Device, modelAsString return err } - s.eventService.PublishEvent(DeviceEventTopic, event.NewUpdateEvent(deviceToUpdate.ID())) + if err := s.eventService.PublishEvent(DeviceEventTopic, event.NewUpdateEvent(deviceToUpdate.ID())); err != nil { + log.Error(err) + } return nil } @@ -120,7 +125,9 @@ func (s *DeviceService) Update(deviceToUpdate device.Device) error { return err } - s.eventService.PublishEvent(DeviceEventTopic, event.NewUpdateEvent(deviceToUpdate.ID())) + if err := s.eventService.PublishEvent(DeviceEventTopic, event.NewUpdateEvent(deviceToUpdate.ID())); err != nil { + log.Error(err) + } return nil } @@ -138,7 +145,9 @@ func (s *DeviceService) Delete(deviceToDelete device.Device) error { } } - s.eventService.PublishEvent(DeviceEventTopic, event.NewDeleteEvent(deviceToDelete.ID())) + if err := s.eventService.PublishEvent(DeviceEventTopic, event.NewDeleteEvent(deviceToDelete.ID())); err != nil { + log.Error(err) + } return nil } diff --git a/controller/nucleus/deviceServiceMock.go b/controller/nucleus/deviceServiceMock.go index 8d6fa09eeb8fd1fabe65317459117573a895ee6d..e90ec1c499827d4faa0723ee1319dc2281c20006 100644 --- a/controller/nucleus/deviceServiceMock.go +++ b/controller/nucleus/deviceServiceMock.go @@ -20,7 +20,7 @@ func NewDeviceServiceMock() device.Service { } } -// Add adds a item device.Device +// Add adds a item device.Device. func (t *DeviceServiceMock) Add(item device.Device) error { _, ok := t.Store[item.ID()] if ok { @@ -33,7 +33,7 @@ func (t *DeviceServiceMock) Add(item device.Device) error { return nil } -// Update updates a item device.Device +// Update updates a item device.Device. func (t *DeviceServiceMock) Update(item device.Device) error { _, ok := t.Store[item.ID()] if ok { @@ -46,7 +46,7 @@ func (t *DeviceServiceMock) Update(item device.Device) error { return nil } -// UpdateModel updates a item device.Device +// UpdateModel updates a item device.Device. func (t *DeviceServiceMock) UpdateModel(item device.Device, model string) error { _, ok := t.Store[item.ID()] if ok { @@ -59,14 +59,14 @@ func (t *DeviceServiceMock) UpdateModel(item device.Device, model string) error return nil } -// Delete deletes a item device.Device +// Delete deletes a item device.Device. func (t *DeviceServiceMock) Delete(item device.Device) error { delete(t.Store, item.ID()) return nil } -// Get gets a item device.Device +// Get gets a item device.Device. func (t *DeviceServiceMock) Get(query store.Query) (device.Device, error) { // First search for direct hit on UUID. item, ok := t.Store[query.ID] @@ -88,7 +88,7 @@ func (t *DeviceServiceMock) Get(query store.Query) (device.Device, error) { return item, nil } -// GetAll gets all items +// GetAll gets all items. func (t *DeviceServiceMock) GetAll() ([]device.LoadedDevice, error) { var allItems []device.LoadedDevice diff --git a/controller/nucleus/deviceStore.go b/controller/nucleus/deviceStore.go index 681209da58bf68486ee76ebcfdbe505f030a0766..22db669671e533f11c12c68efdb1aa59a9422941 100644 --- a/controller/nucleus/deviceStore.go +++ b/controller/nucleus/deviceStore.go @@ -10,7 +10,7 @@ import ( log "github.com/sirupsen/logrus" ) -// NewDeviceStore returns a DeviceStore +// NewDeviceStore returns a DeviceStore. func NewDeviceStore(pndUUID uuid.UUID) device.Store { storeMode := store.GetStoreMode() log.Debugf("StoreMode: %s", storeMode) diff --git a/controller/nucleus/deviceWatcher.go b/controller/nucleus/deviceWatcher.go index 24eb8eaad0bc75cdd58aaceddf3d2941af221b0f..d6326e43a54e48ef378c05985380358d37023cec 100644 --- a/controller/nucleus/deviceWatcher.go +++ b/controller/nucleus/deviceWatcher.go @@ -117,7 +117,7 @@ func (d *DeviceWatcher) StopAndRemoveDeviceSubscription(subID uuid.UUID) { } // handleSubscribeResponse takes the subscribe response and additional information about the device to distinguish -// from which device a subscribe response was sent including improved error handling +// from which device a subscribe response was sent including improved error handling. func (d *DeviceWatcher) handleSubscribeResponse(resp *gpb.SubscribeResponse, subscriptionInfo *transport.SubscriptionInformation) { switch resp := resp.Response.(type) { case *gpb.SubscribeResponse_Error: @@ -125,7 +125,7 @@ func (d *DeviceWatcher) handleSubscribeResponse(resp *gpb.SubscribeResponse, sub PndID: subscriptionInfo.PndID, DeviceID: subscriptionInfo.DeviceID, DeviceName: subscriptionInfo.DeviceName, - Err: fmt.Sprintf("SubscribeResponse_Error"), + Err: fmt.Sprint("SubscribeResponse_Error"), }) case *gpb.SubscribeResponse_SyncResponse: if !resp.SyncResponse { diff --git a/controller/nucleus/errors/errors.go b/controller/nucleus/errors/errors.go index 254cb165389ff596a289d04981c8fefc799aa2f9..483f4af8f3ac56f4956628b4457288a7799c17d1 100644 --- a/controller/nucleus/errors/errors.go +++ b/controller/nucleus/errors/errors.go @@ -12,7 +12,7 @@ type ErrNilClient struct { } func (e *ErrNilClient) Error() string { - return fmt.Sprintf("client cannot be nil") + return fmt.Sprint("client cannot be nil") } // ErrNil implements the Error interface and is called if a struct is nil. @@ -20,7 +20,7 @@ type ErrNil struct { } func (e *ErrNil) Error() string { - return fmt.Sprintf("struct cannot be nil") + return fmt.Sprint("struct cannot be nil") } // ErrAlreadyExists implements the Error interface and is called if a specific ID @@ -39,7 +39,7 @@ type ErrInvalidUUID struct { } func (e *ErrInvalidUUID) Error() string { - return fmt.Sprintf("UUID not valid") + return fmt.Sprint("UUID not valid") } // ErrInvalidTypeAssertion implements the Error interface and is called if the @@ -79,7 +79,7 @@ func (e ErrPathNotFound) Error() string { type ErrNotYetImplemented struct{} func (e ErrNotYetImplemented) Error() string { - return fmt.Sprintf("function not yet implemented") + return fmt.Sprint("function not yet implemented") } // ErrInvalidParameters implements the Error interface and is called if the wrong @@ -160,7 +160,7 @@ func (e ErrTypeNotSupported) Error() string { } // ErrCouldNotMarshall implements Error interface and is called if a -// database respone can not be parsed. +// database response can not be parsed. type ErrCouldNotMarshall struct { Identifier any Type any diff --git a/controller/nucleus/genericService.go b/controller/nucleus/genericService.go index a794928e75c46e5ca8f0f07311f86759b616c313..af0193d532fc826f2258c09ccacfa4c73b342c75 100644 --- a/controller/nucleus/genericService.go +++ b/controller/nucleus/genericService.go @@ -24,7 +24,7 @@ func NewGenericService[T storableConstraint]() GenericService[T] { } } -// Add adds a item T +// Add adds a item T. func (t *GenericService[T]) Add(item T) error { _, ok := t.Store[item.ID()] if ok { @@ -37,7 +37,7 @@ func (t *GenericService[T]) Add(item T) error { return nil } -// Update updates a item T +// Update updates a item T. func (t *GenericService[T]) Update(item T) error { _, ok := t.Store[item.ID()] if ok { @@ -50,14 +50,14 @@ func (t *GenericService[T]) Update(item T) error { return nil } -// Delete deletes a item T +// Delete deletes a item T. func (t *GenericService[T]) Delete(item T) error { delete(t.Store, item.ID()) return nil } -// Get gets a item T +// Get gets a item T. func (t *GenericService[T]) Get(query store.Query) (T, error) { // First search for direct hit on UUID. item, ok := t.Store[query.ID] @@ -79,7 +79,7 @@ func (t *GenericService[T]) Get(query store.Query) (T, error) { return item, nil } -// GetAll gets all items +// GetAll gets all items. func (t *GenericService[T]) GetAll() ([]T, error) { var allItems []T diff --git a/controller/nucleus/gnmi_transport.go b/controller/nucleus/gnmi_transport.go index 029c33fa15681c318156187127cce98dd6b134a6..f5a4482c7fe0a4bbfdb4dafa1d0d7efe776d7d6b 100644 --- a/controller/nucleus/gnmi_transport.go +++ b/controller/nucleus/gnmi_transport.go @@ -195,7 +195,7 @@ func createSetRequest(ctx context.Context, diff *gpb.Notification, json []byte, return req, nil } -//Subscribe subscribes to a gNMI target +//Subscribe subscribes to a gNMI target. func (g *Gnmi) Subscribe(ctx context.Context, params ...string) error { if g.client == nil { return &errors.ErrNilClient{} @@ -213,7 +213,7 @@ func (g *Gnmi) ControlPlaneSubscribe(ctx context.Context, subscribeCallbackFunc return g.controlPlaneSubscribe(ctx, subscribeCallbackFunc, subscriptionInfo) } -// Type returns the gNMI transport type +// Type returns the gNMI transport type. func (g *Gnmi) Type() string { return "gnmi" } @@ -337,7 +337,7 @@ func (g *Gnmi) processResponseDeletes(deletes []*gpb.Path, deviceModel ygot.Vali return nil } -// Capabilities calls GNMI capabilities +// Capabilities calls GNMI capabilities. func (g *Gnmi) Capabilities(ctx context.Context) (interface{}, error) { log.WithFields(log.Fields{ "target": g.Options.Address, @@ -351,7 +351,7 @@ func (g *Gnmi) Capabilities(ctx context.Context) (interface{}, error) { return resp, nil } -// get calls GNMI get +// get calls GNMI get. func (g *Gnmi) get(ctx context.Context, paths [][]string, origin string) (interface{}, error) { ctx = context.WithValue(ctx, types.CtxKeyConfig, g.config) //nolint req, err := gnmi.NewGetRequest(ctx, paths, origin) @@ -448,7 +448,7 @@ func (g *Gnmi) controlPlaneSubscribe(ctx context.Context, subcribeCallbackFunc f return gnmi.SubscribeErr(ctx, g.client, opts, g.RespChan) } -// Close calls GNMI close +// Close calls GNMI close. func (g *Gnmi) Close() error { return nil } @@ -460,12 +460,12 @@ func (g *Gnmi) CustomSet(ctx context.Context, req *gpb.SetRequest) (*gpb.SetResp return g.client.Set(ctx, req) } -// SetPassthrough allows to pass an existing SetRequest. Used for cSBI +// SetPassthrough allows to pass an existing SetRequest. Used for cSBI. func (g *Gnmi) SetPassthrough(ctx context.Context, req *gpb.SetRequest) (*gpb.SetResponse, error) { return g.client.Set(ctx, req) } -// GetPassthrough allows to pass an existing GetRequest. Used for cSBI +// GetPassthrough allows to pass an existing GetRequest. Used for cSBI. func (g *Gnmi) GetPassthrough(ctx context.Context, req *gpb.GetRequest) (*gpb.GetResponse, error) { return g.client.Get(ctx, req) } diff --git a/controller/nucleus/gnmi_transport_test.go b/controller/nucleus/gnmi_transport_test.go index deb6742db9cf6255483cbf4fd0b2a627d8910c65..146b1ce8b14ded564916e05f26d8a8822ec53732 100644 --- a/controller/nucleus/gnmi_transport_test.go +++ b/controller/nucleus/gnmi_transport_test.go @@ -25,7 +25,7 @@ import ( "github.com/stretchr/testify/mock" ) -// testSetupGnmi bootstraps tests for gnmi transport +// testSetupGnmi bootstraps tests for gnmi transport. func testSetupGnmi() { // TODO: Set sane defaults gnmiConfig = &gnmi.Config{ @@ -439,6 +439,7 @@ func TestGnmi_Type(t *testing.T) { } } +//nolint:errcheck func TestGnmi_getWithRequest(t *testing.T) { transport := mockTransport() reqFullNode := gnmiMessages["../test/proto/req-full-node"].(*gpb.GetRequest) diff --git a/controller/nucleus/initialise_test.go b/controller/nucleus/initialise_test.go index 98bbe72e9ffec75644f03e9ebf3ae2061146bdd6..88c55cedb56131247e41f6c0704c8c3206bfbdc5 100644 --- a/controller/nucleus/initialise_test.go +++ b/controller/nucleus/initialise_test.go @@ -26,7 +26,7 @@ import ( pb "google.golang.org/protobuf/proto" ) -// UUIDs for test cases +// UUIDs for test cases. var did uuid.UUID var mdid uuid.UUID var defaultSbiID uuid.UUID @@ -45,7 +45,7 @@ var stopGnmiTarget chan bool var mockContext = mock.MatchedBy(func(ctx context.Context) bool { return true }) // TestMain bootstraps all tests. Humongous beast -// TODO: Move somewhere more sensible +// TODO: Move somewhere more sensible. func TestMain(m *testing.M) { log.SetReportCaller(true) @@ -176,7 +176,7 @@ func newPnd() pndImplementation { } // removeTestPlugins removes the plugins created during running the test in the current directory based on their name consisting of a uuid -// and the time since they`ve been created +// and the time since they`ve been created. func removeTestPlugins() { currentDirectory := "./" // pattern to match plugin uuid used as dir name @@ -204,7 +204,7 @@ func removeTestPlugins() { } // isDirYoungerThanSeconds returns true if the provided dir is younger than the given amount in seconds -// and therefore was created as part of the test suite +// and therefore was created as part of the test suite. func isDirYoungerThanSeconds(dirName string, seconds int64) bool { fileInfo, err := os.Stat(dirName) if err != nil { diff --git a/controller/nucleus/memoryPndStore.go b/controller/nucleus/memoryPndStore.go index c863378992aa4aea076595512fe36b213efd2d49..15cc6909e3b87a1de909ff3f71b378c0bb589c32 100644 --- a/controller/nucleus/memoryPndStore.go +++ b/controller/nucleus/memoryPndStore.go @@ -63,7 +63,7 @@ func (t *MemoryPndStore) GetAll() ([]networkdomain.NetworkDomain, error) { } // PendingChannels holds channels used communicate with pending -// cSBI deployments +// cSBI deployments. func (t *MemoryPndStore) PendingChannels(id uuid.UUID, parseErrors ...error) (chan device.Details, error) { ch, ok := t.pendingChannels[id] if !ok { @@ -72,12 +72,12 @@ func (t *MemoryPndStore) PendingChannels(id uuid.UUID, parseErrors ...error) (ch return ch, nil } -// AddPendingChannel adds a pending channel to the map +// AddPendingChannel adds a pending channel to the map. func (t *MemoryPndStore) AddPendingChannel(id uuid.UUID, ch chan device.Details) { t.pendingChannels[id] = ch } -// RemovePendingChannel removes a pending channel from the map +// RemovePendingChannel removes a pending channel from the map. func (t *MemoryPndStore) RemovePendingChannel(id uuid.UUID) { delete(t.pendingChannels, id) } diff --git a/controller/nucleus/pndFilesystemStore.go b/controller/nucleus/pndFilesystemStore.go index 867d654395359fb7d58a8f3f6c901e93d5cc2524..c179d5330637b0ecb7e24f123da6ba0121d9bf27 100644 --- a/controller/nucleus/pndFilesystemStore.go +++ b/controller/nucleus/pndFilesystemStore.go @@ -27,7 +27,10 @@ type FilesystemPndStore struct { // NewFilesystemPndStore returns a filesystem implementation for a pnd store. func NewFilesystemPndStore() FilesystemPndStore { - store.EnsureFilesystemStorePathExists(store.PndFilename) + if err := store.EnsureFilesystemStorePathExists(store.PndFilename); err != nil { + log.Error(err) + } + return FilesystemPndStore{ pendingChannels: make(map[uuid.UUID]chan device.Details), pathToPndFile: store.GetCompletePathToFileStore(store.PndFilename), @@ -164,7 +167,7 @@ func (t *FilesystemPndStore) GetAll() ([]networkdomain.NetworkDomain, error) { } // PendingChannels holds channels used communicate with pending -// cSBI deployments +// cSBI deployments. func (t *FilesystemPndStore) PendingChannels(id uuid.UUID, parseErrors ...error) (chan device.Details, error) { ch, ok := t.pendingChannels[id] if !ok { @@ -173,12 +176,12 @@ func (t *FilesystemPndStore) PendingChannels(id uuid.UUID, parseErrors ...error) return ch, nil } -// AddPendingChannel adds a pending channel to the map +// AddPendingChannel adds a pending channel to the map. func (t *FilesystemPndStore) AddPendingChannel(id uuid.UUID, ch chan device.Details) { t.pendingChannels[id] = ch } -// RemovePendingChannel removes a pending channel from the map +// RemovePendingChannel removes a pending channel from the map. func (t *FilesystemPndStore) RemovePendingChannel(id uuid.UUID) { delete(t.pendingChannels, id) } diff --git a/controller/nucleus/pndFilesystemStore_test.go b/controller/nucleus/pndFilesystemStore_test.go index 29119f9f343710cf91d6500b2393686d65c68734..abc08fa16eb53e29d105ea06329823f136e6926a 100644 --- a/controller/nucleus/pndFilesystemStore_test.go +++ b/controller/nucleus/pndFilesystemStore_test.go @@ -11,7 +11,10 @@ import ( ) func ensurePndFileForTestIsRemoved() { - store.EnsureFilesystemStorePathExists(store.PndFilename) + if err := store.EnsureFilesystemStorePathExists(store.PndFilename); err != nil { + log.Println(err) + } + path := store.GetCompletePathToFileStore(store.PndFilename) err := os.Remove(path) diff --git a/controller/nucleus/pndStore.go b/controller/nucleus/pndStore.go index 6e4a4b005413a9b8a1f6dfe59bc947afd991a034..61f87daa9ff2b7522c6889aedc6441b741c771fd 100644 --- a/controller/nucleus/pndStore.go +++ b/controller/nucleus/pndStore.go @@ -16,11 +16,11 @@ type LoadedPnd struct { Description string `json:"description,omitempty"` } -// PndStore is used to store PrincipalNetworkDomains +// PndStore is used to store PrincipalNetworkDomains. type PndStore struct { } -// NewPndStore returns a PndStore +// NewPndStore returns a PndStore. func NewPndStore() networkdomain.PndStore { storeMode := store.GetStoreMode() log.Debugf("StoreMode: %s", storeMode) diff --git a/controller/nucleus/principalNetworkDomain.go b/controller/nucleus/principalNetworkDomain.go index b02c2cf083e139154962efb4d58d927de5978fe9..ea13d0988d345d8a4d0b5dcc82d17bb6fda6f470 100644 --- a/controller/nucleus/principalNetworkDomain.go +++ b/controller/nucleus/principalNetworkDomain.go @@ -3,6 +3,7 @@ package nucleus import ( "context" "encoding/json" + goErrors "errors" "fmt" "io" "os" @@ -48,7 +49,7 @@ import ( // changeStores in memory for now. var changeStoreMap = make(map[uuid.UUID]*store.ChangeStore) -// NewPND creates a Principle Network Domain +// NewPND creates a Principle Network Domain. func NewPND( name string, description string, @@ -162,17 +163,17 @@ func (pnd *pndImplementation) Devices() []device.LoadedDevice { return allDevices } -// GetName returns the name of the PND +// GetName returns the name of the PND. func (pnd *pndImplementation) GetName() string { return pnd.Name } -// GetDescription returns the current description of the PND +// GetDescription returns the current description of the PND. func (pnd *pndImplementation) GetDescription() string { return pnd.Description } -// GetSBIs returns the registered SBIs +// GetSBIs returns the registered SBIs. func (pnd *pndImplementation) GetSBIs() ([]southbound.SouthboundInterface, error) { sbis, err := pnd.southboundService.GetAll() if err != nil { @@ -181,7 +182,7 @@ func (pnd *pndImplementation) GetSBIs() ([]southbound.SouthboundInterface, error return sbis, nil } -// GetSBIs returns the registered SBIs +// GetSBIs returns the registered SBIs. func (pnd *pndImplementation) GetSBI(sbiUUID uuid.UUID) (southbound.SouthboundInterface, error) { sbis, err := pnd.southboundService.Get(store.Query{ID: sbiUUID}) if err != nil { @@ -190,18 +191,18 @@ func (pnd *pndImplementation) GetSBI(sbiUUID uuid.UUID) (southbound.SouthboundIn return sbis, nil } -// Destroy destroys the PND +// Destroy destroys the PND. func (pnd *pndImplementation) Destroy() error { return destroy() } -// AddSbi adds a SBI to the PND which will be supported +// AddSbi adds a SBI to the PND which will be supported. func (pnd *pndImplementation) AddSbi(s southbound.SouthboundInterface) error { return pnd.addSbi(s) } // RemoveSbi removes a SBI from the PND -// devices and remove the devices using this SBI +// devices and remove the devices using this SBI. func (pnd *pndImplementation) RemoveSbi(sid uuid.UUID) error { var associatedDevices []device.LoadedDevice @@ -237,7 +238,7 @@ func (pnd *pndImplementation) RemoveSbi(sid uuid.UUID) error { return pnd.removeSbi(sid) } -// AddDevice adds a new device to the PND +// AddDevice adds a new device to the PND. func (pnd *pndImplementation) AddDevice(name string, opt *tpb.TransportOption, sid uuid.UUID) (uuid.UUID, error) { labels := prometheus.Labels{"type": opt.Type.String()} start := metrics.StartHook(labels, deviceCreationsTotal) @@ -269,7 +270,7 @@ func (pnd *pndImplementation) AddDevice(name string, opt *tpb.TransportOption, s return pnd.addDevice(d) } -// TODO: (maba): This should be changed to UUID +// TODO: (maba): This should be changed to UUID. func (pnd *pndImplementation) GetDevice(identifier string) (device.Device, error) { id, err := uuid.Parse(identifier) if err != nil { @@ -290,12 +291,12 @@ func (pnd *pndImplementation) GetDevice(identifier string) (device.Device, error return d, nil } -// RemoveDevice removes a device from the PND +// RemoveDevice removes a device from the PND. func (pnd *pndImplementation) RemoveDevice(uuid uuid.UUID) error { return pnd.removeDevice(uuid) } -// UpdateDeviceModel updates a device from the PND +// UpdateDeviceModel updates a device from the PND. func (pnd *pndImplementation) UpdateDevice(device device.Device, modelAsString string) error { err := pnd.deviceService.UpdateModel(device, modelAsString) if err != nil { @@ -310,7 +311,7 @@ func (pnd *pndImplementation) UpdateDevice(device device.Device, modelAsString s return err } -// Actual implementation, bind to struct if neccessary +// Actual implementation, bind to struct if necessary. func destroy() error { return nil } @@ -396,7 +397,7 @@ func (pnd *pndImplementation) MarshalDevice(identifier string) (string, error) { return string(jsonTree), nil } -// Request sends a get request to a specific device +// Request sends a get request to a specific device. func (pnd *pndImplementation) Request(uuid uuid.UUID, path string) (proto.Message, error) { d, err := pnd.deviceService.Get(store.Query{ ID: uuid, @@ -433,7 +434,7 @@ func (pnd *pndImplementation) Request(uuid uuid.UUID, path string) (proto.Messag return resp, nil } -// RequestAll sends a request for all registered devices +// RequestAll sends a request for all registered devices. func (pnd *pndImplementation) RequestAll(path string) error { allDevices, err := pnd.deviceService.GetAll() if err != nil { @@ -451,7 +452,7 @@ func (pnd *pndImplementation) RequestAll(path string) error { } } // TODO: (maba): this is not returning any useful information; this should - // return some feedback if the requests were successfull + // return some feedback if the requests were successful log.WithFields(log.Fields{ "pnd": pnd.Id, "path": path, @@ -496,7 +497,7 @@ func (pnd *pndImplementation) ensureIntendedConfigurationIsAppliedOnDevice(devic //nolint:gocyclo // ChangeOND creates a change from the provided Operation, path and value. -// The Change is Pending and times out after the specified timeout period +// The Change is Pending and times out after the specified timeout period. func (pnd *pndImplementation) ChangeOND(duid uuid.UUID, operation ppb.ApiOperation, path string, value ...string) (uuid.UUID, error) { //TODO: check if we can get cyclomatic complexity from 16 to at least 15 d, err := pnd.deviceService.Get(store.Query{ @@ -866,7 +867,7 @@ type StreamClient interface { // gRPC stream. A 'gostructs.go' file is created within the goSDN's // 'plugin-folder'. Each 'gostructs.go' file is stored in its own folder based // on a new uuid.UUID. -func saveStreamToFile[T StreamClient](sc T, filename string, id uuid.UUID) error { +func saveStreamToFile[T StreamClient](sc T, filename string, id uuid.UUID) (err error) { folderName := viper.GetString("plugin-folder") path := filepath.Join(folderName, id.String(), filename) @@ -890,8 +891,9 @@ func saveStreamToFile[T StreamClient](sc T, filename string, id uuid.UUID) error } defer func() { - if err := f.Close(); err != nil { - log.Error("error closing file: ", err) + if ferr := f.Close(); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w error closing file:%+s", err, fErrString) } }() @@ -899,7 +901,7 @@ func saveStreamToFile[T StreamClient](sc T, filename string, id uuid.UUID) error for { payload, err := sc.Recv() if err != nil { - if err == io.EOF { + if goErrors.Is(err, io.EOF) { break } closeErr := sc.CloseSend() @@ -927,7 +929,7 @@ func saveStreamToFile[T StreamClient](sc T, filename string, id uuid.UUID) error return nil } -// MarshalBSON implements the MarshalBSON interface to store a device as BSON +// MarshalBSON implements the MarshalBSON interface to store a device as BSON. func (pnd *pndImplementation) MarshalBSON() ([]byte, error) { return bson.Marshal(&struct { ID string `bson:"_id"` diff --git a/controller/nucleus/principalNetworkDomain_test.go b/controller/nucleus/principalNetworkDomain_test.go index bb367138b4c69555961863a5986bf43cce167c1c..8f5001121172fb52e326af54deb589fdac186979 100644 --- a/controller/nucleus/principalNetworkDomain_test.go +++ b/controller/nucleus/principalNetworkDomain_test.go @@ -987,7 +987,11 @@ func Test_pndImplementation_Confirm(t *testing.T) { } d := mockDevice() - tr := d.Transport().(*mocks.Transport) + tr, ok := d.Transport().(*mocks.Transport) + if !ok { + log.Errorf("Confirm(), failed type conversion: %v", ok) + } + tr.On("Set", mockContext, mock.Anything, mock.Anything, mock.Anything).Return(nil) _, err := pnd.addDevice(d) if err != nil { diff --git a/controller/nucleus/restconf_transport.go b/controller/nucleus/restconf_transport.go index 07ecbb1f29e68db528d605140f3a918b45143281..c00c852d68ba44c6bfe0735b2ac70bfd70c9cabf 100644 --- a/controller/nucleus/restconf_transport.go +++ b/controller/nucleus/restconf_transport.go @@ -12,32 +12,32 @@ import ( // possibility to access a Restconf endpoint. type Restconf struct{} -// Get not yet implemented +// Get not yet implemented. func (r Restconf) Get(ctx context.Context, params ...string) (interface{}, error) { return nil, &errors.ErrNotYetImplemented{} } -// Set not yet implemented +// Set not yet implemented. func (r Restconf) Set(ctx context.Context, params ...interface{}) error { return &errors.ErrNotYetImplemented{} } -// Subscribe not yet implemented +// Subscribe not yet implemented. func (r Restconf) Subscribe(ctx context.Context, params ...string) error { return &errors.ErrNotYetImplemented{} } -// Type not yet implemented +// Type not yet implemented. func (r Restconf) Type() string { return "restconf" } -// GetOptions not yet implemented +// GetOptions not yet implemented. func (r Restconf) GetOptions() interface{} { return &errors.ErrNotYetImplemented{} } -// ProcessResponse not yet implemented +// ProcessResponse not yet implemented. func (r Restconf) ProcessResponse(resp interface{}, root interface{}, models *ytypes.Schema) error { return &errors.ErrNotYetImplemented{} } diff --git a/controller/nucleus/sbiFilesystemStore.go b/controller/nucleus/sbiFilesystemStore.go index d9a2dcda474bd0e79ccdd12cbadf323d1ce2f47a..7ead5bf270594cd5105ac6bebf5ecaea8e2d8d0c 100644 --- a/controller/nucleus/sbiFilesystemStore.go +++ b/controller/nucleus/sbiFilesystemStore.go @@ -10,9 +10,10 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/store" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) -// FilesystemSbiStore is used to store SouthboundInterfaces +// FilesystemSbiStore is used to store SouthboundInterfaces. type FilesystemSbiStore struct { pndUUID uuid.UUID fileMutex sync.Mutex @@ -23,7 +24,10 @@ type FilesystemSbiStore struct { func NewFilesystemSbiStore(pndUUID uuid.UUID) southbound.Store { sbiFilenameForUUID := store.GetStoreFilenameForUUID(pndUUID, store.SbiFilenameSuffix) - store.EnsureFilesystemStorePathExists(sbiFilenameForUUID) + if err := store.EnsureFilesystemStorePathExists(sbiFilenameForUUID); err != nil { + log.Error(err) + } + return &FilesystemSbiStore{ pathToSbiFile: store.GetCompletePathToFileStore(sbiFilenameForUUID), fileMutex: sync.Mutex{}, @@ -134,7 +138,7 @@ func (s *FilesystemSbiStore) Get(query store.Query) (southbound.LoadedSbi, error return sbi, &errors.ErrCouldNotFind{ID: query.ID, Name: query.Name} } -// GetAll returns all SBIs +// GetAll returns all SBIs. func (s *FilesystemSbiStore) GetAll() ([]southbound.LoadedSbi, error) { s.fileMutex.Lock() defer s.fileMutex.Unlock() diff --git a/controller/nucleus/sbiFilesystemStore_test.go b/controller/nucleus/sbiFilesystemStore_test.go index 4ec3de489742d87d2fabef6b02e4ec3fcbb25615..179fe2b870da740626de9ba628312e5f8ce6ec2c 100644 --- a/controller/nucleus/sbiFilesystemStore_test.go +++ b/controller/nucleus/sbiFilesystemStore_test.go @@ -13,7 +13,10 @@ import ( ) func ensureSbiFilesForTestAreRemoved() { - store.EnsureFilesystemStorePathExists(store.SbiFilenameSuffix) + if err := store.EnsureFilesystemStorePathExists(store.SbiFilenameSuffix); err != nil { + log.Println(err) + } + wildcartFilename := "*-" + store.SbiFilenameSuffix path := store.GetCompletePathToFileStore(wildcartFilename) diff --git a/controller/nucleus/sbiService.go b/controller/nucleus/sbiService.go index c52a8f882138141c129aff11ae97d41fc9f84285..8c1902431e900c177b99baaed58cabba778e59dc 100644 --- a/controller/nucleus/sbiService.go +++ b/controller/nucleus/sbiService.go @@ -8,6 +8,7 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/interfaces/southbound" "code.fbi.h-da.de/danet/gosdn/controller/store" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) const ( @@ -72,7 +73,9 @@ func (s *SbiService) Add(sbiToAdd southbound.SouthboundInterface) error { return err } - s.eventService.PublishEvent(SbiEventTopic, event.NewAddEvent(sbiToAdd.ID())) + if err := s.eventService.PublishEvent(SbiEventTopic, event.NewAddEvent(sbiToAdd.ID())); err != nil { + log.Error(err) + } return nil } @@ -91,7 +94,9 @@ func (s *SbiService) Delete(sbiToDelete southbound.SouthboundInterface) error { } } - s.eventService.PublishEvent(SbiEventTopic, event.NewDeleteEvent(sbiToDelete.ID())) + if err := s.eventService.PublishEvent(SbiEventTopic, event.NewDeleteEvent(sbiToDelete.ID())); err != nil { + log.Error(err) + } return nil } diff --git a/controller/nucleus/sbiStore.go b/controller/nucleus/sbiStore.go index f413ae6f55cd18e482063d70042705fa4886d9d2..5b07b69eafda6fc7ad4a4ae0df74f4ea3fc0db5f 100644 --- a/controller/nucleus/sbiStore.go +++ b/controller/nucleus/sbiStore.go @@ -9,11 +9,11 @@ import ( "github.com/google/uuid" ) -// SbiStore is used to store SouthboundInterfaces +// SbiStore is used to store SouthboundInterfaces. type SbiStore struct { } -// NewSbiStore returns a sbiStore +// NewSbiStore returns a sbiStore. func NewSbiStore(pndUUID uuid.UUID) southbound.Store { storeMode := store.GetStoreMode() diff --git a/controller/nucleus/southbound.go b/controller/nucleus/southbound.go index 72278e29447bf92d3def28015f3b6485cfeef08b..4e3f4c1bdd211d84efe5ab6d616ca4535d644e70 100644 --- a/controller/nucleus/southbound.go +++ b/controller/nucleus/southbound.go @@ -84,17 +84,17 @@ type OpenConfig struct { // SbiIdentifier returns the string representation of // the SBI -// deprecated +// deprecated. func (oc *OpenConfig) SbiIdentifier() string { return "openconfig" } -// Name returns the name of a sbi +// Name returns the name of a sbi. func (oc *OpenConfig) Name() string { return oc.SbiIdentifier() } -// Schema returns a ygot generated openconfig Schema as ytypes.Schema +// Schema returns a ygot generated openconfig Schema as ytypes.Schema. func (oc *OpenConfig) Schema() *ytypes.Schema { schema, err := openconfig.Schema() oc.schema = schema @@ -165,17 +165,17 @@ func unmarshal(schema *ytypes.Schema, bytes []byte, path *gpb.Path, goStruct ygo return ygot.MergeStructInto(goStruct, validatedDeepCopy, opts...) } -// ID returns the ID of the OpenConfig SBI +// ID returns the ID of the OpenConfig SBI. func (oc *OpenConfig) ID() uuid.UUID { return oc.id } -// SetID sets the ID of the OpenConfig SBI +// SetID sets the ID of the OpenConfig SBI. func (oc *OpenConfig) SetID(id uuid.UUID) { oc.id = id } -// Type returns the Southbound's type +// Type returns the Southbound's type. func (oc *OpenConfig) Type() spb.Type { return spb.Type_TYPE_OPENCONFIG } @@ -188,7 +188,7 @@ type SouthboundPlugin struct { manifest *plugin.Manifest } -// Name returns the name of a sbi +// Name returns the name of a sbi. func (p *SouthboundPlugin) Name() string { return "plugin" } @@ -199,7 +199,7 @@ func (p *SouthboundPlugin) SetNode(schema *yang.Entry, root interface{}, path *g return p.sbi.SetNode(schema, root, path, val, opts...) } -// Schema returns a ygot generated Schema as ytypes.Schema +// Schema returns a ygot generated Schema as ytypes.Schema. func (p *SouthboundPlugin) Schema() *ytypes.Schema { return p.sbi.Schema() } @@ -215,12 +215,12 @@ func (p *SouthboundPlugin) ID() uuid.UUID { return p.sbi.ID() } -// SetID sets the ID of the SouthboundPlugin's SBI +// SetID sets the ID of the SouthboundPlugin's SBI. func (p *SouthboundPlugin) SetID(id uuid.UUID) { p.sbi.SetID(id) } -// Type returns the Southbound's type of the SouthboundPlugin +// Type returns the Southbound's type of the SouthboundPlugin. func (p *SouthboundPlugin) Type() spb.Type { return p.sbi.Type() } @@ -297,7 +297,7 @@ func (p *SouthboundPlugin) Update() error { return nil } -// MarshalJSON implements the MarshalJSON interface to store a sbi as JSON +// MarshalJSON implements the MarshalJSON interface to store a sbi as JSON. func (p *SouthboundPlugin) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { ID string `json:"_id"` @@ -308,7 +308,7 @@ func (p *SouthboundPlugin) MarshalJSON() ([]byte, error) { }) } -// MarshalJSON implements the MarshalJSON interface to store a sbi as JSON +// MarshalJSON implements the MarshalJSON interface to store a sbi as JSON. func (oc *OpenConfig) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { ID string `json:"_id"` @@ -319,7 +319,7 @@ func (oc *OpenConfig) MarshalJSON() ([]byte, error) { }) } -// MarshalBSON implements the MarshalBSON interface to store a sbi as BSON +// MarshalBSON implements the MarshalBSON interface to store a sbi as BSON. func (p *SouthboundPlugin) MarshalBSON() ([]byte, error) { return bson.Marshal(&struct { ID string `bson:"_id"` @@ -330,7 +330,7 @@ func (p *SouthboundPlugin) MarshalBSON() ([]byte, error) { }) } -// MarshalBSON implements the MarshalBSON interface to store a sbi as BSON +// MarshalBSON implements the MarshalBSON interface to store a sbi as BSON. func (oc *OpenConfig) MarshalBSON() ([]byte, error) { return bson.Marshal(&struct { ID string `bson:"_id"` diff --git a/controller/nucleus/transport.go b/controller/nucleus/transport.go index 384cd507150948c25b2dff71493abd10221d0a9e..a2db1ff28b60a17e3ee64f4c311f10bbfe071364 100644 --- a/controller/nucleus/transport.go +++ b/controller/nucleus/transport.go @@ -8,7 +8,7 @@ import ( ) // NewTransport receives TransportOptions and returns an appropriate Transport -// implementation +// implementation. func NewTransport(opts *tpb.TransportOption, sbi southbound.SouthboundInterface) (transport.Transport, error) { if opts == nil { return nil, &errors.ErrInvalidParameters{ diff --git a/controller/nucleus/types/types.go b/controller/nucleus/types/types.go index aa514b17b4068fec76f569f0113c9e3a1dd568d1..bc8228c30b44a26e0a28679961f5c3cd53a370f8 100644 --- a/controller/nucleus/types/types.go +++ b/controller/nucleus/types/types.go @@ -3,14 +3,14 @@ package types // CtxKeyType is a custom type to be used as key in a context.WithValue() or // context.Value() call. For more information see: // https://www.calhoun.io/pitfalls-of-context-values-and-how-to-avoid-or-mitigate-them/ -// TODO: Unexport to comply with best practice +// TODO: Unexport to comply with best practice. type CtxKeyType string const ( - // CtxKeyOpts context key for gnmi.SubscribeOptions + // CtxKeyOpts context key for gnmi.SubscribeOptions. CtxKeyOpts CtxKeyType = "opts" - // CtxKeyConfig is a context key for gnmi.Config + // CtxKeyConfig is a context key for gnmi.Config. CtxKeyConfig = "config" - // CtxKeyOperation is a context key for a gNMI operation (update, replace, delete) + // CtxKeyOperation is a context key for a gNMI operation (update, replace, delete). CtxKeyOperation = "op" ) diff --git a/controller/nucleus/util/path/translate.go b/controller/nucleus/util/path/translate.go index fdd6ab1f4c8f05f05c54ab0bf6fb9d90e731d583..6d6ab7f27a0d2cf87c0218c4c2f20863716a3f03 100644 --- a/controller/nucleus/util/path/translate.go +++ b/controller/nucleus/util/path/translate.go @@ -6,7 +6,7 @@ import ( gpb "github.com/openconfig/gnmi/proto/gnmi" ) -// ToStrings translates a gNMI path to a slice of strings +// ToStrings translates a gNMI path to a slice of strings. func ToStrings(path *gpb.Path) []string { elems := make([]string, len(path.Elem)) for i, e := range path.Elem { diff --git a/controller/nucleus/util/path/traverse.go b/controller/nucleus/util/path/traverse.go index 403ffc5e441f86013e3eb35a7b6ab331e50b0fb9..0615422dfcf80d39200852769ccc41ac2f3857bb 100644 --- a/controller/nucleus/util/path/traverse.go +++ b/controller/nucleus/util/path/traverse.go @@ -11,13 +11,13 @@ import ( const delim = "/" -// Element represents a node in a path containing its name and possible child nodes +// Element represents a node in a path containing its name and possible child nodes. type Element struct { Children []*Element Name string } -// Print prints the path element to stdout. It calls printElement recursively +// Print prints the path element to stdout. It calls printElement recursively. func (p *Element) Print() { printElement(0, p) } @@ -34,7 +34,7 @@ func printElement(indent int, pe *Element) { } } -// ParseSchema takes a YANG schema and parses it into paths +// ParseSchema takes a YANG schema and parses it into paths. func ParseSchema(schema *ytypes.Schema, root string) (map[string]*Element, error) { paths := make(map[string]*Element) tree := schema.SchemaTree @@ -68,8 +68,8 @@ func processEntry(e *yang.Entry) *Element { return leaf } -// Strings constructs a slice containg all possible root to leaf paths. -// Calls stringBuilder internally +// Strings constructs a slice containing all possible root to leaf paths. +// Calls stringBuilder internally. func Strings(paths map[string]*Element) []string { ch := make(chan string) stop := make(chan bool) diff --git a/controller/nucleus/util/pluginVariables.go b/controller/nucleus/util/pluginVariables.go index dc1851885c94a75aad4ab0c2a4e7f47f8c021a70..27d876432384af855d766fd8e8b351d8523dfdc2 100644 --- a/controller/nucleus/util/pluginVariables.go +++ b/controller/nucleus/util/pluginVariables.go @@ -2,15 +2,15 @@ package util const ( // GoStructName references the name of a generated gostruct file that has - // been requested while creating a new device of type plugin/csbi + // been requested while creating a new device of type plugin/csbi. GoStructName string = "gostructs.go" // ManifestFileName references the name of a manifest file that has been - // requested while creating a new device of type plugin/csbi + // requested while creating a new device of type plugin/csbi. ManifestFileName string = "plugin.yml" // GoStructAdditionsName references the name of a additional file // containing the sbi specific methods. It is provided in the process of - // creating a new device of type plugin/csbi + // creating a new device of type plugin/csbi. GoStructAdditionsName string = "csbiAdditions.go" - // PluginOutputName references the name of a generated plugin + // PluginOutputName references the name of a generated plugin. PluginOutputName string = "plugin.so" ) diff --git a/controller/nucleus/util/proto/message.go b/controller/nucleus/util/proto/message.go index cda7787d7ebf80b0ea1ca936deef79d995dc3d6a..96db7baec12707ef25dafe3a8661b6ead0c3cd91 100644 --- a/controller/nucleus/util/proto/message.go +++ b/controller/nucleus/util/proto/message.go @@ -12,7 +12,7 @@ import ( Copycat source: https://dev.to/techschoolguru/go-generate-serialize-protobuf-message-4m7a */ -// Write writes protocol buffer message to binary file +// Write writes protocol buffer message to binary file. func Write(message proto.Message, filename string) error { data, err := proto.Marshal(message) if err != nil { @@ -28,7 +28,7 @@ func Write(message proto.Message, filename string) error { } // Read reads a binary file (containing a marshaled protocol buffer message) -// and unmarshals it back into a protocol buffer message +// and unmarshals it back into a protocol buffer message. func Read(filename string, message proto.Message) error { data, err := ioutil.ReadFile(filepath.Clean(filename)) if err != nil { diff --git a/controller/rbac/databaseRoleStore.go b/controller/rbac/databaseRoleStore.go index 78044d11e07dd637493fa304cb15537705a0da9b..871edf47e2401487e8c636fef35af586f085e155 100644 --- a/controller/rbac/databaseRoleStore.go +++ b/controller/rbac/databaseRoleStore.go @@ -1,6 +1,8 @@ package rbac import ( + "fmt" + "code.fbi.h-da.de/danet/gosdn/controller/interfaces/rbac" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/database" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors" @@ -13,18 +15,23 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" ) -// DatabaseRoleStore is used to store roles in database +// DatabaseRoleStore is used to store roles in database. type DatabaseRoleStore struct { roleStoreName string } // Add adds a Role. -func (s *DatabaseRoleStore) Add(roleToAdd rbac.Role) error { +func (s *DatabaseRoleStore) Add(roleToAdd rbac.Role) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.roleStoreName). InsertOne(ctx, roleToAdd) if err != nil { @@ -39,12 +46,17 @@ func (s *DatabaseRoleStore) Add(roleToAdd rbac.Role) error { } // Delete deletes a Role. -func (s *DatabaseRoleStore) Delete(roleToDelete rbac.Role) error { +func (s *DatabaseRoleStore) Delete(roleToDelete rbac.Role) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.roleStoreName). DeleteOne(ctx, bson.D{primitive.E{Key: "_id", Value: roleToDelete.ID().String()}}) if err != nil { @@ -76,12 +88,15 @@ func (s *DatabaseRoleStore) Get(query store.Query) (rbac.LoadedRole, error) { return loadedRole, nil } -func (s *DatabaseRoleStore) getByID(idOfRole uuid.UUID) (rbac.LoadedRole, error) { - var loadedRole rbac.LoadedRole - +func (s *DatabaseRoleStore) getByID(idOfRole uuid.UUID) (loadedRole rbac.LoadedRole, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.roleStoreName) @@ -90,7 +105,7 @@ func (s *DatabaseRoleStore) getByID(idOfRole uuid.UUID) (rbac.LoadedRole, error) return loadedRole, errors.ErrCouldNotFind{ID: idOfRole} } - err := result.Decode(&loadedRole) + err = result.Decode(&loadedRole) if err != nil { log.Printf("Failed marshalling %v", err) return loadedRole, errors.ErrCouldNotMarshall{Identifier: idOfRole, Type: loadedRole, Err: err} @@ -99,12 +114,15 @@ func (s *DatabaseRoleStore) getByID(idOfRole uuid.UUID) (rbac.LoadedRole, error) return loadedRole, nil } -func (s *DatabaseRoleStore) getByName(nameOfRole string) (rbac.LoadedRole, error) { - var loadedRole rbac.LoadedRole - +func (s *DatabaseRoleStore) getByName(nameOfRole string) (loadedRole rbac.LoadedRole, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.roleStoreName) @@ -113,7 +131,7 @@ func (s *DatabaseRoleStore) getByName(nameOfRole string) (rbac.LoadedRole, error return loadedRole, errors.ErrCouldNotFind{Name: nameOfRole} } - err := result.Decode(&loadedRole) + err = result.Decode(&loadedRole) if err != nil { log.Printf("Failed marshalling %v", err) return loadedRole, errors.ErrCouldNotMarshall{Identifier: nameOfRole, Type: loadedRole, Err: err} @@ -123,12 +141,16 @@ func (s *DatabaseRoleStore) getByName(nameOfRole string) (rbac.LoadedRole, error } // GetAll returns all Roles. -func (s *DatabaseRoleStore) GetAll() ([]rbac.LoadedRole, error) { - var loadedRoles []rbac.LoadedRole - +func (s *DatabaseRoleStore) GetAll() (loadedRoles []rbac.LoadedRole, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() + db := client.Database(database.DatabaseName) collection := db.Collection(s.roleStoreName) @@ -136,7 +158,12 @@ func (s *DatabaseRoleStore) GetAll() ([]rbac.LoadedRole, error) { if err != nil { return nil, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedRoles) if err != nil { @@ -147,14 +174,18 @@ func (s *DatabaseRoleStore) GetAll() ([]rbac.LoadedRole, error) { return loadedRoles, nil } -// Update updates the role -func (s *DatabaseRoleStore) Update(roleToUpdate rbac.Role) error { +// Update updates the role. +func (s *DatabaseRoleStore) Update(roleToUpdate rbac.Role) (err error) { var updatedLoadedRole rbac.LoadedRole client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) - + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() update := bson.D{primitive.E{Key: "$set", Value: roleToUpdate}} upsert := false @@ -164,7 +195,7 @@ func (s *DatabaseRoleStore) Update(roleToUpdate rbac.Role) error { ReturnDocument: &after, } - err := client.Database(database.DatabaseName). + err = client.Database(database.DatabaseName). Collection(s.roleStoreName). FindOneAndUpdate( ctx, bson.M{"_id": roleToUpdate.ID().String()}, update, &opt). diff --git a/controller/rbac/databaseUserStore.go b/controller/rbac/databaseUserStore.go index 0d2cd069343661bdcc640531128f0c8b96f81779..b1f6eeee754ddf193e67a0939c9fe818a57678d8 100644 --- a/controller/rbac/databaseUserStore.go +++ b/controller/rbac/databaseUserStore.go @@ -1,6 +1,8 @@ package rbac import ( + "fmt" + "code.fbi.h-da.de/danet/gosdn/controller/interfaces/rbac" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/database" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors" @@ -13,18 +15,23 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" ) -// DatabaseUserStore is used to store users in database +// DatabaseUserStore is used to store users in database. type DatabaseUserStore struct { userStoreName string } // Add adds an User. -func (s *DatabaseUserStore) Add(userToAdd rbac.User) error { +func (s *DatabaseUserStore) Add(userToAdd rbac.User) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.userStoreName). InsertOne(ctx, userToAdd) if err != nil { @@ -39,12 +46,17 @@ func (s *DatabaseUserStore) Add(userToAdd rbac.User) error { } // Delete deletes an User. -func (s *DatabaseUserStore) Delete(userToDelete rbac.User) error { +func (s *DatabaseUserStore) Delete(userToDelete rbac.User) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.userStoreName). DeleteOne(ctx, bson.D{primitive.E{Key: "_id", Value: userToDelete.ID().String()}}) if err != nil { @@ -76,12 +88,15 @@ func (s *DatabaseUserStore) Get(query store.Query) (rbac.LoadedUser, error) { return loadedUser, nil } -func (s *DatabaseUserStore) getByID(idOfUser uuid.UUID) (rbac.LoadedUser, error) { - var loadedUser rbac.LoadedUser - +func (s *DatabaseUserStore) getByID(idOfUser uuid.UUID) (loadedUser rbac.LoadedUser, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.userStoreName) @@ -90,7 +105,7 @@ func (s *DatabaseUserStore) getByID(idOfUser uuid.UUID) (rbac.LoadedUser, error) return loadedUser, errors.ErrCouldNotFind{ID: idOfUser} } - err := result.Decode(&loadedUser) + err = result.Decode(&loadedUser) if err != nil { log.Printf("Failed marshalling %v", err) return loadedUser, errors.ErrCouldNotMarshall{Identifier: idOfUser, Type: loadedUser, Err: err} @@ -99,12 +114,15 @@ func (s *DatabaseUserStore) getByID(idOfUser uuid.UUID) (rbac.LoadedUser, error) return loadedUser, nil } -func (s *DatabaseUserStore) getByName(nameOfUser string) (rbac.LoadedUser, error) { - var loadedUser rbac.LoadedUser - +func (s *DatabaseUserStore) getByName(nameOfUser string) (loadedUser rbac.LoadedUser, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.userStoreName) @@ -113,7 +131,7 @@ func (s *DatabaseUserStore) getByName(nameOfUser string) (rbac.LoadedUser, error return loadedUser, errors.ErrCouldNotFind{Name: nameOfUser} } - err := result.Decode(&loadedUser) + err = result.Decode(&loadedUser) if err != nil { log.Printf("Failed marshalling %v", err) return loadedUser, errors.ErrCouldNotMarshall{Identifier: nameOfUser, Type: loadedUser, Err: err} @@ -122,13 +140,17 @@ func (s *DatabaseUserStore) getByName(nameOfUser string) (rbac.LoadedUser, error return loadedUser, nil } -// GetAll returns all Users -func (s *DatabaseUserStore) GetAll() ([]rbac.LoadedUser, error) { - var loadedUsers []rbac.LoadedUser - +// GetAll returns all Users. +func (s *DatabaseUserStore) GetAll() (loadedUsers []rbac.LoadedUser, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() + db := client.Database(database.DatabaseName) collection := db.Collection(s.userStoreName) @@ -136,7 +158,12 @@ func (s *DatabaseUserStore) GetAll() ([]rbac.LoadedUser, error) { if err != nil { return nil, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedUsers) if err != nil { @@ -148,12 +175,17 @@ func (s *DatabaseUserStore) GetAll() ([]rbac.LoadedUser, error) { } // Update updates the User. -func (s *DatabaseUserStore) Update(userToUpdate rbac.User) error { +func (s *DatabaseUserStore) Update(userToUpdate rbac.User) (err error) { var updatedLoadedUser rbac.LoadedUser client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() update := bson.D{primitive.E{Key: "$set", Value: userToUpdate}} @@ -164,7 +196,7 @@ func (s *DatabaseUserStore) Update(userToUpdate rbac.User) error { ReturnDocument: &after, } - err := client.Database(database.DatabaseName). + err = client.Database(database.DatabaseName). Collection(s.userStoreName). FindOneAndUpdate( ctx, bson.M{"_id": userToUpdate.ID().String()}, update, &opt). diff --git a/controller/rbac/rbacService.go b/controller/rbac/rbacService.go index 72f9f9127563757ae4ff1c102a6cb72dd6b0bae9..a2b4a288ca6cabd9f72d0989575b9cf8aba9a54b 100644 --- a/controller/rbac/rbacService.go +++ b/controller/rbac/rbacService.go @@ -7,6 +7,7 @@ import ( "github.com/google/uuid" eventInterfaces "code.fbi.h-da.de/danet/gosdn/controller/interfaces/event" + log "github.com/sirupsen/logrus" ) const ( @@ -39,7 +40,9 @@ func (s *UserService) Add(userToAdd rbac.User) error { return err } - s.eventService.PublishEvent(UserEventTopic, event.NewAddEvent(userToAdd.ID())) + if err := s.eventService.PublishEvent(UserEventTopic, event.NewAddEvent(userToAdd.ID())); err != nil { + log.Error(err) + } return nil } @@ -51,7 +54,9 @@ func (s *UserService) Delete(userToDelete rbac.User) error { return err } - s.eventService.PublishEvent(UserEventTopic, event.NewDeleteEvent(userToDelete.ID())) + if err := s.eventService.PublishEvent(UserEventTopic, event.NewDeleteEvent(userToDelete.ID())); err != nil { + log.Error(err) + } return nil } @@ -63,7 +68,9 @@ func (s *UserService) Update(userToUpdate rbac.User) error { return err } - s.eventService.PublishEvent(UserEventTopic, event.NewUpdateEvent(userToUpdate.ID())) + if err := s.eventService.PublishEvent(UserEventTopic, event.NewUpdateEvent(userToUpdate.ID())); err != nil { + log.Error(err) + } return nil } @@ -119,7 +126,9 @@ func (s *RoleService) Add(roleToAdd rbac.Role) error { return err } - s.eventService.PublishEvent(RoleEventTopic, event.NewAddEvent(roleToAdd.ID())) + if err := s.eventService.PublishEvent(RoleEventTopic, event.NewAddEvent(roleToAdd.ID())); err != nil { + log.Error(err) + } return nil } @@ -131,7 +140,9 @@ func (s *RoleService) Delete(roleToDelete rbac.Role) error { return err } - s.eventService.PublishEvent(RoleEventTopic, event.NewDeleteEvent(roleToDelete.ID())) + if err := s.eventService.PublishEvent(RoleEventTopic, event.NewDeleteEvent(roleToDelete.ID())); err != nil { + log.Error(err) + } return nil } @@ -143,7 +154,9 @@ func (s *RoleService) Update(roleToUpdate rbac.Role) error { return err } - s.eventService.PublishEvent(RoleEventTopic, event.NewUpdateEvent(roleToUpdate.ID())) + if err := s.eventService.PublishEvent(RoleEventTopic, event.NewUpdateEvent(roleToUpdate.ID())); err != nil { + log.Error(err) + } return nil } diff --git a/controller/rbac/role.go b/controller/rbac/role.go index a506247ac504f5a56c8013a85a0831da297512c0..0e7c01b14367ce8fd154cd03afe29a4cf5e50cc0 100644 --- a/controller/rbac/role.go +++ b/controller/rbac/role.go @@ -49,7 +49,7 @@ func (r Role) GetPermissions() []string { return r.Permissions } -// RemovePermissionsFromRole takes permissions that should be removed from a role and updates the current permissions accordingly +// RemovePermissionsFromRole takes permissions that should be removed from a role and updates the current permissions accordingly. func (r *Role) RemovePermissionsFromRole(permissionsToRemove []string) { for _, permToRemove := range permissionsToRemove { r.removePermissionFromRoles(permToRemove) @@ -65,7 +65,7 @@ func (r *Role) removePermissionFromRoles(permToRemove string) { } } -// MarshalJSON implements the MarshalJSON interface to store a role as JSON +// MarshalJSON implements the MarshalJSON interface to store a role as JSON. func (r *Role) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { RoleID uuid.UUID `json:"_id"` @@ -80,7 +80,7 @@ func (r *Role) MarshalJSON() ([]byte, error) { }) } -// MarshalBSON implments the MarshalBSON interface to store a role as BSON +// MarshalBSON implments the MarshalBSON interface to store a role as BSON. func (r *Role) MarshalBSON() ([]byte, error) { return bson.Marshal(&struct { RoleID string `bson:"_id"` diff --git a/controller/rbac/roleFileSystemStore.go b/controller/rbac/roleFileSystemStore.go index bcf381396f3f48e17d53a32845286fce784cf375..b6785cd66b8a5e499ca2b792bbc8a2db9079916d 100644 --- a/controller/rbac/roleFileSystemStore.go +++ b/controller/rbac/roleFileSystemStore.go @@ -8,9 +8,10 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/interfaces/rbac" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors" "code.fbi.h-da.de/danet/gosdn/controller/store" + log "github.com/sirupsen/logrus" ) -// FileSystemRoleStore is the filesystem implementation of the role store +// FileSystemRoleStore is the filesystem implementation of the role store. type FileSystemRoleStore struct { fileMutex sync.Mutex pathToRoleFile string @@ -18,7 +19,10 @@ type FileSystemRoleStore struct { // NewFileSystemRoleStore returns a filesystem implementation for a role store. func NewFileSystemRoleStore() rbac.RoleStore { - store.EnsureFilesystemStorePathExists(store.RoleFilename) + if err := store.EnsureFilesystemStorePathExists(store.RoleFilename); err != nil { + log.Error(err) + } + return &FileSystemRoleStore{ fileMutex: sync.Mutex{}, pathToRoleFile: store.GetCompletePathToFileStore(store.RoleFilename), @@ -54,7 +58,7 @@ func (s *FileSystemRoleStore) writeAllRolesToFile(roles []rbac.LoadedRole) error return nil } -// Add adds a Role to the Role store +// Add adds a Role to the Role store. func (s *FileSystemRoleStore) Add(roleToAdd rbac.Role) error { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -80,7 +84,7 @@ func (s *FileSystemRoleStore) Add(roleToAdd rbac.Role) error { return nil } -//Delete deletes a Role from the Role store +//Delete deletes a Role from the Role store. func (s *FileSystemRoleStore) Delete(roleToDelete rbac.Role) error { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -108,7 +112,7 @@ func (s *FileSystemRoleStore) Delete(roleToDelete rbac.Role) error { return &errors.ErrCouldNotDelete{Identifier: roleToDelete.ID(), Type: roleToDelete, Err: err} } -//Get takes a Roles ID and return the Role if found +//Get takes a Roles ID and return the Role if found. func (s *FileSystemRoleStore) Get(query store.Query) (rbac.LoadedRole, error) { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -128,7 +132,7 @@ func (s *FileSystemRoleStore) Get(query store.Query) (rbac.LoadedRole, error) { return role, &errors.ErrCouldNotFind{ID: query.ID, Name: query.Name} } -// GetAll returns all the Roles +// GetAll returns all the Roles. func (s *FileSystemRoleStore) GetAll() ([]rbac.LoadedRole, error) { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -137,7 +141,7 @@ func (s *FileSystemRoleStore) GetAll() ([]rbac.LoadedRole, error) { return Roles, err } -//Update updates an exsisting Role +//Update updates an exsisting Role. func (s *FileSystemRoleStore) Update(roleToUpdate rbac.Role) error { s.fileMutex.Lock() defer s.fileMutex.Unlock() diff --git a/controller/rbac/roleFileSystemStore_test.go b/controller/rbac/roleFileSystemStore_test.go index cfc033ee8b3dd537b7b4421c11e73ffa9b79a814..be1e55071ac23b815314f15f285b64b310b8f362 100644 --- a/controller/rbac/roleFileSystemStore_test.go +++ b/controller/rbac/roleFileSystemStore_test.go @@ -13,7 +13,9 @@ import ( ) func ensureRoleFilesForTestAreRemoved() { - store.EnsureFilesystemStorePathExists(store.RoleFilename) + if err := store.EnsureFilesystemStorePathExists(store.RoleFilename); err != nil { + log.Fatal(err) + } path := store.GetCompletePathToFileStore(store.RoleFilename) files, err := filepath.Glob(path) @@ -72,7 +74,9 @@ func TestFileSystemRoleStore_Delete(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := NewRoleStore() - s.Add(addRole) + if err := s.Add(addRole); err != nil { + t.Error(err) + } if err := s.Delete(tt.args.RoleToDelete); (err != nil) != tt.wantErr { t.Errorf("FileSystemRoleStore.Delete() error = %v, wantErr %v", err, tt.wantErr) } @@ -106,7 +110,9 @@ func TestFileSystemRoleStore_Get(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := NewRoleStore() - s.Add(addRole) + if err := s.Add(addRole); err != nil { + t.Error(err) + } got, err := s.Get(tt.args.query) if (err != nil) != tt.wantErr { t.Errorf("FileSystemRoleStore.Get() error = %v, wantErr %v", err, tt.wantErr) @@ -139,10 +145,22 @@ func TestFileSystemRoleStore_GetAll(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + var errs []error s := NewRoleStore() - s.Add(addRole1) - s.Add(addRole2) - s.Add(addRole3) + if err := s.Add(addRole1); err != nil { + errs = append(errs, err) + } + if err := s.Add(addRole2); err != nil { + errs = append(errs, err) + } + if err := s.Add(addRole3); err != nil { + errs = append(errs, err) + } + + if len(errs) > 0 { + t.Error(errs) + } + got, err := s.GetAll() if (err != nil) != tt.wantErr { t.Errorf("FileSystemRoleStore.GetAll() error = %v, wantErr %v", err, tt.wantErr) @@ -176,7 +194,9 @@ func TestFileSystemRoleStore_Update(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := NewRoleStore() - s.Add(addRole1) + if err := s.Add(addRole1); err != nil { + t.Error(err) + } if err := s.Update(tt.args.roleToUpdate); (err != nil) != tt.wantErr { t.Errorf("FileSystemRoleStore.Update() error = %v, wantErr %v", err, tt.wantErr) } diff --git a/controller/rbac/roleStore.go b/controller/rbac/roleStore.go index 908f8103397321f387229bbf2974f2873793f811..ad76beaa75e173ff92cddcb0d80c69597a29f401 100644 --- a/controller/rbac/roleStore.go +++ b/controller/rbac/roleStore.go @@ -5,7 +5,7 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/store" ) -// NewRoleStore returns a roleStore +// NewRoleStore returns a roleStore. func NewRoleStore() rbac.RoleStore { storeMode := store.GetStoreMode() diff --git a/controller/rbac/user.go b/controller/rbac/user.go index 52514adc5a52d55a63f89753c1f737f1424acc17..19d9dc4f6e3e7ba79fbd19821248e0ac3528d3df 100644 --- a/controller/rbac/user.go +++ b/controller/rbac/user.go @@ -60,12 +60,12 @@ func (u *User) GetToken() string { return u.Token } -// SetName sets the name of the user +// SetName sets the name of the user. func (u *User) SetName(name string) { u.UserName = name } -// SetToken sets the token of the user +// SetToken sets the token of the user. func (u *User) SetToken(token string) { u.Token = token } @@ -75,7 +75,7 @@ func (u *User) GetSalt() string { return u.Salt } -// MarshalJSON implements the MarshalJSON interface to store a user as JSON +// MarshalJSON implements the MarshalJSON interface to store a user as JSON. func (u *User) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { UserID uuid.UUID `json:"_id"` @@ -94,7 +94,7 @@ func (u *User) MarshalJSON() ([]byte, error) { }) } -// MarshalBSON implments the MarshalBSON interface to store a user as BSON +// MarshalBSON implments the MarshalBSON interface to store a user as BSON. func (u *User) MarshalBSON() ([]byte, error) { return bson.Marshal(&struct { UserID string `bson:"_id"` diff --git a/controller/rbac/userFileSystemStore.go b/controller/rbac/userFileSystemStore.go index 146ab0c5f6d717e9b0e860571b33b3ddcf6eb732..4c181842f6821e4e9e3ea843365a47815e1e8006 100644 --- a/controller/rbac/userFileSystemStore.go +++ b/controller/rbac/userFileSystemStore.go @@ -8,9 +8,10 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/interfaces/rbac" "code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors" "code.fbi.h-da.de/danet/gosdn/controller/store" + log "github.com/sirupsen/logrus" ) -// FileSystemUserStore is the filesystem implementation of the user store +// FileSystemUserStore is the filesystem implementation of the user store. type FileSystemUserStore struct { fileMutex sync.Mutex pathToUserFile string @@ -18,7 +19,10 @@ type FileSystemUserStore struct { // NewFileSystemUserStore returns a filesystem implementation for a user store. func NewFileSystemUserStore() rbac.UserStore { - store.EnsureFilesystemStorePathExists(store.UserFilename) + if err := store.EnsureFilesystemStorePathExists(store.UserFilename); err != nil { + log.Error(err) + } + return &FileSystemUserStore{ fileMutex: sync.Mutex{}, pathToUserFile: store.GetCompletePathToFileStore(store.UserFilename), @@ -54,7 +58,7 @@ func (s *FileSystemUserStore) writeAllUsersToFile(users []rbac.LoadedUser) error return nil } -// Add adds a User to the User store +// Add adds a User to the User store. func (s *FileSystemUserStore) Add(UserToAdd rbac.User) error { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -80,7 +84,7 @@ func (s *FileSystemUserStore) Add(UserToAdd rbac.User) error { return nil } -//Delete deletes a User from the User store +//Delete deletes a User from the User store. func (s *FileSystemUserStore) Delete(userToDelete rbac.User) error { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -108,7 +112,7 @@ func (s *FileSystemUserStore) Delete(userToDelete rbac.User) error { return &errors.ErrCouldNotDelete{Identifier: userToDelete.ID(), Type: userToDelete, Err: err} } -//Get takes a Users ID and return the User if found +//Get takes a Users ID and return the User if found. func (s *FileSystemUserStore) Get(query store.Query) (rbac.LoadedUser, error) { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -128,7 +132,7 @@ func (s *FileSystemUserStore) Get(query store.Query) (rbac.LoadedUser, error) { return user, &errors.ErrCouldNotFind{ID: query.ID, Name: query.Name} } -// GetAll returns all the Users +// GetAll returns all the Users. func (s *FileSystemUserStore) GetAll() ([]rbac.LoadedUser, error) { s.fileMutex.Lock() defer s.fileMutex.Unlock() @@ -137,7 +141,7 @@ func (s *FileSystemUserStore) GetAll() ([]rbac.LoadedUser, error) { return Users, err } -//Update updates an exsisting user +//Update updates an exsisting user. func (s *FileSystemUserStore) Update(userToUpdate rbac.User) error { s.fileMutex.Lock() defer s.fileMutex.Unlock() diff --git a/controller/rbac/userFileSystemStore_test.go b/controller/rbac/userFileSystemStore_test.go index 4261e982ec15079bfee2240858fba617e724a21e..d5f88cc2514f50ee4872570ad8b257245060b1be 100644 --- a/controller/rbac/userFileSystemStore_test.go +++ b/controller/rbac/userFileSystemStore_test.go @@ -13,7 +13,10 @@ import ( ) func ensureUserFilesForTestAreRemoved() { - store.EnsureFilesystemStorePathExists(store.UserFilename) + if err := store.EnsureFilesystemStorePathExists(store.UserFilename); err != nil { + log.Fatal(err) + } + path := store.GetCompletePathToFileStore(store.UserFilename) files, err := filepath.Glob(path) @@ -82,7 +85,9 @@ func TestFileSystemUserStore_Delete(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := NewUserStore() - s.Add(testingUser) + if err := s.Add(testingUser); err != nil { + t.Error(err) + } if err := s.Delete(tt.args.UserToDelete); (err != nil) != tt.wantErr { t.Errorf("FileSystemUserStore.Delete() error = %v, wantErr %v", err, tt.wantErr) } @@ -117,7 +122,9 @@ func TestFileSystemUserStore_Get(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := NewUserStore() - s.Add(testingUser) + if err := s.Add(testingUser); err != nil { + t.Error(err) + } got, err := s.Get(tt.args.query) if (err != nil) != tt.wantErr { t.Errorf("FileSystemUserStore.Get() error = %v, wantErr %v", err, tt.wantErr) @@ -151,10 +158,22 @@ func TestFileSystemUserStore_GetAll(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + var errs []error s := NewUserStore() - s.Add(testingUser1) - s.Add(testingUser2) - s.Add(testingUser3) + if err := s.Add(testingUser1); err != nil { + errs = append(errs, err) + } + if err := s.Add(testingUser2); err != nil { + errs = append(errs, err) + } + if err := s.Add(testingUser3); err != nil { + errs = append(errs, err) + } + + if len(errs) > 0 { + t.Error(errs) + } + got, err := s.GetAll() if (err != nil) != tt.wantErr { t.Errorf("FileSystemUserStore.GetAll() error = %v, wantErr %v", err, tt.wantErr) @@ -192,7 +211,9 @@ func TestFileSystemUserStore_Update(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := NewUserStore() - s.Add(testingUser) + if err := s.Add(testingUser); err != nil { + t.Error(err) + } if err := s.Update(tt.args.userToUpdate); (err != nil) != tt.wantErr { t.Errorf("FileSystemUserStore.Update() error = %v, wantErr %v", err, tt.wantErr) } diff --git a/controller/rbac/userStore.go b/controller/rbac/userStore.go index f9f646b3baebf9dda0cd66eabf6b1701eee0b22e..48e6c861802f09382cd9e196dedefc418c48e05b 100644 --- a/controller/rbac/userStore.go +++ b/controller/rbac/userStore.go @@ -5,7 +5,7 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/store" ) -// NewUserStore returns a userStore +// NewUserStore returns a userStore. func NewUserStore() rbac.UserStore { storeMode := store.GetStoreMode() diff --git a/controller/store/changeStores.go b/controller/store/changeStores.go index 8b07a09c4b436d40a43c57ad1ab7c6ea32807eac..3b38a6e001771fd50a193191c20c590a32a1c812 100644 --- a/controller/store/changeStores.go +++ b/controller/store/changeStores.go @@ -9,12 +9,12 @@ import ( ppb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/pnd" ) -// ChangeStore is used to store Changes +// ChangeStore is used to store Changes. type ChangeStore struct { *genericStore } -// NewChangeStore returns a ChangeStore +// NewChangeStore returns a ChangeStore. func NewChangeStore() *ChangeStore { return &ChangeStore{genericStore: newGenericStore()} } @@ -39,17 +39,17 @@ func (s *ChangeStore) GetChange(id uuid.UUID) (change.Change, error) { return c, nil } -// Pending returns the UUIDs of all pending changes +// Pending returns the UUIDs of all pending changes. func (s *ChangeStore) Pending() []uuid.UUID { return filterChanges(s, ppb.ChangeState_CHANGE_STATE_PENDING) } -// Committed returns the UUIDs of all pending changes +// Committed returns the UUIDs of all pending changes. func (s *ChangeStore) Committed() []uuid.UUID { return filterChanges(s, ppb.ChangeState_CHANGE_STATE_COMMITTED) } -// Confirmed returns the UUIDs of all pending changes +// Confirmed returns the UUIDs of all pending changes. func (s *ChangeStore) Confirmed() []uuid.UUID { return filterChanges(s, ppb.ChangeState_CHANGE_STATE_CONFIRMED) } diff --git a/controller/store/filesystem-settings.go b/controller/store/filesystem-settings.go index 5a23dd0b9f54d556b795ec0c5ec6a7cac248980f..cba093e64af2b7ebde453dfc6e553f80bbb2d3b7 100644 --- a/controller/store/filesystem-settings.go +++ b/controller/store/filesystem-settings.go @@ -1,14 +1,14 @@ package store const ( - // PndFilename is the name of the file where the pnds are stored + // PndFilename is the name of the file where the pnds are stored. PndFilename string = "pndStore.json" - // DeviceFilenameSuffix is the suffix of the file where the devices are stored + // DeviceFilenameSuffix is the suffix of the file where the devices are stored. DeviceFilenameSuffix string = "deviceStore.json" - // SbiFilenameSuffix is the suffix of the file where the sbis are stored + // SbiFilenameSuffix is the suffix of the file where the sbis are stored. SbiFilenameSuffix string = "sbiStore.json" - // UserFilename is the name of the file where the users are stored + // UserFilename is the name of the file where the users are stored. UserFilename string = "userStore.json" - // RoleFilename is the name of the file where the roles are stored + // RoleFilename is the name of the file where the roles are stored. RoleFilename string = "roleStore.json" ) diff --git a/controller/store/initialise_test.go b/controller/store/initialise_test.go index 732bad161a89a0fe8a7d9b7e92bf261a027e6031..894d994b3a15c6aaca8ec41c35dbd5091a78ecb0 100644 --- a/controller/store/initialise_test.go +++ b/controller/store/initialise_test.go @@ -8,7 +8,7 @@ import ( log "github.com/sirupsen/logrus" ) -// UUIDs for test cases +// UUIDs for test cases. var mdid uuid.UUID var defaultPndID uuid.UUID var cuid uuid.UUID diff --git a/controller/store/oldGenericStore.go b/controller/store/oldGenericStore.go index 19ab0cc7bc959f621029d0f3cfbef51a926d6973..a08d8c628efd5b5406847e29cb2cd60efff7870d 100644 --- a/controller/store/oldGenericStore.go +++ b/controller/store/oldGenericStore.go @@ -11,7 +11,7 @@ import ( log "github.com/sirupsen/logrus" ) -// newGenericStore returns a genericStore +// newGenericStore returns a genericStore. func newGenericStore() *genericStore { return &genericStore{Store: make(map[uuid.UUID]store.Storable), storeLock: sync.RWMutex{}} } @@ -29,7 +29,7 @@ func (s *genericStore) Exists(id uuid.UUID) bool { return ok } -// Add adds a Storable to the Store +// Add adds a Storable to the Store. func (s *genericStore) Add(item store.Storable) error { if s.Exists(item.ID()) { return &errors.ErrAlreadyExists{Item: item} diff --git a/controller/store/storageMode.go b/controller/store/storageMode.go index bd295dc345afdbfcf056fe36af5de060300da800..7cc86367e240918583855e5d5865626b79f84c34 100644 --- a/controller/store/storageMode.go +++ b/controller/store/storageMode.go @@ -6,11 +6,11 @@ import "code.fbi.h-da.de/danet/gosdn/controller/config" type StorageMode int64 const ( - // Memory is the default storage mode + // Memory is the default storage mode. Memory StorageMode = iota - // Filesystem is a persistent storage mode + // Filesystem is a persistent storage mode. Filesystem - // Database is a persistent storage mode provided by a database + // Database is a persistent storage mode provided by a database. Database ) diff --git a/controller/store/utils.go b/controller/store/utils.go index 769889c7c27d59d201ffed3eb4a0aaf796e989d8..b6866b6cb994ce377aa9f6da3f3746051b812628 100644 --- a/controller/store/utils.go +++ b/controller/store/utils.go @@ -27,7 +27,7 @@ func FromString(id string) (uuid.UUID, error) { return idAsUUID, nil } -//EnsureFilesystemStorePathExists ensures that the filesystem store path exists +//EnsureFilesystemStorePathExists ensures that the filesystem store path exists. func EnsureFilesystemStorePathExists(storeFileName string) error { completeStorePath := filepath.Join(config.FilesystemPathToStores, storeFileName) if _, err := os.Stat(completeStorePath); os.IsNotExist(err) { @@ -67,12 +67,12 @@ func ensureDirExists(fileName string) error { return nil } -//GetCompletePathToFileStore gets the complete path to a file store +//GetCompletePathToFileStore gets the complete path to a file store. func GetCompletePathToFileStore(storeName string) string { return filepath.Join(config.FilesystemPathToStores, storeName) } -//TransformObjectToLoadedObject transform an object into an loadedObject +//TransformObjectToLoadedObject transform an object into an loadedObject. func TransformObjectToLoadedObject[T, R any](object T) (R, error) { var loadedObject R @@ -89,7 +89,7 @@ func TransformObjectToLoadedObject[T, R any](object T) (R, error) { return loadedObject, err } -//GetStoreFilenameForUUID returns the full filename for a given pndUUID and suffix +//GetStoreFilenameForUUID returns the full filename for a given pndUUID and suffix. func GetStoreFilenameForUUID(pndUUID uuid.UUID, deviceFilenameSuffix string) string { return pndUUID.String() + "-" + deviceFilenameSuffix } diff --git a/controller/topology/links/link.go b/controller/topology/links/link.go index b90faf44acb9f65ab9fe0acef0fee4a4d937da18..be6a79d06441cd71129f75ba24464d1afdcd5154 100644 --- a/controller/topology/links/link.go +++ b/controller/topology/links/link.go @@ -6,7 +6,7 @@ import ( "github.com/google/uuid" ) -// Link is a representation of a physical or virtual link between two nodes and their ports +// Link is a representation of a physical or virtual link between two nodes and their ports. type Link struct { ID uuid.UUID `bson:"_id"` Name string `bson:"name,omitempty"` @@ -16,7 +16,7 @@ type Link struct { TargetPort ports.Port `bson:"target_port,omitempty"` } -// GetID returns the id of a link +// GetID returns the id of a link. func (l Link) GetID() uuid.UUID { return l.ID } diff --git a/controller/topology/nodes/node.go b/controller/topology/nodes/node.go index 02ec4ac680cd69877ab1e0fb192a12b40444f454..a9c836fcd8e316bb3b74f31d7ae894c9c718a630 100644 --- a/controller/topology/nodes/node.go +++ b/controller/topology/nodes/node.go @@ -4,13 +4,13 @@ import ( "github.com/google/uuid" ) -// Node is a representation of a network element +// Node is a representation of a network element. type Node struct { ID uuid.UUID `bson:"_id"` Name string `bson:"name"` } -// GetID returns the id of a node +// GetID returns the id of a node. func (n Node) GetID() uuid.UUID { return n.ID } diff --git a/controller/topology/nodes/nodeService.go b/controller/topology/nodes/nodeService.go index 9e7f73a1db6dc65f9348d27c902608308d34647c..76e2de209bc13eafecaf5989178433a405ea531b 100644 --- a/controller/topology/nodes/nodeService.go +++ b/controller/topology/nodes/nodeService.go @@ -6,14 +6,15 @@ import ( query "code.fbi.h-da.de/danet/gosdn/controller/store" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) const ( - // NodeEventTopic is the used topic for node related entity changes + // NodeEventTopic is the used topic for node related entity changes. NodeEventTopic = "node" ) -// Service defines a interface for a NodeService +// Service defines a interface for a NodeService. type Service interface { EnsureExists(Node) (Node, error) Update(Node) error @@ -22,13 +23,13 @@ type Service interface { GetAll() ([]Node, error) } -// NodeService is a NodeService +// NodeService is a NodeService. type NodeService struct { store Store eventService eventInterfaces.Service } -// NewNodeService creates a NodeService +// NewNodeService creates a NodeService. func NewNodeService(store Store, eventService eventInterfaces.Service) Service { return &NodeService{ store: store, @@ -36,7 +37,7 @@ func NewNodeService(store Store, eventService eventInterfaces.Service) Service { } } -// EnsureExists either creates a new node or returns an already existing node +// EnsureExists either creates a new node or returns an already existing node. func (n *NodeService) EnsureExists(node Node) (Node, error) { if node.ID == uuid.Nil { node.ID = uuid.New() @@ -59,36 +60,42 @@ func (n *NodeService) createNode(node Node) (Node, error) { return node, err } - n.eventService.PublishEvent(NodeEventTopic, event.NewAddEvent(node.ID)) + if err := n.eventService.PublishEvent(NodeEventTopic, event.NewAddEvent(node.ID)); err != nil { + log.Error(err) + } return node, nil } -// Update updates an existing node +// Update updates an existing node. func (n *NodeService) Update(node Node) error { err := n.store.Update(node) if err != nil { return err } - n.eventService.PublishEvent(NodeEventTopic, event.NewUpdateEvent(node.ID)) + if err := n.eventService.PublishEvent(NodeEventTopic, event.NewUpdateEvent(node.ID)); err != nil { + log.Error(err) + } return nil } -// Delete deletes a node +// Delete deletes a node. func (n *NodeService) Delete(node Node) error { err := n.store.Delete(node) if err != nil { return err } - n.eventService.PublishEvent(NodeEventTopic, event.NewDeleteEvent(node.ID)) + if err := n.eventService.PublishEvent(NodeEventTopic, event.NewDeleteEvent(node.ID)); err != nil { + log.Error(err) + } return nil } -// Get gets a node +// Get gets a node. func (n *NodeService) Get(query query.Query) (Node, error) { node, err := n.store.Get(query) if err != nil { @@ -98,7 +105,7 @@ func (n *NodeService) Get(query query.Query) (Node, error) { return node, nil } -// GetAll gets all existing nodes +// GetAll gets all existing nodes. func (n *NodeService) GetAll() ([]Node, error) { nodes, err := n.store.GetAll() if err != nil { diff --git a/controller/topology/nodes/nodeStore.go b/controller/topology/nodes/nodeStore.go index a4f6f3123d7aab5e27f1a880e00d0a8c77073ffb..3f69c80d0671c8548a3ca1656ca57867cec9b231 100644 --- a/controller/topology/nodes/nodeStore.go +++ b/controller/topology/nodes/nodeStore.go @@ -13,7 +13,7 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" ) -// Store defines a NodeStore interface +// Store defines a NodeStore interface. type Store interface { Add(Node) error Update(Node) error @@ -22,15 +22,15 @@ type Store interface { GetAll() ([]Node, error) } -// DatabaseNodeStore is a database store for nodes +// DatabaseNodeStore is a database store for nodes. type DatabaseNodeStore struct { storeName string } -// NewDatabaseNodeStore returns a NodeStore +// NewDatabaseNodeStore returns a NodeStore. func NewDatabaseNodeStore() Store { return &DatabaseNodeStore{ - storeName: fmt.Sprintf("node-store.json"), + storeName: fmt.Sprint("node-store.json"), } } @@ -55,12 +55,15 @@ func (s *DatabaseNodeStore) Get(query query.Query) (Node, error) { return loadedNode, nil } -func (s *DatabaseNodeStore) getByID(idOfNode uuid.UUID) (Node, error) { - var loadedNode Node - +func (s *DatabaseNodeStore) getByID(idOfNode uuid.UUID) (loadedNode Node, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() idAsByteArray, _ := idOfNode.MarshalBinary() @@ -71,7 +74,7 @@ func (s *DatabaseNodeStore) getByID(idOfNode uuid.UUID) (Node, error) { return loadedNode, errors.ErrCouldNotFind{ID: idOfNode} } - err := result.Decode(&loadedNode) + err = result.Decode(&loadedNode) if err != nil { return loadedNode, errors.ErrCouldNotMarshall{Identifier: idOfNode, Type: loadedNode, Err: err} } @@ -79,12 +82,15 @@ func (s *DatabaseNodeStore) getByID(idOfNode uuid.UUID) (Node, error) { return loadedNode, nil } -func (s *DatabaseNodeStore) getByName(nameOfNode string) (Node, error) { - var loadedNode Node - +func (s *DatabaseNodeStore) getByName(nameOfNode string) (loadedNode Node, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -93,7 +99,7 @@ func (s *DatabaseNodeStore) getByName(nameOfNode string) (Node, error) { return loadedNode, errors.ErrCouldNotFind{Name: nameOfNode} } - err := result.Decode(&loadedNode) + err = result.Decode(&loadedNode) if err != nil { return loadedNode, errors.ErrCouldNotMarshall{Identifier: nameOfNode, Type: loadedNode, Err: err} } @@ -102,12 +108,15 @@ func (s *DatabaseNodeStore) getByName(nameOfNode string) (Node, error) { } // GetAll returns all stored nodes. -func (s *DatabaseNodeStore) GetAll() ([]Node, error) { - var loadedNode []Node - +func (s *DatabaseNodeStore) GetAll() (loadedNode []Node, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -115,7 +124,12 @@ func (s *DatabaseNodeStore) GetAll() ([]Node, error) { if err != nil { return []Node{}, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedNode) if err != nil { @@ -126,12 +140,17 @@ func (s *DatabaseNodeStore) GetAll() ([]Node, error) { } // Add adds a node to the node store. -func (s *DatabaseNodeStore) Add(node Node) error { +func (s *DatabaseNodeStore) Add(node Node) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.storeName). InsertOne(ctx, node) if err != nil { @@ -142,12 +161,17 @@ func (s *DatabaseNodeStore) Add(node Node) error { } // Update updates a existing node. -func (s *DatabaseNodeStore) Update(node Node) error { +func (s *DatabaseNodeStore) Update(node Node) (err error) { var updatedLoadedNodes Node client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() update := bson.D{primitive.E{Key: "$set", Value: node}} @@ -158,7 +182,7 @@ func (s *DatabaseNodeStore) Update(node Node) error { ReturnDocument: &after, } - err := client.Database(database.DatabaseName). + err = client.Database(database.DatabaseName). Collection(s.storeName). FindOneAndUpdate( ctx, bson.M{"_id": node.ID.String()}, update, &opt). @@ -171,14 +195,19 @@ func (s *DatabaseNodeStore) Update(node Node) error { } // Delete deletes a node from the node store. -func (s *DatabaseNodeStore) Delete(node Node) error { +func (s *DatabaseNodeStore) Delete(node Node) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) - _, err := collection.DeleteOne(ctx, bson.D{primitive.E{Key: node.ID.String()}}) + _, err = collection.DeleteOne(ctx, bson.D{primitive.E{Key: node.ID.String()}}) if err != nil { return err } diff --git a/controller/topology/ports/configuration/configuration.go b/controller/topology/ports/configuration/configuration.go index cc22dd09212a4ea8c9c751f372a1b7eb27a96715..e61f512f64fafaeb49aec3c37b3dc6f37651bb75 100644 --- a/controller/topology/ports/configuration/configuration.go +++ b/controller/topology/ports/configuration/configuration.go @@ -5,13 +5,13 @@ import ( "net" ) -// IPConfig represents an interface configuration for a cEOS instance +// IPConfig represents an interface configuration for a cEOS instance. type IPConfig struct { IP net.IP `bson:"ip,omitempty"` PrefixLength int64 `bson:"prefix_length,omitempty"` } -// New creates a new IPConfig +// New creates a new IPConfig. func New(ip string, prefixLength int64) (IPConfig, error) { newIPConfig := IPConfig{} parsedIP := net.ParseIP(ip) diff --git a/controller/topology/ports/port.go b/controller/topology/ports/port.go index e7456af6f65a9857b78b34262a4bd524a4bc7247..2614f745c574a221f79974eaa95f11217a828187 100644 --- a/controller/topology/ports/port.go +++ b/controller/topology/ports/port.go @@ -5,14 +5,14 @@ import ( "github.com/google/uuid" ) -// Port is a representation of physical port on a network element +// Port is a representation of physical port on a network element. type Port struct { ID uuid.UUID `bson:"_id"` Name string `bson:"name,omitempty"` Configuration configuration.IPConfig `bson:"configuration,omitempty"` } -// GetID returns the id of a port +// GetID returns the id of a port. func (p Port) GetID() uuid.UUID { return p.ID } diff --git a/controller/topology/ports/portService.go b/controller/topology/ports/portService.go index c092d6ada904486631eb111a9dd6b95663c1bd53..1625155a0cb1f4578be24b70186fd36622b17290 100644 --- a/controller/topology/ports/portService.go +++ b/controller/topology/ports/portService.go @@ -6,14 +6,15 @@ import ( query "code.fbi.h-da.de/danet/gosdn/controller/store" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) const ( - // PortEventTopic is the used topic for port related entity changes + // PortEventTopic is the used topic for port related entity changes. PortEventTopic = "port" ) -// Service defines an interface for a PortService +// Service defines an interface for a PortService. type Service interface { EnsureExists(Port) (Port, error) Update(Port) error @@ -22,13 +23,13 @@ type Service interface { GetAll() ([]Port, error) } -// PortService is a service for ports +// PortService is a service for ports. type PortService struct { store Store eventService eventInterfaces.Service } -// NewPortService creates a new PortService +// NewPortService creates a new PortService. func NewPortService(store Store, eventService eventInterfaces.Service) Service { return &PortService{ store: store, @@ -36,7 +37,7 @@ func NewPortService(store Store, eventService eventInterfaces.Service) Service { } } -// EnsureExists either creates a new port or returns an already existing port +// EnsureExists either creates a new port or returns an already existing port. func (p *PortService) EnsureExists(port Port) (Port, error) { if port.ID == uuid.Nil { port.ID = uuid.New() @@ -57,36 +58,42 @@ func (p *PortService) createPort(port Port) (Port, error) { return port, err } - p.eventService.PublishEvent(PortEventTopic, event.NewAddEvent(port.ID)) + if err := p.eventService.PublishEvent(PortEventTopic, event.NewAddEvent(port.ID)); err != nil { + log.Error(err) + } return port, nil } -// Update updates an existing port +// Update updates an existing port. func (p *PortService) Update(port Port) error { err := p.store.Update(port) if err != nil { return err } - p.eventService.PublishEvent(PortEventTopic, event.NewUpdateEvent(port.ID)) + if err := p.eventService.PublishEvent(PortEventTopic, event.NewUpdateEvent(port.ID)); err != nil { + log.Error(err) + } return nil } -// Delete deletes a port +// Delete deletes a port. func (p *PortService) Delete(port Port) error { err := p.store.Delete(port) if err != nil { return err } - p.eventService.PublishEvent(PortEventTopic, event.NewDeleteEvent(port.ID)) + if err := p.eventService.PublishEvent(PortEventTopic, event.NewDeleteEvent(port.ID)); err != nil { + log.Error(err) + } return nil } -// Get gets a port +// Get gets a port. func (p *PortService) Get(query query.Query) (Port, error) { port, err := p.store.Get(query) if err != nil { @@ -96,7 +103,7 @@ func (p *PortService) Get(query query.Query) (Port, error) { return port, nil } -// GetAll gets all existing ports +// GetAll gets all existing ports. func (p *PortService) GetAll() ([]Port, error) { nodes, err := p.store.GetAll() if err != nil { diff --git a/controller/topology/ports/portStore.go b/controller/topology/ports/portStore.go index 7c7d0f0cd21e4ea07ea5c754cba6512f776a30de..0c44a0b3bfd45b1c76725752205f3d0d1a7eda6d 100644 --- a/controller/topology/ports/portStore.go +++ b/controller/topology/ports/portStore.go @@ -14,7 +14,7 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" ) -// Store defines a PortStore interface +// Store defines a PortStore interface. type Store interface { Add(Port) error Update(Port) error @@ -23,15 +23,15 @@ type Store interface { GetAll() ([]Port, error) } -// DatabasePortStore is a database store for ports +// DatabasePortStore is a database store for ports. type DatabasePortStore struct { storeName string } -// NewDatabasePortStore returns a PortStore +// NewDatabasePortStore returns a PortStore. func NewDatabasePortStore() Store { return &DatabasePortStore{ - storeName: fmt.Sprintf("port-store.json"), + storeName: fmt.Sprint("port-store.json"), } } @@ -56,12 +56,15 @@ func (s *DatabasePortStore) Get(query query.Query) (Port, error) { return loadedPort, nil } -func (s *DatabasePortStore) getByID(idOfPort uuid.UUID) (Port, error) { - var loadedPort Port - +func (s *DatabasePortStore) getByID(idOfPort uuid.UUID) (loadedPort Port, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() idAsByteArray, _ := idOfPort.MarshalBinary() @@ -72,7 +75,7 @@ func (s *DatabasePortStore) getByID(idOfPort uuid.UUID) (Port, error) { return loadedPort, errors.ErrCouldNotFind{ID: idOfPort} } - err := result.Decode(&loadedPort) + err = result.Decode(&loadedPort) if err != nil { return loadedPort, errors.ErrCouldNotMarshall{Identifier: idOfPort, Type: loadedPort, Err: err} } @@ -80,12 +83,15 @@ func (s *DatabasePortStore) getByID(idOfPort uuid.UUID) (Port, error) { return loadedPort, nil } -func (s *DatabasePortStore) getByName(nameOfPort string) (Port, error) { - var loadedPort Port - +func (s *DatabasePortStore) getByName(nameOfPort string) (loadedPort Port, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -94,7 +100,7 @@ func (s *DatabasePortStore) getByName(nameOfPort string) (Port, error) { return loadedPort, errors.ErrCouldNotFind{Name: nameOfPort} } - err := result.Decode(&loadedPort) + err = result.Decode(&loadedPort) if err != nil { return loadedPort, errors.ErrCouldNotMarshall{Identifier: nameOfPort, Type: loadedPort, Err: err} } @@ -103,12 +109,16 @@ func (s *DatabasePortStore) getByName(nameOfPort string) (Port, error) { } // GetAll returns all stored ports. -func (s *DatabasePortStore) GetAll() ([]Port, error) { - var loadedPort []Port - +func (s *DatabasePortStore) GetAll() (loadedPorts []Port, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() + db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -116,23 +126,33 @@ func (s *DatabasePortStore) GetAll() ([]Port, error) { if err != nil { return []Port{}, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - err = cursor.All(ctx, &loadedPort) + err = cursor.All(ctx, &loadedPorts) if err != nil { - return loadedPort, errors.ErrCouldNotMarshall{Type: loadedPort, Err: err} + return loadedPorts, errors.ErrCouldNotMarshall{Type: loadedPorts, Err: err} } - return loadedPort, nil + return loadedPorts, nil } // Add adds a port to the port store. -func (s *DatabasePortStore) Add(port Port) error { +func (s *DatabasePortStore) Add(port Port) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.storeName). InsertOne(ctx, port) if err != nil { @@ -143,12 +163,17 @@ func (s *DatabasePortStore) Add(port Port) error { } // Update updates a existing port. -func (s *DatabasePortStore) Update(port Port) error { +func (s *DatabasePortStore) Update(port Port) (err error) { var updatedLoadedDevice device.LoadedDevice client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() update := bson.D{primitive.E{Key: "$set", Value: port}} @@ -159,7 +184,7 @@ func (s *DatabasePortStore) Update(port Port) error { ReturnDocument: &after, } - err := client.Database(database.DatabaseName). + err = client.Database(database.DatabaseName). Collection(s.storeName). FindOneAndUpdate( ctx, bson.M{"_id": port.ID.String()}, update, &opt). @@ -172,14 +197,19 @@ func (s *DatabasePortStore) Update(port Port) error { } // Delete deletes a port from the port store. -func (s *DatabasePortStore) Delete(port Port) error { +func (s *DatabasePortStore) Delete(port Port) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) - _, err := collection.DeleteOne(ctx, bson.D{primitive.E{Key: port.ID.String()}}) + _, err = collection.DeleteOne(ctx, bson.D{primitive.E{Key: port.ID.String()}}) if err != nil { return err } diff --git a/controller/topology/routing-tables/route.go b/controller/topology/routing-tables/route.go index f25292501e0264a1f8e8aa9af13e844686c4c90a..c96378300e32f1f5f21d27114bd98002938acec8 100644 --- a/controller/topology/routing-tables/route.go +++ b/controller/topology/routing-tables/route.go @@ -4,7 +4,7 @@ import ( "github.com/google/uuid" ) -// Route is a routing table entry on a device +// Route is a routing table entry on a device. type Route struct { ID uuid.UUID `bson:"_id"` TargetIPRange string `bson:"target_ip_range"` diff --git a/controller/topology/routing-tables/routingTable.go b/controller/topology/routing-tables/routingTable.go index 833c91df3931ffc80e39b2e0d5717ecd05a7b66d..5398bdc535da342603f239648450d5baeb1425a1 100644 --- a/controller/topology/routing-tables/routingTable.go +++ b/controller/topology/routing-tables/routingTable.go @@ -2,14 +2,14 @@ package routingtables import "github.com/google/uuid" -// RoutingTable is the routing table of a device +// RoutingTable is the routing table of a device. type RoutingTable struct { ID uuid.UUID `bson:"_id"` NodeID uuid.UUID `bson:"node_id"` Routes Route `bson:"routes"` } -// GetID returns the id of a routingtable +// GetID returns the id of a routingtable. func (r RoutingTable) GetID() uuid.UUID { return r.ID } diff --git a/controller/topology/routing-tables/routingTableService.go b/controller/topology/routing-tables/routingTableService.go index b5823217301eb5d92697c0154940611e2423950a..eec4efb2fc4f7cfd9fd0f2c7fa01a5a2bff47955 100644 --- a/controller/topology/routing-tables/routingTableService.go +++ b/controller/topology/routing-tables/routingTableService.go @@ -1,13 +1,21 @@ package routingtables import ( + "code.fbi.h-da.de/danet/gosdn/controller/event" + eventInterfaces "code.fbi.h-da.de/danet/gosdn/controller/interfaces/event" query "code.fbi.h-da.de/danet/gosdn/controller/store" "code.fbi.h-da.de/danet/gosdn/controller/topology/nodes" "code.fbi.h-da.de/danet/gosdn/controller/topology/ports" "github.com/google/uuid" + log "github.com/sirupsen/logrus" ) -// Service defines a interface for a RoutingTableService +const ( + // RoutingTableEventTopic is the used topic for routing table related entity changes. + RoutingTableEventTopic = "routingTable" +) + +// Service defines a interface for a RoutingTableService. type Service interface { EnsureExists(RoutingTable) (RoutingTable, error) Update(RoutingTable) error @@ -16,27 +24,30 @@ type Service interface { GetAll() ([]RoutingTable, error) } -// RoutingTableService is a RoutingTableService +// RoutingTableService is a RoutingTableService. type RoutingTableService struct { - store Store - nodeService nodes.Service - portService ports.Service + store Store + nodeService nodes.Service + portService ports.Service + eventService eventInterfaces.Service } -// NewRoutingTableService creates a RoutingTableService +// NewRoutingTableService creates a RoutingTableService. func NewRoutingTableService( store Store, nodeService nodes.Service, portService ports.Service, + eventService eventInterfaces.Service, ) Service { return &RoutingTableService{ - store: store, - nodeService: nodeService, - portService: portService, + store: store, + nodeService: nodeService, + portService: portService, + eventService: eventService, } } -// EnsureExists either creates a new routingTable or returns an already existing routingTable +// EnsureExists either creates a new routingTable or returns an already existing routingTable. func (r *RoutingTableService) EnsureExists(routingTable RoutingTable) (RoutingTable, error) { if routingTable.ID == uuid.Nil { routingTable.ID = uuid.New() @@ -57,30 +68,42 @@ func (r *RoutingTableService) createRoutingTable(routingTable RoutingTable) (Rou return routingTable, err } - return routingTable, err + if err := r.eventService.PublishEvent(RoutingTableEventTopic, event.NewAddEvent(routingTable.ID)); err != nil { + log.Error(err) + } + + return routingTable, nil } -// Update updates an existing routingTable +// Update updates an existing routingTable. func (r *RoutingTableService) Update(routingTable RoutingTable) error { err := r.store.Update(routingTable) if err != nil { return err } + if err := r.eventService.PublishEvent(RoutingTableEventTopic, event.NewUpdateEvent(routingTable.ID)); err != nil { + log.Error(err) + } + return nil } -// Delete deletes a routingTable +// Delete deletes a routingTable. func (r *RoutingTableService) Delete(routingTable RoutingTable) error { err := r.store.Delete(routingTable) if err != nil { return err } + if err := r.eventService.PublishEvent(RoutingTableEventTopic, event.NewDeleteEvent(routingTable.ID)); err != nil { + log.Error(err) + } + return nil } -// Get gets a routingTable +// Get gets a routingTable. func (r *RoutingTableService) Get(query query.Query) (RoutingTable, error) { routingTable, err := r.store.Get(query) if err != nil { @@ -90,7 +113,7 @@ func (r *RoutingTableService) Get(query query.Query) (RoutingTable, error) { return routingTable, nil } -// GetAll gets all existing routingTables +// GetAll gets all existing routingTables. func (r *RoutingTableService) GetAll() ([]RoutingTable, error) { nodes, err := r.store.GetAll() if err != nil { diff --git a/controller/topology/routing-tables/routingTableService_test.go b/controller/topology/routing-tables/routingTableService_test.go index e2fc764524c012a12496c727f43c1c5415014cf9..d9c6ceffd51405b03f02ee0c7d8650c209b038e1 100644 --- a/controller/topology/routing-tables/routingTableService_test.go +++ b/controller/topology/routing-tables/routingTableService_test.go @@ -5,6 +5,7 @@ import ( "testing" eventservice "code.fbi.h-da.de/danet/gosdn/controller/eventService" + eventInterfaces "code.fbi.h-da.de/danet/gosdn/controller/interfaces/event" query "code.fbi.h-da.de/danet/gosdn/controller/store" "code.fbi.h-da.de/danet/gosdn/controller/topology/nodes" "code.fbi.h-da.de/danet/gosdn/controller/topology/ports" @@ -85,9 +86,10 @@ func getTestStoreWithPorts(t *testing.T, portsToAdd []ports.Port) ports.Store { func TestNewRoutingTableService(t *testing.T) { type args struct { - store Store - nodeService nodes.Service - portService ports.Service + store Store + nodeService nodes.Service + portService ports.Service + eventService eventInterfaces.Service } tests := []struct { name string @@ -97,20 +99,22 @@ func TestNewRoutingTableService(t *testing.T) { { name: "should create a new topology service", args: args{ - store: getTestStoreWithRoutingTables(t, []RoutingTable{}), - nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), - portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + store: getTestStoreWithRoutingTables(t, []RoutingTable{}), + nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), + portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + eventService: eventservice.NewMockEventService(), }, want: NewRoutingTableService( getTestStoreWithRoutingTables(t, []RoutingTable{}), nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + eventservice.NewMockEventService(), ), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := NewRoutingTableService(tt.args.store, tt.args.nodeService, tt.args.portService); !reflect.DeepEqual(got, tt.want) { + if got := NewRoutingTableService(tt.args.store, tt.args.nodeService, tt.args.portService, tt.args.eventService); !reflect.DeepEqual(got, tt.want) { t.Errorf("NewNodeService() = %v, want %v", got, tt.want) } }) @@ -119,9 +123,10 @@ func TestNewRoutingTableService(t *testing.T) { func TestTopologyService_EnsureExists(t *testing.T) { type fields struct { - store Store - nodeService nodes.Service - portService ports.Service + store Store + nodeService nodes.Service + portService ports.Service + eventService eventInterfaces.Service } type args struct { routingTable RoutingTable @@ -151,6 +156,7 @@ func TestTopologyService_EnsureExists(t *testing.T) { ), eventservice.NewMockEventService(), ), + eventService: eventservice.NewMockEventService(), }, args: args{ routingTable: getTestRoutingTable(), @@ -176,6 +182,7 @@ func TestTopologyService_EnsureExists(t *testing.T) { ), eventservice.NewMockEventService(), ), + eventService: eventservice.NewMockEventService(), }, args: args{ routingTable: getTestRoutingTable(), @@ -187,9 +194,10 @@ func TestTopologyService_EnsureExists(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p := &RoutingTableService{ - store: tt.fields.store, - nodeService: tt.fields.nodeService, - portService: tt.fields.portService, + store: tt.fields.store, + nodeService: tt.fields.nodeService, + portService: tt.fields.portService, + eventService: tt.fields.eventService, } got, err := p.EnsureExists(tt.args.routingTable) if (err != nil) != tt.wantErr { @@ -205,9 +213,10 @@ func TestTopologyService_EnsureExists(t *testing.T) { func TestRoutingTableService_Update(t *testing.T) { type fields struct { - store Store - nodeService nodes.Service - portService ports.Service + store Store + nodeService nodes.Service + portService ports.Service + eventService eventInterfaces.Service } type args struct { routingTable RoutingTable @@ -222,9 +231,10 @@ func TestRoutingTableService_Update(t *testing.T) { { name: "should update an existing routing table", fields: fields{ - store: getTestStoreWithRoutingTables(t, []RoutingTable{getTestRoutingTable()}), - nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), - portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + store: getTestStoreWithRoutingTables(t, []RoutingTable{getTestRoutingTable()}), + nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), + portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + eventService: eventservice.NewMockEventService(), }, args: args{ routingTable: getTestRoutingTable(), @@ -236,9 +246,10 @@ func TestRoutingTableService_Update(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p := &RoutingTableService{ - store: tt.fields.store, - nodeService: tt.fields.nodeService, - portService: tt.fields.portService, + store: tt.fields.store, + nodeService: tt.fields.nodeService, + portService: tt.fields.portService, + eventService: tt.fields.eventService, } if err := p.Update(tt.args.routingTable); (err != nil) != tt.wantErr { t.Errorf("RoutingTableService.Update() error = %v, wantErr %v", err, tt.wantErr) @@ -249,9 +260,10 @@ func TestRoutingTableService_Update(t *testing.T) { func TestRoutingTableService_Delete(t *testing.T) { type fields struct { - store Store - nodeService nodes.Service - portService ports.Service + store Store + nodeService nodes.Service + portService ports.Service + eventService eventInterfaces.Service } type args struct { routingTable RoutingTable @@ -266,9 +278,10 @@ func TestRoutingTableService_Delete(t *testing.T) { { name: "should delete an existing routing table", fields: fields{ - store: getTestStoreWithRoutingTables(t, []RoutingTable{getTestRoutingTable()}), - nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), - portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + store: getTestStoreWithRoutingTables(t, []RoutingTable{getTestRoutingTable()}), + nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), + portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + eventService: eventservice.NewMockEventService(), }, args: args{ routingTable: getTestRoutingTable(), @@ -278,9 +291,10 @@ func TestRoutingTableService_Delete(t *testing.T) { { name: "should fail if a routing table does not exists", fields: fields{ - store: store.NewGenericStore[RoutingTable](), - nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), - portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + store: store.NewGenericStore[RoutingTable](), + nodeService: nodes.NewNodeService(getTestStoreWithNodes(t, []nodes.Node{}), eventservice.NewMockEventService()), + portService: ports.NewPortService(getTestStoreWithPorts(t, []ports.Port{}), eventservice.NewMockEventService()), + eventService: eventservice.NewMockEventService(), }, args: args{ routingTable: getTestRoutingTable(), @@ -291,9 +305,10 @@ func TestRoutingTableService_Delete(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p := &RoutingTableService{ - store: tt.fields.store, - nodeService: tt.fields.nodeService, - portService: tt.fields.portService, + store: tt.fields.store, + nodeService: tt.fields.nodeService, + portService: tt.fields.portService, + eventService: tt.fields.eventService, } if err := p.Delete(tt.args.routingTable); (err != nil) != tt.wantErr { t.Errorf("RoutingTableService.Delete() error = %v, wantErr %v", err, tt.wantErr) diff --git a/controller/topology/routing-tables/routingTableStore.go b/controller/topology/routing-tables/routingTableStore.go index b3a414575a5b61d392aebf62f81a7104002c4c2c..0bdd82c7772784973e5664a9a3a7cd5a7e8255d1 100644 --- a/controller/topology/routing-tables/routingTableStore.go +++ b/controller/topology/routing-tables/routingTableStore.go @@ -13,7 +13,7 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" ) -// Store defines a RoutingTable store interface +// Store defines a RoutingTable store interface. type Store interface { Add(RoutingTable) error Update(RoutingTable) error @@ -22,15 +22,15 @@ type Store interface { GetAll() ([]RoutingTable, error) } -// DatabaseRoutingTableStore is a database store for routingTables +// DatabaseRoutingTableStore is a database store for routingTables. type DatabaseRoutingTableStore struct { storeName string } -// NewDatabaseRoutingTableStore returns a RoutingTableStore +// NewDatabaseRoutingTableStore returns a RoutingTableStore. func NewDatabaseRoutingTableStore() Store { return &DatabaseRoutingTableStore{ - storeName: fmt.Sprintf("routing-table-store.json"), + storeName: fmt.Sprint("routing-table-store.json"), } } @@ -55,34 +55,40 @@ func (s *DatabaseRoutingTableStore) Get(query query.Query) (RoutingTable, error) return loadedRoutingTable, nil } -func (s *DatabaseRoutingTableStore) getByID(idOfRoutingTable uuid.UUID) (RoutingTable, error) { - var RoutingTable RoutingTable - +func (s *DatabaseRoutingTableStore) getByID(idOfRoutingTable uuid.UUID) (routingTable RoutingTable, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) result := collection.FindOne(ctx, bson.D{primitive.E{Key: "_id", Value: idOfRoutingTable.String()}}) if result == nil { - return RoutingTable, errors.ErrCouldNotFind{ID: idOfRoutingTable} + return routingTable, errors.ErrCouldNotFind{ID: idOfRoutingTable} } - err := result.Decode(&RoutingTable) + err = result.Decode(&routingTable) if err != nil { - return RoutingTable, errors.ErrCouldNotMarshall{Identifier: idOfRoutingTable, Type: RoutingTable, Err: err} + return routingTable, errors.ErrCouldNotMarshall{Identifier: idOfRoutingTable, Type: routingTable, Err: err} } - return RoutingTable, nil + return routingTable, nil } -func (s *DatabaseRoutingTableStore) getByName(nameOfRoutingTable string) (RoutingTable, error) { - var loadedRoutingTable RoutingTable - +func (s *DatabaseRoutingTableStore) getByName(nameOfRoutingTable string) (loadedRoutingTable RoutingTable, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -91,7 +97,7 @@ func (s *DatabaseRoutingTableStore) getByName(nameOfRoutingTable string) (Routin return loadedRoutingTable, errors.ErrCouldNotFind{Name: nameOfRoutingTable} } - err := result.Decode(&loadedRoutingTable) + err = result.Decode(&loadedRoutingTable) if err != nil { return loadedRoutingTable, errors.ErrCouldNotMarshall{Type: loadedRoutingTable, Err: err} } @@ -100,12 +106,16 @@ func (s *DatabaseRoutingTableStore) getByName(nameOfRoutingTable string) (Routin } // GetAll returns all stored routingTables. -func (s *DatabaseRoutingTableStore) GetAll() ([]RoutingTable, error) { - var loadedRoutingTable []RoutingTable - +func (s *DatabaseRoutingTableStore) GetAll() (loadedRoutingTable []RoutingTable, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() + db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -113,7 +123,12 @@ func (s *DatabaseRoutingTableStore) GetAll() ([]RoutingTable, error) { if err != nil { return []RoutingTable{}, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedRoutingTable) if err != nil { @@ -124,12 +139,17 @@ func (s *DatabaseRoutingTableStore) GetAll() ([]RoutingTable, error) { } // Add adds a RoutingTable to the store. -func (s *DatabaseRoutingTableStore) Add(routingTable RoutingTable) error { +func (s *DatabaseRoutingTableStore) Add(routingTable RoutingTable) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.storeName). InsertOne(ctx, routingTable) if err != nil { @@ -140,12 +160,17 @@ func (s *DatabaseRoutingTableStore) Add(routingTable RoutingTable) error { } // Update updates a existing routingTable. -func (s *DatabaseRoutingTableStore) Update(routingTable RoutingTable) error { +func (s *DatabaseRoutingTableStore) Update(routingTable RoutingTable) (err error) { var updatedLoadedRoutingTable RoutingTable client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() update := bson.D{primitive.E{Key: "$set", Value: routingTable}} @@ -156,7 +181,7 @@ func (s *DatabaseRoutingTableStore) Update(routingTable RoutingTable) error { ReturnDocument: &after, } - err := client.Database(database.DatabaseName). + err = client.Database(database.DatabaseName). Collection(s.storeName). FindOneAndUpdate( ctx, bson.M{"_id": routingTable.ID.String()}, update, &opt). @@ -169,14 +194,19 @@ func (s *DatabaseRoutingTableStore) Update(routingTable RoutingTable) error { } // Delete deletes a node from the node store. -func (s *DatabaseRoutingTableStore) Delete(routingTable RoutingTable) error { +func (s *DatabaseRoutingTableStore) Delete(routingTable RoutingTable) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) - _, err := collection.DeleteOne(ctx, bson.D{primitive.E{Key: routingTable.ID.String()}}) + _, err = collection.DeleteOne(ctx, bson.D{primitive.E{Key: routingTable.ID.String()}}) if err != nil { return err } diff --git a/controller/topology/topologyService.go b/controller/topology/topologyService.go index 9caa065fdbcf81808682a73c072a8ac465056051..6949108435b88caf15e0b7b6e65bc9c8453018a8 100644 --- a/controller/topology/topologyService.go +++ b/controller/topology/topologyService.go @@ -7,14 +7,15 @@ import ( "code.fbi.h-da.de/danet/gosdn/controller/topology/links" "code.fbi.h-da.de/danet/gosdn/controller/topology/nodes" "code.fbi.h-da.de/danet/gosdn/controller/topology/ports" + log "github.com/sirupsen/logrus" ) const ( - // LinkEventTopic is the used topic for link related entity changes + // LinkEventTopic is the used topic for link related entity changes. LinkEventTopic = "link" ) -// Service defines an interface for a Service +// Service defines an interface for a Service. type Service interface { AddLink(links.Link) error UpdateLink(links.Link) error @@ -23,7 +24,7 @@ type Service interface { GetAll() ([]links.Link, error) } -// service is a service for ports +// service is a service for ports. type service struct { store Store nodeService nodes.Service @@ -31,7 +32,7 @@ type service struct { eventService eventInterfaces.Service } -// NewTopologyService creates a new TopologyService +// NewTopologyService creates a new TopologyService. func NewTopologyService( store Store, nodeService nodes.Service, @@ -46,7 +47,7 @@ func NewTopologyService( } } -// AddLink adds a new link to the topology +// AddLink adds a new link to the topology. func (t *service) AddLink(link links.Link) error { // These checks are also happening in the current NBI implementation. // This should be refactored to only to these checks here. @@ -73,24 +74,28 @@ func (t *service) AddLink(link links.Link) error { return err } - t.eventService.PublishEvent(LinkEventTopic, event.NewAddEvent(link.ID)) + if err := t.eventService.PublishEvent(LinkEventTopic, event.NewAddEvent(link.ID)); err != nil { + log.Error(err) + } return nil } -// UpdateLink updates an existing link +// UpdateLink updates an existing link. func (t *service) UpdateLink(link links.Link) error { err := t.store.Update(link) if err != nil { return err } - t.eventService.PublishEvent(LinkEventTopic, event.NewUpdateEvent(link.ID)) + if err := t.eventService.PublishEvent(LinkEventTopic, event.NewUpdateEvent(link.ID)); err != nil { + log.Error(err) + } return nil } -// DeleteLink deletes a link +// DeleteLink deletes a link. func (t *service) DeleteLink(link links.Link) error { // TODO: Delete should also check if a node or port is used somewhere else and // if not, delete the node and its ports @@ -99,12 +104,14 @@ func (t *service) DeleteLink(link links.Link) error { return err } - t.eventService.PublishEvent(LinkEventTopic, event.NewDeleteEvent(link.ID)) + if err := t.eventService.PublishEvent(LinkEventTopic, event.NewDeleteEvent(link.ID)); err != nil { + log.Error(err) + } return nil } -// GetAll returns the current topology +// GetAll returns the current topology. func (t *service) GetAll() ([]links.Link, error) { topo, err := t.store.GetAll() if err != nil { @@ -113,7 +120,7 @@ func (t *service) GetAll() ([]links.Link, error) { return topo, nil } -// GetAll returns the current topology +// GetAll returns the current topology. func (t *service) Get(query query.Query) (links.Link, error) { link, err := t.store.Get(query) if err != nil { diff --git a/controller/topology/topologyStore.go b/controller/topology/topologyStore.go index 9c63aa120d89c4e6acb0fa6b27fb7894454a2f82..dc12b10af93c0bc226592f0498e54078c55fb7f8 100644 --- a/controller/topology/topologyStore.go +++ b/controller/topology/topologyStore.go @@ -14,7 +14,7 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" ) -// Store defines a Topology store interface +// Store defines a Topology store interface. type Store interface { Add(links.Link) error Update(links.Link) error @@ -23,15 +23,15 @@ type Store interface { GetAll() ([]links.Link, error) } -// DatabaseTopologyStore is a database store for the topology +// DatabaseTopologyStore is a database store for the topology. type DatabaseTopologyStore struct { storeName string } -// NewDatabaseTopologyStore returns a TopologyStore +// NewDatabaseTopologyStore returns a TopologyStore. func NewDatabaseTopologyStore() Store { return &DatabaseTopologyStore{ - storeName: fmt.Sprintf("topology-store.json"), + storeName: fmt.Sprint("topology-store.json"), } } @@ -56,12 +56,15 @@ func (s *DatabaseTopologyStore) Get(query query.Query) (links.Link, error) { return loadedTopology, nil } -func (s *DatabaseTopologyStore) getByID(idOfTopology uuid.UUID) (links.Link, error) { - var loadedTopology links.Link - +func (s *DatabaseTopologyStore) getByID(idOfTopology uuid.UUID) (loadedTopology links.Link, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -70,7 +73,7 @@ func (s *DatabaseTopologyStore) getByID(idOfTopology uuid.UUID) (links.Link, err return loadedTopology, errors.ErrCouldNotFind{ID: idOfTopology} } - err := result.Decode(&loadedTopology) + err = result.Decode(&loadedTopology) if err != nil { return loadedTopology, errors.ErrCouldNotMarshall{Identifier: idOfTopology, Type: loadedTopology, Err: err} } @@ -78,12 +81,15 @@ func (s *DatabaseTopologyStore) getByID(idOfTopology uuid.UUID) (links.Link, err return loadedTopology, nil } -func (s *DatabaseTopologyStore) getByName(nameOfTopology string) (links.Link, error) { - var loadedTopology links.Link - +func (s *DatabaseTopologyStore) getByName(nameOfTopology string) (loadedTopology links.Link, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -92,7 +98,7 @@ func (s *DatabaseTopologyStore) getByName(nameOfTopology string) (links.Link, er return loadedTopology, errors.ErrCouldNotFind{Name: nameOfTopology} } - err := result.Decode(&loadedTopology) + err = result.Decode(&loadedTopology) if err != nil { return loadedTopology, errors.ErrCouldNotMarshall{Identifier: nameOfTopology, Type: loadedTopology, Err: err} } @@ -101,12 +107,16 @@ func (s *DatabaseTopologyStore) getByName(nameOfTopology string) (links.Link, er } // GetAll returns all stored links. -func (s *DatabaseTopologyStore) GetAll() ([]links.Link, error) { - var loadedTopology []links.Link - +func (s *DatabaseTopologyStore) GetAll() (loadedTopology []links.Link, err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() + db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) @@ -114,7 +124,12 @@ func (s *DatabaseTopologyStore) GetAll() ([]links.Link, error) { if err != nil { return loadedTopology, err } - defer cursor.Close(ctx) + defer func() { + if ferr := cursor.Close(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() err = cursor.All(ctx, &loadedTopology) if err != nil { @@ -125,12 +140,17 @@ func (s *DatabaseTopologyStore) GetAll() ([]links.Link, error) { } // Add adds a link to the link store. -func (s *DatabaseTopologyStore) Add(link links.Link) error { +func (s *DatabaseTopologyStore) Add(link links.Link) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - _, err := client.Database(database.DatabaseName). + _, err = client.Database(database.DatabaseName). Collection(s.storeName). InsertOne(ctx, link) if err != nil { @@ -141,12 +161,17 @@ func (s *DatabaseTopologyStore) Add(link links.Link) error { } // Update updates a existing link. -func (s *DatabaseTopologyStore) Update(linkToUpdate links.Link) error { +func (s *DatabaseTopologyStore) Update(linkToUpdate links.Link) (err error) { var updatedLink links.Link client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() update := bson.D{primitive.E{Key: "$set", Value: linkToUpdate}} @@ -157,7 +182,7 @@ func (s *DatabaseTopologyStore) Update(linkToUpdate links.Link) error { ReturnDocument: &after, } - err := client.Database(database.DatabaseName). + err = client.Database(database.DatabaseName). Collection(s.storeName). FindOneAndUpdate( ctx, bson.M{"_id": linkToUpdate.ID.String()}, update, &opt). @@ -170,14 +195,19 @@ func (s *DatabaseTopologyStore) Update(linkToUpdate links.Link) error { } // Delete deletes a link from the link store. -func (s *DatabaseTopologyStore) Delete(linkToDelete links.Link) error { +func (s *DatabaseTopologyStore) Delete(linkToDelete links.Link) (err error) { client, ctx, cancel := database.GetMongoConnection() defer cancel() - defer client.Disconnect(ctx) + defer func() { + if ferr := client.Disconnect(ctx); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() db := client.Database(database.DatabaseName) collection := db.Collection(s.storeName) - _, err := collection.DeleteOne(ctx, bson.D{primitive.E{Key: linkToDelete.ID.String()}}) + _, err = collection.DeleteOne(ctx, bson.D{primitive.E{Key: linkToDelete.ID.String()}}) if err != nil { return err } diff --git a/csbi/build.go b/csbi/build.go index 82c091e5964eac8ced2e1a5079a70b8b3e0afb16..ee20cb8ca03fdcc03178196867f7a2f950965806 100644 --- a/csbi/build.go +++ b/csbi/build.go @@ -16,6 +16,7 @@ import ( "github.com/docker/docker/client" "github.com/docker/docker/pkg/archive" "github.com/prometheus/client_golang/prometheus" + log "github.com/sirupsen/logrus" ) // nolint @@ -29,7 +30,7 @@ type ErrorDetail struct { Message string `json:"message"` } -func buildImage(d Deployment, dockerClient *client.Client) error { +func buildImage(d Deployment, dockerClient *client.Client) (err error) { labels := prometheus.Labels{"type": spb.Type_TYPE_CONTAINERISED.String()} start := promStartHook(labels, buildsTotal) @@ -51,9 +52,14 @@ func buildImage(d Deployment, dockerClient *client.Client) error { if err != nil { return err } - defer res.Body.Close() + defer func() { + if ferr := res.Body.Close(); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() - err = print(res.Body) + err = printImageBody(res.Body) if err != nil { return err } @@ -61,7 +67,7 @@ func buildImage(d Deployment, dockerClient *client.Client) error { return nil } -func print(rd io.Reader) error { +func printImageBody(rd io.Reader) error { var lastLine string scanner := bufio.NewScanner(rd) @@ -71,9 +77,11 @@ func print(rd io.Reader) error { } errLine := &ErrorLine{} - json.Unmarshal([]byte(lastLine), errLine) + err := json.Unmarshal([]byte(lastLine), errLine) if errLine.Error != "" { return errors.New(errLine.Error) + } else if err != nil { + log.Error(err) } return scanner.Err() diff --git a/csbi/build_test.go b/csbi/build_test.go index 4e6f1b6aeb949eb26a0438773a6b61e409926cdb..15c7b107619a4026df3291c3c678e985791e28cc 100644 --- a/csbi/build_test.go +++ b/csbi/build_test.go @@ -41,7 +41,7 @@ func Test_print(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := print(tt.args.rd); (err != nil) != tt.wantErr { + if err := printImageBody(tt.args.rd); (err != nil) != tt.wantErr { t.Errorf("print() error = %v, wantErr %v", err, tt.wantErr) } }) diff --git a/csbi/cmd/deploy.go b/csbi/cmd/deploy.go index 94233a70640456b827e55f1c6f13ec22460dc2fc..9d191850869c515626f5b1d27673ce1bb6297080 100644 --- a/csbi/cmd/deploy.go +++ b/csbi/cmd/deploy.go @@ -37,7 +37,7 @@ import ( "github.com/spf13/cobra" ) -// deployCmd represents the deploy command +// deployCmd represents the deploy command. var deployCmd = &cobra.Command{ Use: "deploy", Short: "A brief description of your command", diff --git a/csbi/cmd/discover.go b/csbi/cmd/discover.go index 21457cb96b9fc2e4126e561cf20ba11b5e6560d2..38fe3ba09082a8016a0d706d3b77d155eeb5625a 100644 --- a/csbi/cmd/discover.go +++ b/csbi/cmd/discover.go @@ -37,7 +37,7 @@ import ( "github.com/spf13/cobra" ) -// discoverCmd represents the discover command +// discoverCmd represents the discover command. var discoverCmd = &cobra.Command{ Use: "discover", Short: "A brief description of your command", diff --git a/csbi/cmd/generate.go b/csbi/cmd/generate.go index 9713dd284b2133457603185a21383d0d13971fab..86be06f3b87e36c6ec5184fb488c2c05d494923a 100644 --- a/csbi/cmd/generate.go +++ b/csbi/cmd/generate.go @@ -43,7 +43,7 @@ import ( "google.golang.org/grpc/peer" ) -// generateCmd represents the generate command +// generateCmd represents the generate command. var generateCmd = &cobra.Command{ Use: "generate", Short: "generates a blank csbi boilerplate", diff --git a/csbi/cmd/hello.go b/csbi/cmd/hello.go index 7a82f17b89be6869f93b2025fa736f0e6abd5162..b2c7ecd2673733784e4e6cc844b6ec039c5372dc 100644 --- a/csbi/cmd/hello.go +++ b/csbi/cmd/hello.go @@ -45,7 +45,7 @@ import ( "google.golang.org/grpc" ) -// helloCmd represents the hello command +// helloCmd represents the hello command. var helloCmd = &cobra.Command{ Use: "hello", Short: "serves Hello service for testing purposes", @@ -87,7 +87,7 @@ func (s server) Hello(ctx context.Context, syn *pb.Syn) (*pb.Ack, error) { return ack, nil } -// Run bootstraps the orchestrator and waits for the shutdown signal +// Run bootstraps the orchestrator and waits for the shutdown signal. func Run(bindAddr string) { g := grpc.NewServer() s := &server{} diff --git a/csbi/cmd/init.go b/csbi/cmd/init.go index 3d06f85cd70809a52478fad5c94b9efe4d8fb103..8a1f9ec68251c8e661db306fc355d86912c80b6c 100644 --- a/csbi/cmd/init.go +++ b/csbi/cmd/init.go @@ -37,7 +37,7 @@ import ( "github.com/spf13/cobra" ) -// initCmd represents the init command +// initCmd represents the init command. var initCmd = &cobra.Command{ Use: "init", Short: "A brief description of your command", diff --git a/csbi/cmd/repository.go b/csbi/cmd/repository.go index c1142b913e483e95cb5a733c0d2ef2748d72d72f..21eda8bb64e4db0bd8156b5a1bf1fcafac18ceed 100644 --- a/csbi/cmd/repository.go +++ b/csbi/cmd/repository.go @@ -38,7 +38,7 @@ import ( "github.com/spf13/cobra" ) -// repositoryCmd represents the repository command +// repositoryCmd represents the repository command. var repositoryCmd = &cobra.Command{ Use: "repository", Short: "run the 'repository' command", diff --git a/csbi/cmd/root.go b/csbi/cmd/root.go index 75eef6f39a737ff615850c5eea5e73ca79e6870a..da6ae200e4646f88b589ab8b704e8cca3bf397bc 100644 --- a/csbi/cmd/root.go +++ b/csbi/cmd/root.go @@ -51,7 +51,7 @@ var logLevel string var repoBasePath string -// rootCmd represents the base command when called without any subcommands +// rootCmd represents the base command when called without any subcommands. var rootCmd = &cobra.Command{ Use: "csbi", Short: "start the csbi orchestrator", diff --git a/csbi/config/config.go b/csbi/config/config.go index c029ed8aa62750742ac0246c4058b27c44db0752..045b5267384ab8f40506b915ae3dbda7e27c721c 100644 --- a/csbi/config/config.go +++ b/csbi/config/config.go @@ -6,22 +6,22 @@ import ( "github.com/spf13/viper" ) -// RepositoryBasePath returns the repository base path from viper +// RepositoryBasePath returns the repository base path from viper. func RepositoryBasePath() string { return viper.GetString("repository-base-path") } -// RepositoryAccessToken returns the repository access token from viper +// RepositoryAccessToken returns the repository access token from viper. func RepositoryAccessToken() string { return viper.GetString("repository-access-token") } -// OrchestratorShutdownTimeout returns the orchestrator shutdown timer from viper +// OrchestratorShutdownTimeout returns the orchestrator shutdown timer from viper. func OrchestratorShutdownTimeout() time.Duration { return viper.GetDuration("orchestrator-shutown-timeout") } -// DockerOrchestratorNetwork returns the docker orchestrator network from viper +// DockerOrchestratorNetwork returns the docker orchestrator network from viper. func DockerOrchestratorNetwork() string { return viper.GetString("docker-orchestrator-network") } diff --git a/csbi/deployment.go b/csbi/deployment.go index 72d25a4c597a133eb27934d9050a257a8d87057c..8cf1da9709e06aec3e2ede877cde7bfc2b09450a 100644 --- a/csbi/deployment.go +++ b/csbi/deployment.go @@ -31,7 +31,7 @@ type DeploymentStore struct { } // NewDeploymentStore returns a DeploymentStore. It takes a time.Duration -// variable to configure the garbage collection interval +// variable to configure the garbage collection interval. func NewDeploymentStore(garbageCollectionInterval ...time.Duration) DeploymentStore { var gcInterval time.Duration if len(garbageCollectionInterval) > 0 { diff --git a/csbi/deployment_test.go b/csbi/deployment_test.go index 246c826f21dbbe6ce035822675d360a24f0fbbaa..670e7ad339086635e249c689ccc9d15f5c0370e8 100644 --- a/csbi/deployment_test.go +++ b/csbi/deployment_test.go @@ -12,6 +12,7 @@ import ( "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/csbi" "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/southbound" "github.com/google/uuid" + log "github.com/sirupsen/logrus" "google.golang.org/grpc/peer" ) @@ -144,7 +145,9 @@ func Test_garbageCollector(t *testing.T) { rval := rand.Float32() if tt.name == "inconsistent" { d.State = csbi.State_STATE_DECOMMISSIONED - os.RemoveAll(d.ID.String()) + if err := os.RemoveAll(d.ID.String()); err != nil { + log.Error(err) + } } else { if rval < tt.args.quota { d.State = csbi.State_STATE_DECOMMISSIONED diff --git a/csbi/discover.go b/csbi/discover.go index 78bceec3e8790d58e004cf5a575c34d6fe062baa..fb270c1119bff0f88e40b064e445c49dcdcc88e5 100644 --- a/csbi/discover.go +++ b/csbi/discover.go @@ -12,7 +12,7 @@ import ( ) // Discover sends a gnmi Capabilities request to the specified target and -// returns the gnmi.ModelData +// returns the gnmi.ModelData. func Discover(ctx context.Context, opts *tpb.TransportOption) ([]*gnmi.ModelData, error) { sbi, err := nucleus.NewSBI(spb.Type_TYPE_OPENCONFIG) if err != nil { diff --git a/csbi/generate.go b/csbi/generate.go index b3d1e8dc6a573daf31db351f6decf6ec14049eda..d299aa53ecdabecb2beb4232f0768cce92bdc58a 100644 --- a/csbi/generate.go +++ b/csbi/generate.go @@ -101,11 +101,13 @@ func Generate(ctx context.Context, models []*gpb.ModelData, repository Repositor lock.Unlock() if len(errs) != 0 { + var handledErrs []error n := len(errs) log.Errorf("%v errors during code generation", n) for _, err := range errs { - promHandleError(labels, err, codeGenerationErrorsTotal) + handledErrs = append(handledErrs, promHandleError(labels, err, codeGenerationErrorsTotal)) } + log.Errorf("error details after handling: \n%v\n", handledErrs) } if code == nil { diff --git a/csbi/grpc.go b/csbi/grpc.go index 32fe2587173b39fe3ec135776515f6e19b9e8a01..cd6359f179f063a958e98bb20d6f2207475f69e6 100644 --- a/csbi/grpc.go +++ b/csbi/grpc.go @@ -2,6 +2,7 @@ package csbi import ( "context" + "errors" "fmt" "io" "os" @@ -66,7 +67,7 @@ func (s server) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, e } // Create creates a new cSBI; this includes generating a deployment, building -// the container, generating gostructs from the devices capabilites. +// the container, generating gostructs from the devices capabilities. func (s server) Create(ctx context.Context, req *pb.CreateRequest) (*pb.CreateResponse, error) { labels := prometheus.Labels{"rpc": "create"} start := promStartHook(labels, grpcRequestsTotal) @@ -98,15 +99,19 @@ func (s server) Create(ctx context.Context, req *pb.CreateRequest) (*pb.CreateRe // GetFile sends files based on the requested file name. Currently only // `gostructs.go`, `plugin.yml` and `csbiAdditions.go` are allowed to be // requested. -func (s server) GetFile(req *pb.GetPayloadRequest, stream pb.CsbiService_GetFileServer) error { +func (s server) GetFile(req *pb.GetPayloadRequest, stream pb.CsbiService_GetFileServer) (err error) { log.Info("started GetGoStruct") labels := prometheus.Labels{"rpc": "get_go_struct"} start := promStartHook(labels, grpcRequestsTotal) defer promEndHook(labels, start, grpcRequestDurationSecondsTotal, grpcRequestDurationSeconds) var file *os.File - var err error - defer file.Close() + defer func() { + if ferr := file.Close(); ferr != nil { + fErrString := ferr.Error() + err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString) + } + }() switch fn := req.GetFile(); { case fn == util.GoStructName: @@ -133,7 +138,7 @@ func (s server) GetFile(req *pb.GetPayloadRequest, stream pb.CsbiService_GetFile for { n, err := file.Read(buffer) if err != nil { - if err != io.EOF { + if errors.Is(err, io.EOF) { fmt.Println(err) } break diff --git a/csbi/model.go b/csbi/model.go index 355aeb9a858c272cc12d4d2885ae37d50f6232c2..8fecf0c4ec71aeb3dc4d0792a27e794365a88fbf 100644 --- a/csbi/model.go +++ b/csbi/model.go @@ -18,7 +18,6 @@ const ( OpenconfigNetworkInstance = "openconfig-network-instance" ) -// nolint var ( // ModelData is a list of supported models. ModelData = []*gpb.ModelData{{ diff --git a/csbi/orchestrator.go b/csbi/orchestrator.go index c489a086d9701a03e4aa8dd487dca687bd785efe..d2a29be548666aec09b61cca4a97250ee7af2216 100644 --- a/csbi/orchestrator.go +++ b/csbi/orchestrator.go @@ -31,7 +31,7 @@ const ( Docker OrchestratorType = iota ) -// Orchestrator manages the lifecycle of cSBI deployments +// Orchestrator manages the lifecycle of cSBI deployments. type Orchestrator interface { Build(ctx context.Context, model []*gpb.ModelData) (Deployment, error) Deploy(deployment Deployment) error @@ -43,7 +43,7 @@ type Orchestrator interface { // NewOrchestrator returns an implementation of the Orchestrator interface // depending on the passed OrchestratorTYpe. Returns an error if an invalid -// type is passed +// type is passed. func NewOrchestrator(flavour OrchestratorType) (Orchestrator, error) { switch flavour { case Docker: @@ -168,7 +168,13 @@ func (o *dockerOrchestrator) attachLogger(ctx context.Context, containerID strin if err != nil { log.Error(err) } - defer logStream.Close() + + defer func() { + if err := logStream.Close(); err != nil { + log.Error(err) + } + }() + stdlogger := log.StandardLogger() stdlogger.Trace("detached logger") stdout := stdlogger.Writer() diff --git a/csbi/repository.go b/csbi/repository.go index 3a96d5c6d3250fa5add9f45a5b8477ef6bbdd1b7..e4da27900b8e32beeb3c48dccc32426ce8fb5edd 100644 --- a/csbi/repository.go +++ b/csbi/repository.go @@ -20,7 +20,7 @@ type Repository interface { YANGPathsWithSuffix() ([]string, error) } -// NewRepository returns a implementation of the Repository interface +// NewRepository returns a implementation of the Repository interface. func NewRepository(basePath string) Repository { return &repo{ fs: &filesystem{ @@ -114,7 +114,7 @@ func (osfs *filesystem) Stat(name string) (fs.FileInfo, error) { func (osfs *filesystem) Glob(pattern string) (paths []string, err error) { defer func() { if e := recover(); e != nil { - err = e.(error) + err = e.(error) //nolint:errcheck paths = nil } }() diff --git a/csbi/run.go b/csbi/run.go index 469899836c0d998b37cd14a739888127c89ff6bf..a5eaf9ae86193b5afea3ad7cdbddbe887ae1ef31 100644 --- a/csbi/run.go +++ b/csbi/run.go @@ -21,7 +21,7 @@ func init() { signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM) } -// Run bootstraps the orchestrator and waits for the shutdown signal +// Run bootstraps the orchestrator and waits for the shutdown signal. func Run(bindAddr string) { g := grpc.NewServer() o, err := NewOrchestrator(Docker) diff --git a/csbi/templates.go b/csbi/templates.go index 89f5407e8c0d3c5c2652035b46751fcc367cf890..9289fc248ba2495ba2766690b7ebf906186f4131 100644 --- a/csbi/templates.go +++ b/csbi/templates.go @@ -2,7 +2,7 @@ package csbi import "github.com/openconfig/ygot/ygen" -// deprecated +// deprecated. var southboundStruct = ygen.GoStructCodeSnippet{ StructName: "Csbi", StructDef: `type Csbi struct { @@ -88,7 +88,7 @@ func (csbi *Csbi) ID() uuid.UUID { `, } -// deprecated +// deprecated. const southboundStructCsbiAmendmend = ` // Type returns the Southbound's type @@ -102,7 +102,7 @@ func (csbi *Csbi) Name() string { } ` -// deprecated +// deprecated. const southboundStructPluginAmendmend = ` // Type returns the Southbound's type @@ -117,7 +117,7 @@ func (csbi *Csbi) Name() string { ` -// deprecated +// deprecated. const southboundImportAmendmend = ` "code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors" diff --git a/csbi/write.go b/csbi/write.go index ed6396c36c22e515fb0293e3cb6620971f9d741d..ccc679bcf8dd611c267b387b1d3885287030f949 100644 --- a/csbi/write.go +++ b/csbi/write.go @@ -28,7 +28,7 @@ import ( // The output includes a package header which is generated. func write(ctx context.Context, code *ygen.GeneratedGoCode, path string, sbiType spb.Type) error { if err := os.Mkdir(path, 0755); err != nil { - if err.(*fs.PathError).Err.Error() != "file exists" { + if err.(*fs.PathError).Err.Error() != "file exists" { //nolint:errorlint return err } } @@ -165,7 +165,7 @@ func writeGoStruct(path string, code *ygen.GeneratedGoCode, t spb.Type) error { return nil } -// deprecated +// deprecated. func writeCode(path string, code *ygen.GeneratedGoCode, t spb.Type) error { code.CommonHeader = strings.TrimSuffix(code.CommonHeader, ")\n") code.CommonHeader = code.CommonHeader + southboundImportAmendmend @@ -216,7 +216,7 @@ func writeCode(path string, code *ygen.GeneratedGoCode, t spb.Type) error { return nil } -// Manifest represents a csbi manifest +// Manifest represents a csbi manifest. type Manifest struct { Name, Author, Version string }