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

Handling selectors with match expression #365

Closed
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
8 changes: 4 additions & 4 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ jobs:

steps:
- name: Checkout repository
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@23acc5c183826b7a8a97bce3cecc52db901f8251
uses: github/codeql-action/init@9fdb3e49720b44c48891d036bb502feb25684276
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
Expand All @@ -56,7 +56,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@23acc5c183826b7a8a97bce3cecc52db901f8251
uses: github/codeql-action/autobuild@9fdb3e49720b44c48891d036bb502feb25684276

# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
Expand All @@ -70,4 +70,4 @@ jobs:
# make release

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@23acc5c183826b7a8a97bce3cecc52db901f8251
uses: github/codeql-action/analyze@9fdb3e49720b44c48891d036bb502feb25684276
2 changes: 1 addition & 1 deletion .github/workflows/go-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332
- uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29

- name: Set up Go
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
name: golangci-lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332
- uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29
- uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7
with:
go-version-file: ./go.mod
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/make-release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29

- name: Set up Go
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
github.com/hashicorp/golang-lru/v2 v2.0.7
github.com/np-guard/models v0.3.2
github.com/openshift/api v0.0.0-20230502160752-c71432710382
github.com/spf13/cobra v1.8.1
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.9.0
k8s.io/api v0.29.2
k8s.io/apimachinery v0.29.2
Expand Down
6 changes: 3 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWR
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand Down Expand Up @@ -113,8 +113,8 @@ github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncj
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand Down
15 changes: 11 additions & 4 deletions pkg/cli/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ func getRequiredOutputFormatString(validFormats string) string {
return fmt.Sprintf("Required output format (%s)", validFormats)
}

// getListOutputFormatDescription returns the description of the required formats of the list command
// exposure analysis is supported with less formats
func getListOutputFormatDescription() string {
comma := ","
supportedFormats := strings.Join(connlist.ValidFormats, comma)
supportedExposureFormats := strings.Join(connlist.ExposureValidFormats, comma)
return getRequiredOutputFormatString(supportedFormats) + " or (" + supportedExposureFormats + " with exposure analysis) "
}

func runListCommand() error {
var conns []connlist.Peer2PeerConnection
var err error
Expand Down Expand Up @@ -102,7 +111,7 @@ defined`,
k8snetpolicy list -k ./kube/config`,

PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := connlist.ValidateOutputFormat(output); err != nil {
if err := connlist.ValidateOutputFormat(output, exposureAnalysis); err != nil {
return err
}
// call parent pre-run
Expand Down Expand Up @@ -131,9 +140,7 @@ defined`,
"Focus connections of specified workload in the output (<workload-name> or <workload-namespace/workload-name>)")
c.Flags().BoolVarP(&exposureAnalysis, "exposure", "", false, "Turn on exposure analysis and append results to the output")
// output format - default txt
// output format - default txt
supportedFormats := strings.Join(connlist.ValidFormats, ",")
c.Flags().StringVarP(&output, "output", "o", outconsts.DefaultFormat, getRequiredOutputFormatString(supportedFormats))
c.Flags().StringVarP(&output, "output", "o", outconsts.DefaultFormat, getListOutputFormatDescription())
// out file
c.Flags().StringVarP(&outFile, "file", "f", "", "Write output to specified file")

Expand Down
32 changes: 16 additions & 16 deletions pkg/netpol/connlist/connlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ type ConnlistAnalyzer struct {
exposureResult []ExposedPeer
outputFormat string
muteErrsAndWarns bool
peersList []Peer // internally used peersList used in dot formatting; in case of focusWorkload option contains only relevant peers
}

// The new interface
Expand Down Expand Up @@ -102,6 +101,8 @@ func (ca *ConnlistAnalyzer) ConnlistFromDirPath(dirPath string) ([]Peer2PeerConn
var ValidFormats = []string{output.TextFormat, output.JSONFormat, output.DOTFormat,
output.CSVFormat, output.MDFormat}

var ExposureValidFormats = []string{output.TextFormat, output.DOTFormat}

// ConnlistAnalyzerOption is the type for specifying options for ConnlistAnalyzer,
// using Golang's Options Pattern (https://golang.cafe/blog/golang-functional-options-pattern.html).
type ConnlistAnalyzerOption func(*ConnlistAnalyzer)
Expand Down Expand Up @@ -274,7 +275,7 @@ func (ca *ConnlistAnalyzer) ConnectionsListToString(conns []Peer2PeerConnection)
ca.errors = append(ca.errors, newResultFormattingError(err))
return "", err
}
out, err := connsFormatter.writeOutput(conns, ca.exposureResult, ca.exposureAnalysis)
out, err := connsFormatter.writeOutput(conns, ca.exposureResult)
if err != nil {
ca.errors = append(ca.errors, newResultFormattingError(err))
return "", err
Expand All @@ -283,8 +284,12 @@ func (ca *ConnlistAnalyzer) ConnectionsListToString(conns []Peer2PeerConnection)
}

// validate the value of the output format
func ValidateOutputFormat(format string) error {
for _, formatName := range ValidFormats {
func ValidateOutputFormat(format string, exposureFlag bool) error {
formatList := ValidFormats
if exposureFlag {
formatList = ExposureValidFormats
}
for _, formatName := range formatList {
if format == formatName {
return nil
}
Expand All @@ -294,7 +299,7 @@ func ValidateOutputFormat(format string) error {

// returns the relevant formatter for the analyzer's outputFormat
func (ca *ConnlistAnalyzer) getFormatter() (connsFormatter, error) {
if err := ValidateOutputFormat(ca.outputFormat); err != nil {
if err := ValidateOutputFormat(ca.outputFormat, ca.exposureAnalysis); err != nil {
return nil, err
}
switch ca.outputFormat {
Expand All @@ -303,7 +308,7 @@ func (ca *ConnlistAnalyzer) getFormatter() (connsFormatter, error) {
case output.TextFormat:
return &formatText{}, nil
case output.DOTFormat:
return &formatDOT{ca.peersList}, nil
return &formatDOT{}, nil
case output.CSVFormat:
return &formatCSV{}, nil
case output.MDFormat:
Expand Down Expand Up @@ -403,7 +408,8 @@ func getPeerNsNameFormat(peer Peer) string {
// isPeerFocusWorkload returns true if focus-workload flag is not used (each peer is included),
// or if the focus-workload is equal to peer's name
func (ca *ConnlistAnalyzer) isPeerFocusWorkload(peer Peer) bool {
return ca.focusWorkload == "" || peer.Name() == ca.focusWorkload || getPeerNsNameFormat(peer) == ca.focusWorkload
return ca.focusWorkload == "" ||
(!peer.IsPeerIPType() && (peer.Name() == ca.focusWorkload || getPeerNsNameFormat(peer) == ca.focusWorkload))
}

func convertEvalPeersToConnlistPeer(peers []eval.Peer) []Peer {
Expand Down Expand Up @@ -438,17 +444,11 @@ func (ca *ConnlistAnalyzer) getConnectionsList(pe *eval.PolicyEngine, ia *ingres
representativePeers := pe.GetRepresentativePeersList()
connPeers = append(connPeers, convertEvalPeersToConnlistPeer(representativePeers)...)
}
ca.peersList = make([]Peer, 0, len(peerList))
for _, p := range peerList {
if ca.isPeerFocusWorkload(p) {
ca.peersList = append(ca.peersList, p)
}
}

excludeIngressAnalysis := (ia == nil || ia.IsEmpty())

// if ca.focusWorkload is not empty, check if it exists in the peers before proceeding
existFocusWorkload, warningMsg := ca.existsFocusWorkload(excludeIngressAnalysis)
existFocusWorkload, warningMsg := ca.existsFocusWorkload(peers, excludeIngressAnalysis)
if ca.focusWorkload != "" && !existFocusWorkload {
ca.errors = append(ca.errors, newConnlistAnalyzerWarning(errors.New(warningMsg)))
ca.logWarning(warningMsg)
Expand Down Expand Up @@ -490,7 +490,7 @@ func (ca *ConnlistAnalyzer) getConnectionsList(pe *eval.PolicyEngine, ia *ingres
// existsFocusWorkload checks if the provided focus workload is ingress-controller
// or if it exists in the peers list from the parsed resources
// if not returns a suitable warning message
func (ca *ConnlistAnalyzer) existsFocusWorkload(excludeIngressAnalysis bool) (existFocusWorkload bool, warning string) {
func (ca *ConnlistAnalyzer) existsFocusWorkload(peers []Peer, excludeIngressAnalysis bool) (existFocusWorkload bool, warning string) {
if ca.focusWorkload == common.IngressPodName {
if excludeIngressAnalysis { // if the ingress-analyzer is empty,
// then no routes/k8s-ingress objects -> ingrss-controller pod will not be added
Expand All @@ -500,7 +500,7 @@ func (ca *ConnlistAnalyzer) existsFocusWorkload(excludeIngressAnalysis bool) (ex
}

// check if the focusworkload is in the peers
for _, peer := range ca.peersList {
for _, peer := range peers {
if ca.isPeerFocusWorkload(peer) {
return true, ""
}
Expand Down
Loading