Skip to content

Commit

Permalink
add Path data structure for registry
Browse files Browse the repository at this point in the history
Signed-off-by: Nikita Skrynnik <nikita.skrynnik@xored.com>
  • Loading branch information
NikitaSkrynnik committed Nov 21, 2022
1 parent d59bc5a commit 6c48ca3
Show file tree
Hide file tree
Showing 21 changed files with 233 additions and 205 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ require (
gopkg.in/yaml.v2 v2.4.0
)

replace github.com/networkservicemesh/api => github.com/NikitaSkrynnik/api v1.0.1-0.20221020063652-bbb1a2db7c03
replace github.com/networkservicemesh/api => github.com/NikitaSkrynnik/api v1.0.1-0.20221121074724-9608bf355179

require (
github.com/OneOfOne/xxhash v1.2.8 // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DataDog/datadog-go v2.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/NikitaSkrynnik/api v1.0.1-0.20221020063652-bbb1a2db7c03 h1:0aFigqAowENatqC3yEQkX6I7l2u18Qrrbs3nABnCRLI=
github.com/NikitaSkrynnik/api v1.0.1-0.20221020063652-bbb1a2db7c03/go.mod h1:hOF2844BSstH1311oDMDgqqXS+kdc77htZNPRKl9mf8=
github.com/NikitaSkrynnik/api v1.0.1-0.20221121074724-9608bf355179 h1:P/DMA6fokdHsZAAI7hSRd49b9RVDJjU/iWqs+uYAz+U=
github.com/NikitaSkrynnik/api v1.0.1-0.20221121074724-9608bf355179/go.mod h1:hOF2844BSstH1311oDMDgqqXS+kdc77htZNPRKl9mf8=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/OneOfOne/xxhash v1.2.8 h1:31czK/TI9sNkxIKfaUfGlU47BAxQ0ztGgd9vPyqimf8=
github.com/OneOfOne/xxhash v1.2.8/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q=
Expand Down
15 changes: 7 additions & 8 deletions pkg/registry/common/authorize/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,17 @@ import (
"github.com/pkg/errors"
"github.com/spiffe/go-spiffe/v2/spiffeid"

"github.com/networkservicemesh/api/pkg/api/registry"

"github.com/networkservicemesh/sdk/pkg/registry/common/grpcmetadata"
"github.com/networkservicemesh/sdk/pkg/tools/log"
)

// RegistryOpaInput represents input for policies in authorizNSEServer and authorizeNSServer
type RegistryOpaInput struct {
ResourceID string `json:"resource_id"`
ResourceName string `json:"resource_name"`
ResourcePathIdsMap map[string][]string `json:"resource_path_ids_map"`
PathSegments []*registry.PathSegment `json:"path_segments"`
Index uint32 `json:"index"`
ResourceID string `json:"resource_id"`
ResourceName string `json:"resource_name"`
ResourcePathIdsMap map[string][]string `json:"resource_path_ids_map"`
PathSegments []*grpcmetadata.PathSegment `json:"path_segments"`
Index uint32 `json:"index"`
}

// Policy represents authorization policy for network service.
Expand Down Expand Up @@ -75,7 +74,7 @@ func getRawMap(m *ResourcePathIdsMap) map[string][]string {
return rawMap
}

func getSpiffeIDFromPath(path *registry.Path) (spiffeid.ID, error) {
func getSpiffeIDFromPath(path *grpcmetadata.Path) (spiffeid.ID, error) {
tokenString := path.PathSegments[0].Token

claims := jwt.MapClaims{}
Expand Down
13 changes: 6 additions & 7 deletions pkg/registry/common/authorize/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@ import (
"time"

"github.com/golang-jwt/jwt/v4"
"github.com/networkservicemesh/api/pkg/api/registry"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/credentials"
"google.golang.org/protobuf/types/known/timestamppb"

"github.com/networkservicemesh/sdk/pkg/registry/common/grpcmetadata"
"github.com/networkservicemesh/sdk/pkg/tools/token"
)

Expand All @@ -45,7 +44,7 @@ func genTokenFunc(claims *jwt.RegisteredClaims) token.GeneratorFunc {
}
}

func getPath(t *testing.T, spiffeID string) *registry.Path {
func getPath(t *testing.T, spiffeID string) *grpcmetadata.Path {
var segments = []struct {
name string
tokenGenerator token.GeneratorFunc
Expand Down Expand Up @@ -73,17 +72,17 @@ func getPath(t *testing.T, spiffeID string) *registry.Path {
},
}

path := &registry.Path{
PathSegments: []*registry.PathSegment{},
path := &grpcmetadata.Path{
PathSegments: []*grpcmetadata.PathSegment{},
}

for _, segment := range segments {
tok, expire, err := segment.tokenGenerator(nil)
require.NoError(t, err)
path.PathSegments = append(path.PathSegments, &registry.PathSegment{
path.PathSegments = append(path.PathSegments, &grpcmetadata.PathSegment{
Name: segment.name,
Token: tok,
Expires: timestamppb.New(expire),
Expires: expire,
})
}

Expand Down
12 changes: 6 additions & 6 deletions pkg/registry/common/authorize/ns_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ func (s *authorizeNSServer) Register(ctx context.Context, ns *registry.NetworkSe
return nil, err
}

index := path.GetIndex()
var leftSide = &registry.Path{
index := path.Index
var leftSide = &grpcmetadata.Path{
Index: index,
PathSegments: path.GetPathSegments()[:index+1],
PathSegments: path.PathSegments[:index+1],
}

rawMap := getRawMap(s.nsPathIdsMap)
Expand Down Expand Up @@ -112,10 +112,10 @@ func (s *authorizeNSServer) Unregister(ctx context.Context, ns *registry.Network
return nil, err
}

index := path.GetIndex()
var leftSide = &registry.Path{
index := path.Index
var leftSide = &grpcmetadata.Path{
Index: index,
PathSegments: path.GetPathSegments()[:index+1],
PathSegments: path.PathSegments[:index+1],
}

rawMap := getRawMap(s.nsPathIdsMap)
Expand Down
12 changes: 6 additions & 6 deletions pkg/registry/common/authorize/nse_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ func (s *authorizeNSEServer) Register(ctx context.Context, nse *registry.Network
return nil, err
}

index := path.GetIndex()
var leftSide = &registry.Path{
index := path.Index
var leftSide = &grpcmetadata.Path{
Index: index,
PathSegments: path.GetPathSegments()[:index+1],
PathSegments: path.PathSegments[:index+1],
}

rawMap := getRawMap(s.nsePathIdsMap)
Expand Down Expand Up @@ -113,10 +113,10 @@ func (s *authorizeNSEServer) Unregister(ctx context.Context, nse *registry.Netwo
return nil, err
}

index := path.GetIndex()
var leftSide = &registry.Path{
index := path.Index
var leftSide = &grpcmetadata.Path{
Index: index,
PathSegments: path.GetPathSegments()[:index+1],
PathSegments: path.PathSegments[:index+1],
}

rawMap := getRawMap(s.nsePathIdsMap)
Expand Down
19 changes: 9 additions & 10 deletions pkg/registry/common/grpcmetadata/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"encoding/json"
"errors"

"github.com/networkservicemesh/api/pkg/api/registry"
"google.golang.org/grpc/metadata"
)

Expand All @@ -31,27 +30,27 @@ const (
pathContextKey pathContextkey = "pathContextKey"
)

// PathFromContext returns registry.Path from context if it exists
func PathFromContext(ctx context.Context) (*registry.Path, error) {
if value, ok := ctx.Value(pathContextKey).(*registry.Path); ok {
// PathFromContext returns Path from context if it exists
func PathFromContext(ctx context.Context) (*Path, error) {
if value, ok := ctx.Value(pathContextKey).(*Path); ok {
return value, nil
}

return nil, errors.New("failed to get registry.Path from context")
return nil, errors.New("failed to get grpcmetadata.Path from context")
}

// PathWithContext puts registry.Path to context
func PathWithContext(ctx context.Context, path *registry.Path) context.Context {
// PathWithContext puts Path to context
func PathWithContext(ctx context.Context, path *Path) context.Context {
return context.WithValue(ctx, pathContextKey, path)
}

func loadFromMetadata(md metadata.MD) (*registry.Path, error) {
func loadFromMetadata(md metadata.MD) (*Path, error) {
pathValue, loaded := md["path"]
if !loaded {
return nil, errors.New("failed to load path from grpc metadata")
}

path := &registry.Path{}
path := &Path{}
err := json.Unmarshal([]byte(pathValue[0]), path)
if err != nil {
return nil, err
Expand All @@ -60,7 +59,7 @@ func loadFromMetadata(md metadata.MD) (*registry.Path, error) {
return path, nil
}

func appendToMetadata(ctx context.Context, path *registry.Path) (context.Context, error) {
func appendToMetadata(ctx context.Context, path *Path) (context.Context, error) {
bytes, err := json.Marshal(path)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion pkg/registry/common/grpcmetadata/ns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func TestGRPCMetadataNetworkService(t *testing.T) {
grpcmetadata.NewNetworkServiceRegistryClient(),
registry.NewNetworkServiceRegistryClient(conn))

path := registry.Path{}
path := grpcmetadata.Path{}
ctx = grpcmetadata.PathWithContext(ctx, &path)

ns := &registry.NetworkService{Name: "ns"}
Expand Down
2 changes: 1 addition & 1 deletion pkg/registry/common/grpcmetadata/nse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func TestGRPCMetadataNetworkServiceEndpoint(t *testing.T) {
grpcmetadata.NewNetworkServiceEndpointRegistryClient(),
registry.NewNetworkServiceEndpointRegistryClient(conn))

path := registry.Path{}
path := grpcmetadata.Path{}
ctx = grpcmetadata.PathWithContext(ctx, &path)

nse := &registry.NetworkServiceEndpoint{Name: "nse"}
Expand Down
71 changes: 71 additions & 0 deletions pkg/registry/common/grpcmetadata/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright (c) 2022 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package grpcmetadata

import (
"time"
)

// PathSegment represents one segment of private registry Path
type PathSegment struct {
Name string
ID string
Token string
Expires time.Time
}

// Path represents private path that is passed via grpcmetadata during NS and NSE registration
type Path struct {
Index uint32
PathSegments []*PathSegment
}

// GetPrevPathSegment returns path.Index - 1 segments if it exists
func (p *Path) GetPrevPathSegment() *PathSegment {
// TODO: move to API (path_helper functions)
if p == nil {
return nil
}
if len(p.PathSegments) == 0 {
return nil
}
if int(p.Index) == 0 {
return nil
}
if int(p.Index)-1 > len(p.PathSegments) {
return nil
}
return p.PathSegments[p.Index-1]
}

// Clone clones Path
func (p *Path) Clone() *Path {
result := &Path{
Index: p.Index,
}

for _, segment := range p.PathSegments {
result.PathSegments = append(result.PathSegments, &PathSegment{
ID: segment.ID,
Name: segment.Name,
Token: segment.Token,
Expires: segment.Expires,
})
}

return result
}
24 changes: 12 additions & 12 deletions pkg/registry/common/updatepath/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
"github.com/google/uuid"
"github.com/pkg/errors"

"github.com/networkservicemesh/api/pkg/api/registry"
"github.com/networkservicemesh/sdk/pkg/registry/common/grpcmetadata"
)

/*
Expand All @@ -37,17 +37,17 @@ Logic for Update path:
2.2 if no next path segment available, it will add one more path segment and generate new Id, update connection.Id.
2.3 if path has next segment available and next name is segmentName, take Id from next path segment.
*/
func updatePath(path *registry.Path, segmentName string) (*registry.Path, uint32, error) {
func updatePath(path *grpcmetadata.Path, segmentName string) (*grpcmetadata.Path, uint32, error) {
if path == nil {
return nil, 0, errors.New("updatePath cannot be called with a nil path")
}
if len(path.GetPathSegments()) == 0 {
if len(path.PathSegments) == 0 {
// 0. Index == 0, and there is no current segment
path.Index = 0
// Add current segment to list
path.PathSegments = append(path.PathSegments, &registry.PathSegment{
path.PathSegments = append(path.PathSegments, &grpcmetadata.PathSegment{
Name: segmentName,
Id: uuid.New().String(),
ID: uuid.New().String(),
})
return path, 0, nil
}
Expand All @@ -60,26 +60,26 @@ func updatePath(path *registry.Path, segmentName string) (*registry.Path, uint32

// We need to move to next item
nextIndex := int(path.Index) + 1
if nextIndex > len(path.GetPathSegments()) {
if nextIndex > len(path.PathSegments) {
// We have index > segments count
return nil, 0, errors.Errorf("Path.Index+1==%d should be less or equal len(Path.PathSegments)==%d",
nextIndex, len(path.GetPathSegments()))
nextIndex, len(path.PathSegments))
}

if nextIndex < len(path.GetPathSegments()) && path.GetPathSegments()[nextIndex].Name != segmentName {
if nextIndex < len(path.PathSegments) && path.PathSegments[nextIndex].Name != segmentName {
// 2.1 path has next segment available, but next name is not equal to segmentName
path.PathSegments[nextIndex].Name = segmentName
path.PathSegments[nextIndex].Id = uuid.New().String()
path.PathSegments[nextIndex].ID = uuid.New().String()
}

// Increment index to be accurate to current chain element
path.Index++

if int(path.Index) >= len(path.GetPathSegments()) {
if int(path.Index) >= len(path.PathSegments) {
// 2.2 no next path segment available
path.PathSegments = append(path.PathSegments, &registry.PathSegment{
path.PathSegments = append(path.PathSegments, &grpcmetadata.PathSegment{
Name: segmentName,
Id: uuid.New().String(),
ID: uuid.New().String(),
})
}

Expand Down
6 changes: 3 additions & 3 deletions pkg/registry/common/updatepath/common_ns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ var nsClientSamples = []*nsClientSample{
})

server := newUpdatePathClient(nse1)
path := &registry.Path{}
path := &grpcmetadata.Path{}
_, err := server.Register(grpcmetadata.PathWithContext(context.Background(), path), &registry.NetworkService{})
require.NoError(t, err)

Expand Down Expand Up @@ -105,7 +105,7 @@ var nsClientSamples = []*nsClientSample{
goleak.VerifyNone(t)
})

var nsPath *registry.Path
var nsPath *grpcmetadata.Path
server := next.NewNetworkServiceRegistryClient(
newUpdatePathClient(nse3),
checkcontext.NewNSClient(t, func(t *testing.T, ctx context.Context) {
Expand All @@ -131,7 +131,7 @@ var nsClientSamples = []*nsClientSample{
goleak.VerifyNone(t)
})

var nsPath *registry.Path
var nsPath *grpcmetadata.Path
server := next.NewNetworkServiceRegistryClient(
newUpdatePathClient(nse3),
checkcontext.NewNSClient(t, func(t *testing.T, ctx context.Context) {
Expand Down
Loading

0 comments on commit 6c48ca3

Please sign in to comment.