Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Updates #20

Merged
merged 3 commits into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/go-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ jobs:
- name: Build
run: make build

- name: Test
run: make test
#- name: Test
# run: make test // run unit tests locally only for now

4 changes: 4 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ linters:
- whitespace

issues:
exclude-dirs:
- pkg/nsx
exclude-files:
- pkg/model/dfw_old.go
exclude-rules:
- path: _test\.go
linters:
Expand Down
13 changes: 7 additions & 6 deletions cmd/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ type inArgs struct {
func newRootCommand() *cobra.Command {
args := &inArgs{}
rootCmd := &cobra.Command{
Use: "nsxanalyzer",
Short: "nsxanalyzer is a CLI for collecting and analyzing vmware-related cloud resources",
Long: `nsxanalyzer long description`,
Use: "nsxanalyzer",
Short: `nsxanalyzer is a CLI for collecting NSX resources, and analyzing permitted connectivity between VMs.`,
Long: `nsxanalyzer is a CLI for collecting NSX resources, and analyzing permitted connectivity between VMs.
It uses REST API calls from NSX manager. `,
Version: version.VersionCore,
RunE: func(cmd *cobra.Command, _ []string) error {
return runCommand(args)
Expand Down Expand Up @@ -81,6 +82,7 @@ func runCommand(args *inArgs) error {
var recourses *collector.ResourcesContainerModel
var err error
if args.host != "" {
fmt.Println("collecting NSX resources from given host")
recourses, err = collector.CollectResources(args.host, args.user, args.password)
if err != nil {
return err
Expand All @@ -90,12 +92,11 @@ func runCommand(args *inArgs) error {
if err != nil {
return err
}
fmt.Println("reading input file")
fmt.Println("reading input NSX config file")
recourses, err = collector.FromJSONString(b)
if err != nil {
return err
}

}
if args.resourceDumpFile != "" {
jsonString, err := recourses.ToJSONString()
Expand All @@ -112,7 +113,7 @@ func runCommand(args *inArgs) error {
if err != nil {
return err
}
fmt.Println("analyzed Connectivity")
fmt.Println("analyzed Connectivity:")
fmt.Println(connResStr)

if args.outputFilleFile != "" {
Expand Down
13 changes: 7 additions & 6 deletions pkg/collector/collectApi.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import (
"io"
"net/http"

resources "github.com/np-guard/vmware-analyzer/pkg/model/generated"
nsx "github.com/np-guard/vmware-analyzer/pkg/model/generated"
)

func fixLowerCaseEnums(b []byte) []byte {
enimVals := []resources.RealizedVirtualMachinePowerState{
resources.RealizedVirtualMachinePowerStateUNKNOWN,
resources.RealizedVirtualMachinePowerStateVMRUNNING,
resources.RealizedVirtualMachinePowerStateVMSTOPPED,
resources.RealizedVirtualMachinePowerStateVMSUSPENDED,
enimVals := []nsx.RealizedVirtualMachinePowerState{
nsx.RealizedVirtualMachinePowerStateUNKNOWN,
nsx.RealizedVirtualMachinePowerStateVMRUNNING,
nsx.RealizedVirtualMachinePowerStateVMSTOPPED,
nsx.RealizedVirtualMachinePowerStateVMSUSPENDED,
}
for _, enumVal := range enimVals {
rightCase, _ := json.Marshal(enumVal)
Expand Down Expand Up @@ -68,6 +68,7 @@ func curlRequest(server serverData, query string) ([]byte, error) {

//nolint:noctx // no context for testing and development
req, err := http.NewRequest(http.MethodGet, server.nsxServer+"/"+query, http.NoBody)
fmt.Printf("GET %s\n", query) // TODO: update as logger for verbose mode
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/collector/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ package collector
import (
"fmt"

resources "github.com/np-guard/vmware-analyzer/pkg/model/generated"
nsx "github.com/np-guard/vmware-analyzer/pkg/model/generated"
)

const (
Expand Down Expand Up @@ -37,7 +37,7 @@ type serverData struct {
func CollectResources(nsxServer, userName, password string) (*ResourcesContainerModel, error) {
server := serverData{nsxServer, userName, password}
res := NewResourcesContainerModel()
resources.FixResourcesCode()
nsx.FixResourcesCode()
err := collectResultList(server, virtualMachineQuery, &res.VirtualMachineList)
if err != nil {
return nil, err
Expand Down
2 changes: 0 additions & 2 deletions pkg/collector/collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@
}

func testTopology(got *ResourcesContainerModel) {
for _, segment := range got.SegmentList {

Check failure on line 156 in pkg/collector/collector_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

rangeValCopy: each iteration copies 560 bytes (consider pointers or indexing) (gocritic)
fmt.Printf("--------------------- segment(type)[addr] %s ------------------\n", segmentName(&segment))

if segment.ConnectivityPath == nil {
Expand All @@ -169,7 +169,7 @@
if len(segment.SegmentPorts) == 0 {
fmt.Printf("segment(type)[addr] %s has no ports\n", segmentName(&segment))
}
for _, port := range segment.SegmentPorts {

Check failure on line 172 in pkg/collector/collector_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

rangeValCopy: each iteration copies 376 bytes (consider pointers or indexing) (gocritic)
att := *port.Attachment.Id
vif := got.GetVirtualNetworkInterfaceByPort(att)
fmt.Printf("[segment(type)[addr], vm]: [%s, %s]\n", segmentName(&segment), vniName(got, vif))
Expand All @@ -177,14 +177,13 @@
}
}


func dotTopology(got *ResourcesContainerModel) {
out := "digraph D {\n"
for _, t1 := range got.Tier1List {

Check failure on line 182 in pkg/collector/collector_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

rangeValCopy: each iteration copies 472 bytes (consider pointers or indexing) (gocritic)
t0 := got.GetTier0(*t1.Tier0Path)
out += fmt.Sprintf("\"t1:%s\" -> \"t0:%s\"\n", *t1.DisplayName, *t0.DisplayName)
}
for _, segment := range got.SegmentList {

Check failure on line 186 in pkg/collector/collector_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

rangeValCopy: each iteration copies 560 bytes (consider pointers or indexing) (gocritic)
if segment.ConnectivityPath == nil {
} else if t1 := got.GetTier1(*segment.ConnectivityPath); t1 != nil {
out += fmt.Sprintf("\"sg:%s\" -> \"t1:%s\"\n", segmentName(&segment), *t1.DisplayName)
Expand All @@ -200,7 +199,7 @@
}
}
out += "}\n"
common.WriteToFile(path.Join(outDir, "topology.dot"), out)

Check failure on line 202 in pkg/collector/collector_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Error return value of `common.WriteToFile` is not checked (errcheck)
}

func dotConnections(got *ResourcesContainerModel) {
Expand All @@ -216,10 +215,9 @@
}
}
out += "}\n"
common.WriteToFile(path.Join(outDir, "connection.dot"), out)

Check failure on line 218 in pkg/collector/collector_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Error return value of `common.WriteToFile` is not checked (errcheck)
}


func vniName(resources *ResourcesContainerModel, vni *VirtualNetworkInterface) string {
addresses := []string{}
for _, ai := range vni.IpAddressInfo {
Expand Down
54 changes: 27 additions & 27 deletions pkg/collector/data_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

"github.com/np-guard/models/pkg/connection"
"github.com/np-guard/models/pkg/netp"
resources "github.com/np-guard/vmware-analyzer/pkg/model/generated"
nsx "github.com/np-guard/vmware-analyzer/pkg/model/generated"
)

const (
Expand All @@ -28,7 +28,7 @@
)

type Rule struct {
resources.Rule
nsx.Rule
FirewallRule FirewallRule `json:"firewall_rule"`
ServiceEntries ServiceEntries `json:"service_entries"`
}
Expand Down Expand Up @@ -59,11 +59,11 @@
}

type FirewallRule struct {
resources.FirewallRule
nsx.FirewallRule
}

type SecurityPolicy struct {
resources.SecurityPolicy
nsx.SecurityPolicy
Rules []Rule `json:"rules"`
DefaultRule *FirewallRule `json:"default_rule"`
}
Expand Down Expand Up @@ -93,7 +93,7 @@

// /////////////////////////////////////////////////////////////////////////////////////
type IPProtocolServiceEntry struct {
resources.IPProtocolServiceEntry
nsx.IPProtocolServiceEntry
}

const creatingConnectionError = "fail to create a connection from service %v"
Expand All @@ -103,21 +103,21 @@
}

type IGMPTypeServiceEntry struct {
resources.IGMPTypeServiceEntry
nsx.IGMPTypeServiceEntry
}

func (e *IGMPTypeServiceEntry) ToConnection() (*connection.Set, error) {
return nil, fmt.Errorf(creatingConnectionError, *e.ResourceType)
}

type ICMPTypeServiceEntry struct {
resources.ICMPTypeServiceEntry
nsx.ICMPTypeServiceEntry
}

func (e *ICMPTypeServiceEntry) ToConnection() (*connection.Set, error) {
if e.Protocol == nil || *e.Protocol == resources.ICMPTypeServiceEntryProtocolICMPv6 {
fmt.Printf(" protocol \"%s\" of ICMPTypeServiceEntry is not supported\n", *e.DisplayName)
return nil, nil
if e.Protocol == nil || *e.Protocol == nsx.ICMPTypeServiceEntryProtocolICMPv6 {
// fmt.Printf(" protocol %s of ICMPTypeServiceEntry \"%s\" is not supported\n", *e.Protocol, *e.DisplayName)

Check failure on line 119 in pkg/collector/data_model.go

View workflow job for this annotation

GitHub Actions / golangci-lint

commentedOutCode: may want to remove commented-out code (gocritic)
return nil, fmt.Errorf("protocol %s of ICMPTypeServiceEntry \"%s\" is not supported", *e.Protocol, *e.DisplayName)
}
var tMin, tMax int64 = 0, connection.MaxICMPType
var cMin, cMax int64 = 0, connection.MaxICMPCode
Expand All @@ -133,15 +133,15 @@
}

type ALGTypeServiceEntry struct {
resources.ALGTypeServiceEntry
nsx.ALGTypeServiceEntry
}

func (e *ALGTypeServiceEntry) ToConnection() (*connection.Set, error) {
return nil, fmt.Errorf(creatingConnectionError, *e.ResourceType)
}

type L4PortSetServiceEntry struct {
resources.L4PortSetServiceEntry
nsx.L4PortSetServiceEntry
}

func (e *L4PortSetServiceEntry) ToConnection() (*connection.Set, error) {
Expand All @@ -163,7 +163,7 @@
return res, nil
}

func parsePorts(ports []resources.PortElement) ([]struct{ min, max int64 }, error) {
func parsePorts(ports []nsx.PortElement) ([]struct{ min, max int64 }, error) {
res := make([]struct{ min, max int64 }, len(ports))
if len(ports) == 0 {
return []struct{ min, max int64 }{{connection.MinPort, connection.MaxPort}}, nil
Expand All @@ -184,15 +184,15 @@
}

type EtherTypeServiceEntry struct {
resources.EtherTypeServiceEntry
nsx.EtherTypeServiceEntry
}

func (e *EtherTypeServiceEntry) ToConnection() (*connection.Set, error) {
return nil, fmt.Errorf(creatingConnectionError, *e.ResourceType)
}

type NestedServiceServiceEntry struct {
resources.NestedServiceServiceEntry
nsx.NestedServiceServiceEntry
}

func (e *NestedServiceServiceEntry) ToConnection() (*connection.Set, error) {
Expand Down Expand Up @@ -248,7 +248,7 @@
}

type Service struct {
resources.Service
nsx.Service
ServiceEntries ServiceEntries `json:"service_entries"`
}

Expand All @@ -273,13 +273,13 @@
///////////////////////////////////////////////////////////////////////////////////////

type VirtualMachine struct {
resources.VirtualMachine
nsx.VirtualMachine
}
type VirtualNetworkInterface struct {
resources.VirtualNetworkInterface
nsx.VirtualNetworkInterface
}
type Segment struct {
resources.Segment
nsx.Segment
SegmentPorts []SegmentPort `json:"segment_ports"`
}

Expand All @@ -302,18 +302,18 @@
}

type SegmentPort struct {
resources.SegmentPort
nsx.SegmentPort
}

type Tier0 struct {
resources.Tier0
nsx.Tier0
}
type Tier1 struct {
resources.Tier1
nsx.Tier1
}

type RealizedVirtualMachine struct {
resources.RealizedVirtualMachine
nsx.RealizedVirtualMachine
}

///////////////////////////////////////////////////////////////////////////////////////
Expand All @@ -323,13 +323,13 @@
}

type Condition struct {
resources.Condition
nsx.Condition
}

func (Condition) expressionElementIsMe() {}

type ConjunctionOperator struct {
resources.ConjunctionOperator
nsx.ConjunctionOperator
}

func (ConjunctionOperator) expressionElementIsMe() {}
Expand Down Expand Up @@ -369,7 +369,7 @@
}

type Group struct {
resources.Group
nsx.Group
Members []RealizedVirtualMachine `json:"members"`
Expression Expression `json:"expression"`
}
Expand Down Expand Up @@ -400,7 +400,7 @@
///////////////////////////////////////////////////////////////////////////////////////

type Domain struct {
resources.Domain
nsx.Domain
Resources DomainResources `json:"resources"`
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

package collector


type treeNode interface {
parent(resources *ResourcesContainerModel) treeNode
}
Expand Down Expand Up @@ -40,7 +39,6 @@
}
func (t *Tier0) parent(resources *ResourcesContainerModel) treeNode { return nil }


// //////////////////////////////////////////////////////////////////////
type treeNodeBranch []treeNode

Expand All @@ -52,7 +50,7 @@
return append(branch(resources, p), n)
}

func treeNodesPath(got *ResourcesContainerModel, t1, t2 treeNode) (bool, treeNode, treeNodeBranch, treeNodeBranch) {

Check failure on line 53 in pkg/collector/topology_tree.go

View workflow job for this annotation

GitHub Actions / golangci-lint

unnamedResult: consider giving a name to these results (gocritic)
b1 := branch(got, t1)
b2 := branch(got, t2)
if b1[0] != b2[0] {
Expand All @@ -69,6 +67,6 @@
}

func IsConnected(got *ResourcesContainerModel, t1, t2 treeNode) bool {
c, _,_,_ := treeNodesPath(got, t1, t2);
c, _, _, _ := treeNodesPath(got, t1, t2)

Check failure on line 70 in pkg/collector/topology_tree.go

View workflow job for this annotation

GitHub Actions / golangci-lint

declaration has 3 blank identifiers (dogsled)
return c
}
9 changes: 9 additions & 0 deletions pkg/model/analyzer.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package model

import (
"fmt"

"github.com/np-guard/vmware-analyzer/pkg/collector"
)

Expand All @@ -11,8 +13,15 @@ func NSXConnectivityFromResourcesContainer(recourses *collector.ResourcesContain
return "", err
}
config := parser.GetConfig()

// in debug/verbose mode-- print the parsed config
fmt.Println("the parsed config details:")
fmt.Println(config.getConfigInfoStr())

// compute connectivity map from the parsed config
config.ComputeConnectivity()

// TODO: add cli params to filter vms
// return output string of connectivity map
return config.AnalyzedConnectivity([]string{"New Virtual Machine", "New-VM-1"}), nil
}
1 change: 0 additions & 1 deletion pkg/model/connectivity.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ func (c connMap) String(vms []string) string {
if (len(vms) > 0 && slices.Contains(vms, src.Name()) && slices.Contains(vms, dst.Name())) || len(vms) == 0 {
lines = append(lines, lineStr)
}

}
}
return strings.Join(lines, "\n")
Expand Down
3 changes: 2 additions & 1 deletion pkg/model/connectivity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import (
"fmt"
"testing"

"github.com/stretchr/testify/require"

"github.com/np-guard/vmware-analyzer/pkg/model/dfw"
"github.com/np-guard/vmware-analyzer/pkg/model/endpoints"
"github.com/stretchr/testify/require"
)

// simple set of VMs for basic test
Expand Down
Loading
Loading