diff --git a/api/go.sum b/api/go.sum index 622c112fc..f2ffd3bd6 100644 --- a/api/go.sum +++ b/api/go.sum @@ -1,31 +1,17 @@ -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= 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/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= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/evanphx/json-patch/v5 v5.6.0/go.mod h1:G79N1coSVB93tBe7j6PhzjmR3/2VvlbKOFpnXhI9Bw4= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/zapr v1.2.3/go.mod h1:eIauM6P8qSvTw5o2ez6UEAfGjQKrxQTl5EoK+Qa2oG4= -github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= -github.com/go-openapi/jsonreference v0.20.1/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= -github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -33,88 +19,61 @@ github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/matttproud/golang_protobuf_extensions v1.0.2/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/onsi/ginkgo/v2 v2.9.7 h1:06xGQy5www2oN160RtEZoTvnP2sPhEfePYmCDc2szss= github.com/onsi/ginkgo/v2 v2.9.7/go.mod h1:cxrmXWykAwTwhQsJOPfdIDiJ+l2RYq7U8hFU+M/1uw0= github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc= github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= -github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= -github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA= -github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= 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= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk= -golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -125,10 +84,7 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gomodules.xyz/jsonpatch/v2 v2.2.0/go.mod h1:WXp+iVDkoLQqPudfQ9GBlwB2eZ5DKOnjQZCYdOS8GPY= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -142,14 +98,10 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/api v0.26.3 h1:emf74GIQMTik01Aum9dPP0gAypL8JTLl/lHa4V9RFSU= k8s.io/api v0.26.3/go.mod h1:PXsqwPMXBSBcL1lJ9CYDKy7kIReUydukS5JiRlxC3qE= -k8s.io/apiextensions-apiserver v0.26.1/go.mod h1:AptjOSXDGuE0JICx/Em15PaoO7buLwTs0dGleIHixSM= k8s.io/apimachinery v0.27.4 h1:CdxflD4AF61yewuid0fLl6bM4a3q04jWel0IlP+aYjs= k8s.io/apimachinery v0.27.4/go.mod h1:XNfZ6xklnMCOGGFNqXG7bUrQCoR04dh/E7FprV6pb+E= -k8s.io/client-go v0.26.1/go.mod h1:IWNSglg+rQ3OcvDkhY6+QLeasV4OYHDjdqeWkDQZwGE= -k8s.io/component-base v0.26.1/go.mod h1:VHrLR0b58oC035w6YQiBSbtsf0ThuSwXP+p5dD/kAWU= k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f/go.mod h1:byini6yhqGC14c3ebc/QwanvYwhuMWF6yz2F8uwW8eg= k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= sigs.k8s.io/controller-runtime v0.14.6 h1:oxstGVvXGNnMvY7TAESYk+lzr6S3V5VFxQ6d92KcwQA= diff --git a/docs/examples/lldp.yaml b/docs/examples/lldp.yaml index f4887c1b6..078da272a 100644 --- a/docs/examples/lldp.yaml +++ b/docs/examples/lldp.yaml @@ -5,7 +5,7 @@ metadata: spec: capture: ethernets: interfaces.type=="ethernet" - ethernets-up: capture.ethernets | interfaces.state=="up" ethernets-lldp: capture.ethernets-up | interfaces.lldp.enabled:=true + ethernets-up: capture.ethernets | interfaces.state=="up" desiredState: interfaces: "{{ capture.ethernets-lldp.interfaces }}" diff --git a/go.mod b/go.mod index b2607d94a..2aa45b68b 100644 --- a/go.mod +++ b/go.mod @@ -105,7 +105,6 @@ require ( github.com/gofrs/flock v0.7.1 github.com/kelseyhightower/envconfig v1.4.0 github.com/nmstate/kubernetes-nmstate/api v0.0.0-00010101000000-000000000000 - github.com/nmstate/nmpolicy v0.6.0 github.com/openshift/api v0.0.0-20230803134339-2d9b46419536 github.com/openshift/cluster-network-operator v0.0.0-20200922032245-f47200e8dbc0 github.com/phoracek/networkmanager-go v0.3.0 diff --git a/go.sum b/go.sum index 7f51d6956..64a24a9f4 100644 --- a/go.sum +++ b/go.sum @@ -121,6 +121,7 @@ github.com/aws/aws-sdk-go v1.25.48/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpi github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= +github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -639,6 +640,7 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= @@ -742,8 +744,6 @@ github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+ github.com/nakagami/firebirdsql v0.0.0-20190310045651-3c02a58cfed8/go.mod h1:86wM1zFnC6/uDBfZGNwB65O+pR2OFi5q/YQaEUid1qA= github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/nmstate/nmpolicy v0.6.0 h1:6qtm0lHjXAFh2fnTy38o7Fssbv8Ya/5/K1WT2YW5jb0= -github.com/nmstate/nmpolicy v0.6.0/go.mod h1:jXA9IOzfrcVDqu08Q1e8M4JbhNDuFxU1MvjwOy4JZ80= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= @@ -763,6 +763,7 @@ github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+ github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU= github.com/onsi/ginkgo/v2 v2.1.6/go.mod h1:MEH45j8TBi6u9BMogfbp0stKC5cdGjumZj5Y7AG4VIk= @@ -911,6 +912,7 @@ github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.5.0/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rubenv/sql-migrate v0.0.0-20191025130928-9355dd04f4b3/go.mod h1:WS0rl9eEliYI8DPnr3TOwz4439pay+qNgzJoVya/DmY= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= @@ -927,6 +929,7 @@ github.com/sclevine/spec v1.2.0/go.mod h1:W4J29eT/Kzv7/b9IWLB055Z+qvVC9vt0Arko24 github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= 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/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= @@ -1060,6 +1063,7 @@ go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/automaxprocs v1.2.0/go.mod h1:YfO3fm683kQpzETxlTGZhGIVmXAhaw3gxeBADbpZtnU= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= +go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= go.uber.org/multierr v0.0.0-20180122172545-ddea229ff1df/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= @@ -1138,6 +1142,7 @@ golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2 golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI= golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk= +golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1573,6 +1578,7 @@ gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= +gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= helm.sh/helm/v3 v3.1.0/go.mod h1:WYsFJuMASa/4XUqLyv54s0U/f3mlAaRErGmyy4z921g= helm.sh/helm/v3 v3.1.2/go.mod h1:WYsFJuMASa/4XUqLyv54s0U/f3mlAaRErGmyy4z921g= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/pkg/nmpolicy/generate.go b/pkg/nmpolicy/generate.go index 105ca169a..04e70dd9f 100644 --- a/pkg/nmpolicy/generate.go +++ b/pkg/nmpolicy/generate.go @@ -18,105 +18,55 @@ limitations under the License. package nmpolicy import ( - "github.com/nmstate/nmpolicy/nmpolicy" - nmpolicytypes "github.com/nmstate/nmpolicy/nmpolicy/types" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "encoding/json" nmstateapi "github.com/nmstate/kubernetes-nmstate/api/shared" + "github.com/nmstate/kubernetes-nmstate/pkg/nmstatectl" ) -type NMPolicyGenerator interface { - GenerateState( - nmpolicySpec nmpolicytypes.PolicySpec, - currentState []byte, - cache nmpolicytypes.CachedState, - ) (nmpolicytypes.GeneratedState, error) -} - -type GenerateStateWithNMPolicy struct{} - -func (GenerateStateWithNMPolicy) GenerateState( - nmpolicySpec nmpolicytypes.PolicySpec, - currentState []byte, - cache nmpolicytypes.CachedState, -) (nmpolicytypes.GeneratedState, error) { - return nmpolicy.GenerateState(nmpolicySpec, currentState, cache) -} - -// The method generates the state using the default NMPolicyGenerator -func GenerateState(desiredState nmstateapi.State, - policySpec nmstateapi.NodeNetworkConfigurationPolicySpec, - currentState nmstateapi.State, - cachedState map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState) ( - map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState, /* resolved captures */ - nmstateapi.State, /* updated desired state */ - error) { - return GenerateStateWithStateGenerator(GenerateStateWithNMPolicy{}, desiredState, policySpec, currentState, cachedState) -} - -// The method generates the state using NMPolicyGenerator.GenerateState and then converts the returned value to the match the enactment api -func GenerateStateWithStateGenerator(stateGenerator NMPolicyGenerator, +func GenerateState( desiredState nmstateapi.State, policySpec nmstateapi.NodeNetworkConfigurationPolicySpec, currentState nmstateapi.State, cachedState map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState) ( - map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState, - nmstateapi.State, error) { - nmpolicySpec := nmpolicytypes.PolicySpec{ + map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState, nmstateapi.State, error) { + if len(desiredState.Raw) == 0 || len(currentState.Raw) == 0 { + return map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{}, + nmstateapi.State{}, nil + } + nmstatePolicy := struct { + Capture map[string]string `json:"capture,omitempty"` + DesiredState nmstateapi.State `json:"desiredState,omitempty"` + }{ Capture: policySpec.Capture, - DesiredState: []byte(desiredState.Raw), + DesiredState: policySpec.DesiredState, } - nmpolicyGeneratedState, err := stateGenerator.GenerateState( - nmpolicySpec, - currentState.Raw, - convertCachedStateFromEnactment(cachedState), - ) + + nmstatePolicyRaw, err := json.Marshal(nmstatePolicy) if err != nil { return map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{}, nmstateapi.State{}, err } - - capturedStates, desiredState := convertGeneratedStateToEnactmentConfig(nmpolicyGeneratedState) - return capturedStates, desiredState, nil -} - -func convertGeneratedStateToEnactmentConfig(nmpolicyGeneratedState nmpolicytypes.GeneratedState) ( - map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState, nmstateapi.State) { - capturedStates := map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{} - - for captureKey, capturedState := range nmpolicyGeneratedState.Cache.Capture { - capturedState := nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{ - State: nmstateapi.State{ - Raw: []byte(capturedState.State), - }, - MetaInfo: convertMetaInfoToEnactment(capturedState.MetaInfo), + cachedStateRaw := []byte{} + if len(cachedState) > 0 { + cachedStateRaw, err = json.Marshal(cachedState) + if err != nil { + return map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{}, + nmstateapi.State{}, err } - capturedStates[captureKey] = capturedState } - return capturedStates, nmstateapi.State{Raw: []byte(nmpolicyGeneratedState.DesiredState)} -} -func convertCachedStateFromEnactment( - enactmentCachedState map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState, -) nmpolicytypes.CachedState { - cachedState := nmpolicytypes.CachedState{Capture: make(map[string]nmpolicytypes.CaptureState)} - for captureKey, capturedState := range enactmentCachedState { - capturedState := nmpolicytypes.CaptureState{ - State: nmpolicytypes.NMState(capturedState.State.Raw), - MetaInfo: nmpolicytypes.MetaInfo{ - Version: capturedState.MetaInfo.Version, - TimeStamp: capturedState.MetaInfo.TimeStamp.Time, - }, - } - cachedState.Capture[captureKey] = capturedState + output, capturedStateRaw, err := nmstatectl.Policy(nmstatePolicyRaw, []byte(currentState.Raw), cachedStateRaw) + if err != nil { + return map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{}, + nmstateapi.State{}, err } - return cachedState -} -func convertMetaInfoToEnactment(metaInfo nmpolicytypes.MetaInfo) nmstateapi.NodeNetworkConfigurationEnactmentMetaInfo { - return nmstateapi.NodeNetworkConfigurationEnactmentMetaInfo{ - Version: metaInfo.Version, - TimeStamp: metav1.NewTime(metaInfo.TimeStamp), + capturedState := map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{} + if err := json.Unmarshal(capturedStateRaw, &capturedState); err != nil { + return map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{}, + nmstateapi.State{}, err } + + return capturedState, nmstateapi.State{Raw: output}, nil } diff --git a/pkg/nmpolicy/generate_test.go b/pkg/nmpolicy/generate_test.go deleted file mode 100644 index 52404e1bd..000000000 --- a/pkg/nmpolicy/generate_test.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright The Kubernetes NMState Authors. - - -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 nmpolicy - -import ( - "fmt" - "time" - - nmstateapi "github.com/nmstate/kubernetes-nmstate/api/shared" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - nmpolicytypes "github.com/nmstate/nmpolicy/nmpolicy/types" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -var _ = Describe("NMPolicy GenerateState", func() { - When("fails", func() { - It("Should return an error", func() { - capturedState, desiredState, err := GenerateStateWithStateGenerator( - nmpolicyStub{shouldFail: true}, - nmstateapi.State{}, - nmstateapi.NodeNetworkConfigurationPolicySpec{}, - nmstateapi.State{}, - map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{}, - ) - Expect(err).To(HaveOccurred()) - Expect(capturedState).To(Equal(map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{})) - Expect(desiredState).To(Equal(nmstateapi.State{})) - }) - - }) - - When("succeeds", func() { - const desiredStateYaml = `desire state yaml` - const captureYaml1 = `default-gw expression` - const captureYaml2 = `base-iface expression` - const metaVersion = "5" - metaTime := time.Now() - - nmpolicyMetaInfo := nmpolicytypes.MetaInfo{ - Version: metaVersion, - TimeStamp: metaTime, - } - - generatedState := nmpolicytypes.GeneratedState{ - DesiredState: []byte(desiredStateYaml), - Cache: nmpolicytypes.CachedState{ - Capture: map[string]nmpolicytypes.CaptureState{ - "default-gw": {State: []byte(captureYaml1), MetaInfo: nmpolicyMetaInfo}, - "base-iface": {State: []byte(captureYaml2)}, - }, - }, - } - - capturedStates, desiredState, err := GenerateStateWithStateGenerator( - nmpolicyStub{output: generatedState}, - nmstateapi.State{}, - nmstateapi.NodeNetworkConfigurationPolicySpec{}, - nmstateapi.State{}, - map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{}, - ) - - Expect(err).NotTo(HaveOccurred()) - - expectedMetaInfo := nmstateapi.NodeNetworkConfigurationEnactmentMetaInfo{ - Version: metaVersion, - TimeStamp: metav1.NewTime(metaTime), - } - - expectedcCaptureCache := map[string]nmstateapi.NodeNetworkConfigurationEnactmentCapturedState{ - "default-gw": {State: nmstateapi.State{Raw: []byte(captureYaml1)}, MetaInfo: expectedMetaInfo}, - "base-iface": {State: nmstateapi.State{Raw: []byte(captureYaml2)}}, - } - - Expect(capturedStates).To(Equal(expectedcCaptureCache)) - Expect(desiredState).To(Equal(nmstateapi.State{Raw: []byte(desiredStateYaml)})) - }) -}) - -type nmpolicyStub struct { - shouldFail bool - output nmpolicytypes.GeneratedState -} - -func (n nmpolicyStub) GenerateState( - nmpolicySpec nmpolicytypes.PolicySpec, - currentState []byte, - cache nmpolicytypes.CachedState, -) (nmpolicytypes.GeneratedState, error) { - if n.shouldFail { - return nmpolicytypes.GeneratedState{}, fmt.Errorf("GenerateStateFailed") - } - return n.output, nil -} diff --git a/pkg/nmstatectl/nmstatectl.go b/pkg/nmstatectl/nmstatectl.go index c00082000..cfeb50289 100644 --- a/pkg/nmstatectl/nmstatectl.go +++ b/pkg/nmstatectl/nmstatectl.go @@ -21,6 +21,7 @@ import ( "bytes" "fmt" "io" + "os" "os/exec" "strconv" "strings" @@ -141,3 +142,63 @@ func Statistic(desiredState nmstate.State) (*Stats, error) { } return NewStats(stats.Features), nil } + +func Policy(policy, currentState, capturedState []byte) (desiredState, generatedCapturedState []byte, err error) { + policyFile, err := generateFileWithContent("policy", policy) + if err != nil { + return nil, nil, err + } + defer func() { + os.Remove(policyFile) + }() + + args := []string{"policy"} + if len(currentState) > 0 { + var currentStateFile string + currentStateFile, err = generateFileWithContent("currentState", currentState) + if err != nil { + return nil, nil, err + } + defer func() { + os.Remove(currentStateFile) + }() + args = append(args, "--current", currentStateFile) + } + + args = append(args, "--json") + + capturedStateFile, err := generateFileWithContent("capturedState", capturedState) + if err != nil { + return nil, nil, err + } + defer func() { + os.Remove(capturedStateFile) + }() + args = append(args, "--output-captured", capturedStateFile) + if len(capturedState) > 0 { + args = append(args, "--captured", capturedStateFile) + } + + args = append(args, policyFile) + out, err := nmstatectl(args) + if err != nil { + return nil, nil, errors.Wrapf(err, "failed calling nmstatectl rollback") + } + capturedState, err = os.ReadFile(capturedStateFile) + if err != nil { + return nil, nil, errors.Wrapf(err, "failed failed reading captured state") + } + return []byte(out), capturedState, nil +} + +func generateFileWithContent(name string, content []byte) (string, error) { + file, err := os.CreateTemp("/tmp", name) + if err != nil { + return "", err + } + defer file.Close() + if _, err := file.Write(content); err != nil { + return "", err + } + return file.Name(), nil +} diff --git a/test/e2e/handler/nnce_conditions_test.go b/test/e2e/handler/nnce_conditions_test.go index 14e55bb3a..d14cbf6cc 100644 --- a/test/e2e/handler/nnce_conditions_test.go +++ b/test/e2e/handler/nnce_conditions_test.go @@ -18,7 +18,6 @@ limitations under the License. package handler import ( - "fmt" "sync" "time" @@ -30,14 +29,6 @@ import ( policyconditions "github.com/nmstate/kubernetes-nmstate/test/e2e/policy" ) -func invalidConfig(bridgeName string) nmstate.State { - return nmstate.NewState(fmt.Sprintf(`interfaces: - - name: %s - type: linux-bridge - state: invalid_state -`, bridgeName)) -} - var _ = Describe("EnactmentCondition", func() { Context("when applying valid config", func() { AfterEach(func() { @@ -76,7 +67,11 @@ var _ = Describe("EnactmentCondition", func() { Context("when applying invalid configuration", func() { BeforeEach(func() { - updateDesiredState(invalidConfig(bridge1)) + updateDesiredState(nmstate.NewState(`interfaces: + - name: bad1 + type: ethernet + state: up +`)) }) AfterEach(func() { diff --git a/vendor/github.com/nmstate/kubernetes-nmstate/api/v1/zz_generated.deepcopy.go b/vendor/github.com/nmstate/kubernetes-nmstate/api/v1/zz_generated.deepcopy.go index c7c3265d1..115337b2a 100644 --- a/vendor/github.com/nmstate/kubernetes-nmstate/api/v1/zz_generated.deepcopy.go +++ b/vendor/github.com/nmstate/kubernetes-nmstate/api/v1/zz_generated.deepcopy.go @@ -1,5 +1,4 @@ //go:build !ignore_autogenerated -// +build !ignore_autogenerated /* Copyright The Kubernetes NMState Authors. diff --git a/vendor/github.com/nmstate/kubernetes-nmstate/api/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/nmstate/kubernetes-nmstate/api/v1alpha1/zz_generated.deepcopy.go index 7d7d69280..6adb5b1b5 100644 --- a/vendor/github.com/nmstate/kubernetes-nmstate/api/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/github.com/nmstate/kubernetes-nmstate/api/v1alpha1/zz_generated.deepcopy.go @@ -1,5 +1,4 @@ //go:build !ignore_autogenerated -// +build !ignore_autogenerated /* Copyright The Kubernetes NMState Authors. diff --git a/vendor/github.com/nmstate/kubernetes-nmstate/api/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/nmstate/kubernetes-nmstate/api/v1beta1/zz_generated.deepcopy.go index 81e245319..edf9a8b3c 100644 --- a/vendor/github.com/nmstate/kubernetes-nmstate/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/github.com/nmstate/kubernetes-nmstate/api/v1beta1/zz_generated.deepcopy.go @@ -1,5 +1,4 @@ //go:build !ignore_autogenerated -// +build !ignore_autogenerated /* Copyright The Kubernetes NMState Authors. diff --git a/vendor/github.com/nmstate/nmpolicy/LICENSE b/vendor/github.com/nmstate/nmpolicy/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/nmstate/nmpolicy/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/equal.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/equal.go deleted file mode 100644 index a656b38cf..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/equal.go +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 ast - -func deepEqualStringPtr(lhs, rhs *string) bool { - if lhs == rhs { - return true - } - if rhs != nil && lhs != nil { - return *lhs == *rhs - } - return false -} - -func (t Terminal) DeepEqual(rhs Terminal) bool { - return deepEqualStringPtr(rhs.Identity, t.Identity) && - deepEqualStringPtr(rhs.Str, t.Str) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/types.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/types.go deleted file mode 100644 index 23d976085..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/types.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 ast - -import "fmt" - -type Meta struct { - Position int `json:"pos"` -} - -type TernaryOperator [3]Node -type VariadicOperator []Node -type Terminal struct { - Str *string `json:"string,omitempty"` - Identity *string `json:"identity,omitempty"` - Number *int `json:"number,omitempty"` - Boolean *bool `json:"boolean,omitempty"` -} - -type Node struct { - Meta - EqFilter *TernaryOperator `json:"eqfilter,omitempty"` - NeFilter *TernaryOperator `json:"nefilter,omitempty"` - Replace *TernaryOperator `json:"replace,omitempty"` - Path *VariadicOperator `json:"path,omitempty"` - Terminal -} - -func (n Node) String() string { - if n.EqFilter != nil { - return fmt.Sprintf("EqFilter(%s)", *n.EqFilter) - } - if n.NeFilter != nil { - return fmt.Sprintf("NeFilter(%s)", *n.NeFilter) - } - if n.Replace != nil { - return fmt.Sprintf("Replace(%s)", *n.Replace) - } - if n.Path != nil { - return fmt.Sprintf("Path=%s", *n.Path) - } - return n.Terminal.String() -} - -func (t Terminal) String() string { - if t.Str != nil { - return fmt.Sprintf("String=%s", *t.Str) - } - if t.Identity != nil { - return fmt.Sprintf("Identity=%s", *t.Identity) - } - if t.Number != nil { - return fmt.Sprintf("Number=%d", *t.Number) - } - if t.Boolean != nil { - return fmt.Sprintf("Boolean=%t", *t.Boolean) - } - return "" -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/values.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/values.go deleted file mode 100644 index 3bdf9535f..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/ast/values.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 ast - -func CurrentStateIdentity() Terminal { - literal := "currentState" - return Terminal{ - Identity: &literal, - } -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/capture/capture.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/capture/capture.go deleted file mode 100644 index 43c2bf51d..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/capture/capture.go +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 capture - -import ( - "fmt" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" - "github.com/nmstate/nmpolicy/nmpolicy/internal/lexer" - "github.com/nmstate/nmpolicy/nmpolicy/internal/types" -) - -type Capture struct { - lexer Lexer - parser Parser - resolver Resolver -} - -type Lexer interface { - Lex(expression string) ([]lexer.Token, error) -} - -type Parser interface { - Parse(string, []lexer.Token) (ast.Node, error) -} - -type Resolver interface { - Resolve(captureExpressions types.CaptureExpressions, captureASTPool types.CaptureASTPool, - state types.NMState, capturedStates types.CapturedStates) (types.CapturedStates, error) - ResolveCaptureEntryPath(expression string, captureEntryPathAST ast.Node, capturedStates types.CapturedStates) (interface{}, error) -} - -func New(leXer Lexer, parser Parser, resolver Resolver) Capture { - return Capture{ - lexer: leXer, - parser: parser, - resolver: resolver, - } -} - -func (c Capture) Resolve( - capturesExpr types.CaptureExpressions, - capturesCache types.CapturedStates, - state types.NMState) (types.CapturedStates, error) { - if len(capturesExpr) == 0 || len(state) == 0 && len(capturesCache) == 0 { - return nil, nil - } - - capturesState := filterCacheBasedOnExprCaptures(capturesCache, capturesExpr) - capturesExpr = filterOutExprBasedOnCachedCaptures(capturesExpr, capturesCache) - - astPool := types.CaptureASTPool{} - for capID, capExpr := range capturesExpr { - tokens, err := c.lexer.Lex(capExpr) - if err != nil { - return nil, fmt.Errorf("failed to resolve capture expression, err: %v", err) - } - - astRoot, err := c.parser.Parse(capExpr, tokens) - if err != nil { - return nil, fmt.Errorf("failed to resolve capture expression, err: %v", err) - } - - astPool[capID] = astRoot - } - - resolvedCapturedStates, err := c.resolver.Resolve(capturesExpr, astPool, state, capturesState) - if err != nil { - return nil, fmt.Errorf("failed to resolve capture expression, err: %v", err) - } - - return resolvedCapturedStates, nil -} - -func filterOutExprBasedOnCachedCaptures(capturesExpr types.CaptureExpressions, - capturesCache types.CapturedStates) types.CaptureExpressions { - for capID := range capturesCache { - delete(capturesExpr, capID) - } - return capturesExpr -} - -func filterCacheBasedOnExprCaptures(capsState types.CapturedStates, - capsExpr types.CaptureExpressions) types.CapturedStates { - caps := types.CapturedStates{} - - for capID := range capsExpr { - if capState, ok := capsState[capID]; ok { - caps[capID] = capState - } - } - return caps -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/capture/capture_entry.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/capture/capture_entry.go deleted file mode 100644 index ade26c8cf..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/capture/capture_entry.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 capture - -import ( - "fmt" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/lexer" - "github.com/nmstate/nmpolicy/nmpolicy/internal/parser" - "github.com/nmstate/nmpolicy/nmpolicy/internal/resolver" - "github.com/nmstate/nmpolicy/nmpolicy/internal/types" -) - -type CaptureEntry struct { - capturedStates types.CapturedStates - lexer Lexer - parser Parser - resolver Resolver -} - -func NewCaptureEntryWithLexerParserResolver(capturedStates types.CapturedStates, - l Lexer, p Parser, r Resolver) (CaptureEntry, error) { - return CaptureEntry{ - capturedStates: capturedStates, - lexer: l, - parser: p, - resolver: r, - }, nil -} - -func NewCaptureEntry(capturedStates types.CapturedStates) (CaptureEntry, error) { - return NewCaptureEntryWithLexerParserResolver(capturedStates, lexer.New(), parser.New(), resolver.New()) -} - -func (c CaptureEntry) ResolveCaptureEntryPath( - captureEntryPathExpression string) (interface{}, error) { - captureEntryPathTokens, err := c.lexer.Lex(captureEntryPathExpression) - if err != nil { - return nil, fmt.Errorf("failed to resolve capture entry path expression: %v", err) - } - - captureEntryPathAST, err := c.parser.Parse(captureEntryPathExpression, captureEntryPathTokens) - if err != nil { - return nil, fmt.Errorf("failed to resolve capture entry path expression: %v", err) - } - - resolvedCaptureEntryPath, err := c.resolver.ResolveCaptureEntryPath(captureEntryPathExpression, captureEntryPathAST, c.capturedStates) - if err != nil { - return nil, fmt.Errorf("failed to resolve capture entry path expression: %v", err) - } - - return resolvedCaptureEntryPath, nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expander/state_expander.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expander/state_expander.go deleted file mode 100644 index 66eca1701..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expander/state_expander.go +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 expander - -import ( - "fmt" - "regexp" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/types" -) - -type StateExpander struct { - capResolver CapturePathResolver -} - -type CapturePathResolver interface { - ResolveCaptureEntryPath(capturePath string) (interface{}, error) -} - -func New(capResolver CapturePathResolver) StateExpander { - return StateExpander{capResolver: capResolver} -} - -func (c StateExpander) Expand(desiredState types.NMState) (types.NMState, error) { - expandedState, err := c.expandState(map[string]interface{}(desiredState)) - if err != nil { - return nil, fmt.Errorf("failed expanding desired state: %v", err) - } - return types.NMState(expandedState.(map[string]interface{})), nil -} - -func (c StateExpander) expandState(state interface{}) (interface{}, error) { - switch stateValue := state.(type) { - case nil: - return state, nil - case string: - return c.expandString(stateValue) - case map[string]interface{}: - return c.expandMap(stateValue) - case []interface{}: - return c.exapndSlice(stateValue) - default: - return state, nil - } -} - -func (c StateExpander) exapndSlice(sliceState []interface{}) ([]interface{}, error) { - for i, value := range sliceState { - expandedValue, err := c.expandState(value) - if err != nil { - return nil, err - } - sliceState[i] = expandedValue - } - return sliceState, nil -} - -func (c StateExpander) expandMap(mapState map[string]interface{}) (map[string]interface{}, error) { - for key, value := range mapState { - expandedValue, err := c.expandState(value) - mapState[key] = expandedValue - if err != nil { - return nil, err - } - } - return mapState, nil -} - -func (c StateExpander) expandString(stringState string) (interface{}, error) { - re := regexp.MustCompile(`^{{ (.*) }}$`) - submatch := re.FindStringSubmatch(stringState) - - if len(submatch) == 0 { - return stringState, nil - } - - const captureSubmatchLength = 2 - if len(submatch) != captureSubmatchLength { - return nil, fmt.Errorf("the capture expression has wrong format %s", stringState) - } - - capturePath := submatch[1] - resolvedPath, err := c.capResolver.ResolveCaptureEntryPath(capturePath) - - if err != nil { - return nil, err - } - - return resolvedPath, nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expression/error.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expression/error.go deleted file mode 100644 index c63ccebc0..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expression/error.go +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2001 NMPolicy Authors. - * - * 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 expression - -import ( - "fmt" -) - -// WrapError construct a new error wrapping the error and decorating it -// with the expression and a pointer at the position specified. -func WrapError(err error, expression string, pos int) error { - return fmt.Errorf("%w\n%s", err, snippet(expression, pos)) -} - -// DecorateError construct a new error including the error and decorating it -// with the expression and a pointer at the position specified. -func DecorateError(err error, expression string, pos int) error { - return fmt.Errorf("%s\n%s", err, snippet(expression, pos)) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expression/snippet.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expression/snippet.go deleted file mode 100644 index 696650f24..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/expression/snippet.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2001 NMPolicy Authors. - * - * 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 expression - -import ( - "fmt" - "strings" -) - -// Snippet returns a string containing src and a pointer at pos. -// Example of str "123456" and pos "4": -// -// | 123456 -// | ...^ -func snippet(expression string, pos int) string { - if expression == "" { - return "" - } - - if pos >= len(expression) { - pos = len(expression) - 1 - } - - marker := strings.Builder{} - for i := 0; i < pos; i++ { - marker.WriteString(".") - } - marker.WriteString("^") - return fmt.Sprintf("| %s\n| %s", expression, marker.String()) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/lexer.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/lexer.go deleted file mode 100644 index 958d9d98e..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/lexer.go +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 lexer - -import ( - "fmt" - "strings" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/expression" - "github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/scanner" -) - -// Lexer struct is used to tokenize values returned by a reader. -type Lexer struct{} - -type lexer struct { - expression string - scn *scanner.Scanner -} - -// NewLexer construct a Lexer using reader as the input. -func New() Lexer { - return Lexer{} -} - -func newLexer(expr string) *lexer { - return &lexer{expression: expr, scn: scanner.New(strings.NewReader(expr))} -} - -// Lex scans the input for the next token. -// It returns a Token struct with position, type, and the literal value. -func (Lexer) Lex(expr string) ([]Token, error) { - return newLexer(expr).Lex() -} - -// Lex scans the input for the next token. -// It returns a Token struct with position, type, and the literal value. -func (l *lexer) Lex() ([]Token, error) { - // keep looping until we return a token - tokens := []Token{} - for { - token, err := l.lex() - if err != nil { - return nil, expression.WrapError(err, l.expression, l.scn.Position()) - } - if token == nil { - continue - } - tokens = append(tokens, *token) - if token.Type == EOF { - break - } - } - return tokens, nil -} - -func (l *lexer) lex() (*Token, error) { - for { - err := l.scn.Next() - if err != nil { - return nil, err - } - token, err := l.lexCurrentRune() - if err != nil { - return nil, err - } - if token == nil { - continue - } - return token, nil - } -} - -func (l *lexer) lexCurrentRune() (*Token, error) { - if l.isEOF() { - return &Token{l.scn.Position(), EOF, ""}, nil - } else if l.isSpace() { - return nil, nil - } else if l.isDigit() { - return l.lexNumber() - } else if l.isString() { - return l.lexString() - } else if l.isLetter() { - return l.lexIdentityOrBoolean() - } else if l.isDot() { - return &Token{l.scn.Position(), DOT, string(l.scn.Rune())}, nil - } else if l.isColon() { - return l.lexEqualAs(REPLACE) - } else if l.isEqual() { - return l.lexEqualAs(EQFILTER) - } else if l.isExclamationMark() { - return l.lexEqualAs(NEFILTER) - } else if l.isPlus() { - return &Token{l.scn.Position(), MERGE, string(l.scn.Rune())}, nil - } else if l.isPipe() { - return &Token{l.scn.Position(), PIPE, string(l.scn.Rune())}, nil - } - return nil, fmt.Errorf("illegal rune %s", string(l.scn.Rune())) -} - -func (l *lexer) lexNumber() (*Token, error) { - token := &Token{l.scn.Position(), NUMBER, string(l.scn.Rune())} - for { - if err := l.scn.Next(); err != nil { - return nil, err - } - - if l.isEOF() || l.isSpace() { - // If it's EOF or space we have finish here - return token, nil - } else if l.isDot() || l.isPipe() { - if err := l.scn.Prev(); err != nil { - return nil, fmt.Errorf("failed lexing number: %w", err) - } - return token, nil - } else if l.isDigit() { - token.Literal += string(l.scn.Rune()) - } else { - // nmpolicy supports only simple numbers with just digist - return nil, fmt.Errorf("invalid number format (%s is not a digit)", string(l.scn.Rune())) - } - } -} - -func (l *lexer) lexString() (*Token, error) { - token := &Token{l.scn.Position(), STRING, ""} - // Strings should close with the same rune they have started - expectedTerminator := l.scn.Rune() - for { - if err := l.scn.Next(); err != nil { - return nil, err - } - - if l.isEOF() { - return nil, fmt.Errorf("invalid string format (missing %s terminator)", string(expectedTerminator)) - } else if l.scn.Rune() == expectedTerminator { - return token, nil - } else { - token.Literal += string(l.scn.Rune()) - } - } -} - -func (l *lexer) lexIdentityOrBoolean() (*Token, error) { - token := &Token{l.scn.Position(), IDENTITY, string(l.scn.Rune())} - - for i := 1; ; i++ { - if err := l.scn.Next(); err != nil { - return nil, err - } - - if l.isDelimiter() { - if token.IsTrue() || token.IsFalse() { - token.Type = BOOLEAN - } - if l.isEOF() || l.isSpace() { - return token, nil - } - - if err := l.scn.Prev(); err != nil { - return nil, fmt.Errorf("failed lexing identity: %w", err) - } - return token, nil - } else if l.isDigit() || l.isLetter() || l.scn.Rune() == '-' { - token.Literal += string(l.scn.Rune()) - } else { - return nil, fmt.Errorf("invalid identity format (%s is not a digit, letter or -)", string(l.scn.Rune())) - } - } -} - -func (l *lexer) lexEqualAs(tokenType TokenType) (*Token, error) { - var literal strings.Builder - literal.WriteRune(l.scn.Rune()) - if err := l.scn.Next(); err != nil { - return nil, err - } - if l.isEqual() { - literal.WriteRune(l.scn.Rune()) - return &Token{l.scn.Position() - 1, tokenType, literal.String()}, nil - } else { - return nil, fmt.Errorf("invalid %s operation format (%s is not equal char)", tokenType, string(l.scn.Rune())) - } -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/rune.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/rune.go deleted file mode 100644 index 453d353be..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/rune.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 lexer - -import ( - "strings" - "unicode" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/scanner" -) - -func (l *lexer) isDigit() bool { - return unicode.IsDigit(l.scn.Rune()) -} - -func (l *lexer) isSpace() bool { - return unicode.IsSpace(l.scn.Rune()) -} - -func (l *lexer) isEOF() bool { - return l.scn.Rune() == scanner.EOF -} - -func (l *lexer) isString() bool { - return strings.ContainsRune(`"'`, l.scn.Rune()) -} - -func (l *lexer) isLetter() bool { - return unicode.IsLetter(l.scn.Rune()) -} - -func (l *lexer) isDot() bool { - return l.scn.Rune() == '.' -} - -func (l *lexer) isEqual() bool { - return l.scn.Rune() == '=' -} - -func (l *lexer) isColon() bool { - return l.scn.Rune() == ':' -} - -func (l *lexer) isPlus() bool { - return l.scn.Rune() == '+' -} - -func (l *lexer) isPipe() bool { - return l.scn.Rune() == '|' -} - -func (l *lexer) isExclamationMark() bool { - return l.scn.Rune() == '!' -} - -func (l *lexer) isDelimiter() bool { - return l.isEOF() || l.isSpace() || l.isDot() || l.isEqual() || l.isColon() || l.isPlus() || l.isPipe() || l.isExclamationMark() -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/scanner/scanner.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/scanner/scanner.go deleted file mode 100644 index 2719a9a30..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/scanner/scanner.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 scanner - -import ( - "io" -) - -const ( - EOF rune = -1 -) - -type Scanner struct { - reader io.RuneScanner - currentRune rune - prevRune rune - pos int -} - -func New(reader io.RuneScanner) *Scanner { - return &Scanner{ - reader: reader, - } -} - -func (s *Scanner) Next() error { - rn, err := s.next() - if err != nil { - return err - } - s.prevRune = s.currentRune - s.currentRune = rn - if rn != EOF { - s.pos++ - } - return nil -} - -func (s *Scanner) Rune() rune { - return s.currentRune -} - -func (s *Scanner) Prev() error { - if err := s.reader.UnreadRune(); err != nil { - return err - } - s.currentRune = s.prevRune - s.pos-- - return nil -} - -func (s *Scanner) Position() int { - return s.pos - 1 -} - -func (s *Scanner) next() (rune, error) { - rn, _, err := s.reader.ReadRune() - if err != nil { - if err == io.EOF { - return EOF, nil - } - return EOF, err - } - return rn, nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/token.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/token.go deleted file mode 100644 index 4266e6e81..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/token.go +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 lexer - -type TokenType int - -const ( - EOF TokenType = iota - IDENTITY - NUMBER - STRING - BOOLEAN - - DOT // . - - operatorsBegin - PIPE // | - REPLACE // := - EQFILTER // == - NEFILTER // != - MERGE // + - operatorsEnd -) - -var tokens = []string{ - EOF: "EOF", - IDENTITY: "IDENTITY", - NUMBER: "NUMBER", - STRING: "STRING", - BOOLEAN: "BOOLEAN", - - DOT: "DOT", - PIPE: "PIPE", - - REPLACE: "REPLACE", - EQFILTER: "EQFILTER", - NEFILTER: "NEFILTER", - MERGE: "MERGE", -} - -func (t TokenType) String() string { - return tokens[t] -} - -func (t TokenType) IsOperator() bool { - return t > operatorsBegin && t < operatorsEnd -} - -type Token struct { - Position int - Type TokenType - Literal string -} - -func (t *Token) IsTrue() bool { - return t.Literal == "true" -} - -func (t *Token) IsFalse() bool { - return t.Literal == "false" -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/operations.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/operations.go deleted file mode 100644 index be885677a..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/operations.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 internal - -import ( - "fmt" - "time" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/capture" - "github.com/nmstate/nmpolicy/nmpolicy/internal/expander" - "github.com/nmstate/nmpolicy/nmpolicy/internal/lexer" - "github.com/nmstate/nmpolicy/nmpolicy/internal/parser" - "github.com/nmstate/nmpolicy/nmpolicy/internal/resolver" - "github.com/nmstate/nmpolicy/nmpolicy/internal/types" -) - -func GenerateState(policySpec types.PolicySpec, currentState types.NMState, cachedState types.CachedState) (types.GeneratedState, error) { - var ( - capturedStates types.CapturedStates - desiredState types.NMState - ) - - if policySpec.DesiredState != nil { - capResolver := capture.New(lexer.New(), parser.New(), resolver.New()) - var err error - capturedStates, err = capResolver.Resolve(policySpec.Capture, cachedState.CapturedStates, currentState) - if err != nil { - return types.GeneratedState{}, fmt.Errorf("failed to generate state, err: %v", err) - } - - captureEntryPathResolver, err := capture.NewCaptureEntry(capturedStates) - if err != nil { - return types.GeneratedState{}, fmt.Errorf("failed to generate state, err: %v", err) - } - - stateExpander := expander.New(captureEntryPathResolver) - desiredState, err = stateExpander.Expand(policySpec.DesiredState) - if err != nil { - return types.GeneratedState{}, fmt.Errorf("failed to generate state, err: %v", err) - } - } - - stampCapturedStates(capturedStates) - return types.GeneratedState{ - Cache: types.CachedState{CapturedStates: capturedStates}, - DesiredState: desiredState, - }, nil -} - -func stampCapturedStates(capturedStates types.CapturedStates) { - now := time.Now().UTC() - for captureID, capturedState := range capturedStates { - if capturedState.MetaInfo.TimeStamp.IsZero() { - capturedState.MetaInfo.TimeStamp = now - capturedState.MetaInfo.Version = "0" - capturedStates[captureID] = capturedState - } - } -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/parser/errors.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/parser/errors.go deleted file mode 100644 index df51cdb02..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/parser/errors.go +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 parser - -import ( - "strings" -) - -type parserError struct { - prefix string - inner error - msg string -} - -func (p parserError) Unwrap() error { - return p.inner -} - -func (p parserError) Error() string { - errorMsg := strings.Builder{} - errorMsg.WriteString(p.prefix) - errorMsg.WriteString(": ") - if p.inner != nil { - errorMsg.WriteString(p.inner.Error()) - } else { - errorMsg.WriteString(p.msg) - } - return errorMsg.String() -} - -const invalidPathErrorPrefix = "invalid path" - -func wrapWithInvalidPathError(err error) *parserError { - return &parserError{ - prefix: invalidPathErrorPrefix, - inner: err, - } -} - -func invalidPathError(msg string) *parserError { - return &parserError{ - prefix: invalidPathErrorPrefix, - msg: msg, - } -} - -func wrapWithInvalidEqualityFilterError(err error) *parserError { - return &parserError{ - prefix: "invalid equality filter", - inner: err, - } -} - -func wrapWithInvalidInequalityFilterError(err error) *parserError { - return &parserError{ - prefix: "invalid inequality filter", - inner: err, - } -} - -func wrapWithInvalidReplaceError(err error) *parserError { - return &parserError{ - prefix: "invalid replace", - inner: err, - } -} - -func invalidExpressionError(msg string) *parserError { - return &parserError{ - prefix: "invalid expression", - msg: msg, - } -} - -func invalidPipeError(msg string) *parserError { - return &parserError{ - prefix: "invalid pipe", - msg: msg, - } -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/parser/parser.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/parser/parser.go deleted file mode 100644 index 51a4cb760..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/parser/parser.go +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 parser - -import ( - "fmt" - "strconv" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" - "github.com/nmstate/nmpolicy/nmpolicy/internal/expression" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/lexer" -) - -type Parser struct{} - -type parser struct { - expression string - tokens []lexer.Token - currentTokenIdx int - lastNode *ast.Node - pipedInNode *ast.Node -} - -func New() Parser { - return Parser{} -} - -func newParser(expr string, tokens []lexer.Token) *parser { - return &parser{expression: expr, tokens: tokens} -} - -func (Parser) Parse(expr string, tokens []lexer.Token) (ast.Node, error) { - return newParser(expr, tokens).Parse() -} - -func (p *parser) Parse() (ast.Node, error) { - node, err := p.parse() - if err != nil { - return ast.Node{}, expression.WrapError(err, p.expression, p.currentToken().Position) - } - return node, nil -} - -func (p *parser) parse() (ast.Node, error) { - for { - if p.currentToken() == nil { - return ast.Node{}, nil - } else if p.currentToken().Type == lexer.EOF { - break - } else if p.currentToken().Type == lexer.STRING { - if err := p.parseString(); err != nil { - return ast.Node{}, err - } - } else if p.currentToken().Type == lexer.BOOLEAN { - if err := p.parseBoolean(); err != nil { - return ast.Node{}, err - } - } else if p.currentToken().Type == lexer.IDENTITY { - if err := p.parsePath(); err != nil { - return ast.Node{}, err - } - } else if p.currentToken().Type == lexer.EQFILTER { - if err := p.parseEqFilter(); err != nil { - return ast.Node{}, err - } - } else if p.currentToken().Type == lexer.NEFILTER { - if err := p.parseNeFilter(); err != nil { - return ast.Node{}, err - } - } else if p.currentToken().Type == lexer.REPLACE { - if err := p.parseReplace(); err != nil { - return ast.Node{}, err - } - } else if p.currentToken().Type == lexer.PIPE { - if err := p.parsePipe(); err != nil { - return ast.Node{}, err - } - } else { - return ast.Node{}, invalidExpressionError(fmt.Sprintf("unexpected token `%+v`", p.currentToken().Literal)) - } - p.nextToken() - } - if p.pipedInNode != nil { - return ast.Node{}, invalidPipeError("missing pipe out expression") - } - return p.lastEmitedNode(), nil -} - -func (p *parser) lastEmitedNode() ast.Node { - if p.lastNode == nil { - return ast.Node{} - } - return *p.lastNode -} - -func (p *parser) nextToken() { - if len(p.tokens) == 0 { - return - } - if p.currentTokenIdx >= len(p.tokens)-1 { - p.currentTokenIdx = len(p.tokens) - 1 - } else { - p.currentTokenIdx++ - } -} - -func (p *parser) prevToken() { - if len(p.tokens) == 0 { - return - } - if p.currentTokenIdx > 0 { - p.currentTokenIdx-- - } - if p.currentTokenIdx >= len(p.tokens)-1 { - p.currentTokenIdx = len(p.tokens) - 1 - } -} - -func (p *parser) currentToken() *lexer.Token { - if len(p.tokens) == 0 || p.currentTokenIdx >= len(p.tokens) { - return nil - } - return &p.tokens[p.currentTokenIdx] -} - -func (p *parser) parseIdentity() error { - p.lastNode = &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - Terminal: ast.Terminal{Identity: &p.currentToken().Literal}, - } - return nil -} - -func (p *parser) parseString() error { - p.lastNode = &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - Terminal: ast.Terminal{Str: &p.currentToken().Literal}, - } - return nil -} - -func (p *parser) parseNumber() error { - number, err := strconv.Atoi(p.currentToken().Literal) - if err != nil { - return err - } - p.lastNode = &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - Terminal: ast.Terminal{Number: &number}, - } - return nil -} - -func (p *parser) parseBoolean() error { - if p.currentToken().IsTrue() || p.currentToken().IsFalse() { - boolean, err := strconv.ParseBool(p.currentToken().Literal) - if err != nil { - return err - } - p.lastNode = &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - Terminal: ast.Terminal{Boolean: &boolean}, - } - return nil - } else { - return fmt.Errorf("only true/false is accepted as boolean literal") - } -} - -func (p *parser) parsePath() error { - if err := p.parseIdentity(); err != nil { - return err - } - operator := &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - Path: &ast.VariadicOperator{*p.lastNode}, - } - for { - p.nextToken() - if p.currentToken().Type == lexer.DOT { - p.nextToken() - if p.currentToken().Type == lexer.IDENTITY { - if err := p.parseIdentity(); err != nil { - return err - } - } else if p.currentToken().Type == lexer.NUMBER { - if err := p.parseNumber(); err != nil { - return wrapWithInvalidPathError(err) - } - } else { - return invalidPathError("missing identity or number after dot") - } - path := append(*operator.Path, *p.lastNode) - operator.Path = &path - } else if p.currentToken().Type != lexer.EOF && !p.currentToken().Type.IsOperator() { - return invalidPathError("missing dot") - } else { - // Token has not being consumed let's go back. - p.prevToken() - break - } - } - p.lastNode = operator - return nil -} - -func (p *parser) parseEqFilter() error { - operator := &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - EqFilter: &ast.TernaryOperator{}, - } - if err := p.fillInTernaryOperator(operator.EqFilter); err != nil { - return wrapWithInvalidEqualityFilterError(err) - } - p.lastNode = operator - return nil -} - -func (p *parser) parseNeFilter() error { - operator := &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - NeFilter: &ast.TernaryOperator{}, - } - if err := p.fillInTernaryOperator(operator.NeFilter); err != nil { - return wrapWithInvalidInequalityFilterError(err) - } - p.lastNode = operator - return nil -} - -func (p *parser) parseReplace() error { - operator := &ast.Node{ - Meta: ast.Meta{Position: p.currentToken().Position}, - Replace: &ast.TernaryOperator{}, - } - if err := p.fillInTernaryOperator(operator.Replace); err != nil { - return wrapWithInvalidReplaceError(err) - } - p.lastNode = operator - return nil -} - -func (p *parser) fillInTernaryOperator(operator *ast.TernaryOperator) error { - if p.lastNode == nil { - return fmt.Errorf("missing left hand argument") - } - if p.lastNode.Path == nil { - return fmt.Errorf("left hand argument is not a path") - } - - p.fillInPipedInOrCurrentState(&operator[0]) - - operator[1] = *p.lastNode - - p.nextToken() - if p.currentToken().Type == lexer.STRING { - if err := p.parseString(); err != nil { - return err - } - operator[2] = *p.lastNode - } else if p.currentToken().Type == lexer.BOOLEAN { - if err := p.parseBoolean(); err != nil { - return err - } - operator[2] = *p.lastNode - } else if p.currentToken().Type == lexer.IDENTITY { - err := p.parsePath() - if err != nil { - return err - } - operator[2] = *p.lastNode - } else if p.currentToken().Type == lexer.EOF { - return fmt.Errorf("missing right hand argument") - } else { - return fmt.Errorf("right hand argument is not a string or identity") - } - return nil -} - -func (p *parser) fillInPipedInOrCurrentState(node *ast.Node) { - if p.pipedInNode != nil { - *node = *p.pipedInNode - p.pipedInNode = nil - } else { - node.Terminal = ast.CurrentStateIdentity() - } -} - -func (p *parser) parsePipe() error { - if p.lastNode == nil { - return invalidPipeError("missing pipe in expression") - } - if p.lastNode.Path == nil { - return invalidPipeError("only paths can be piped in") - } - p.pipedInNode = p.lastNode - return nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/errors.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/errors.go deleted file mode 100644 index 7a5a2952f..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/errors.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 resolver - -import ( - "fmt" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" -) - -type PathError struct { - inner error - errorNode *ast.Node -} - -func (r PathError) Unwrap() error { - return r.inner -} - -func (r PathError) Error() string { - return r.inner.Error() -} - -func pathError(currentStepNode *ast.Node, format string, a ...interface{}) PathError { - return wrapWithPathError(currentStepNode, fmt.Errorf(format, a...)) -} - -func wrapWithPathError(currentStepNode *ast.Node, err error) PathError { - return PathError{inner: fmt.Errorf("invalid path: %v", err), errorNode: currentStepNode} -} - -func wrapWithResolveError(err error) error { - return fmt.Errorf("resolve error: %w", err) -} - -func wrapWithEqFilterError(err error) error { - return fmt.Errorf("eqfilter error: %w", err) -} - -func wrapWithNeFilterError(err error) error { - return fmt.Errorf("nefilter error: %w", err) -} - -func replaceError(format string, a ...interface{}) error { - return wrapWithReplaceError(fmt.Errorf(format, a...)) -} - -func wrapWithReplaceError(err error) error { - return fmt.Errorf("replace error: %w", err) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/filter.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/filter.go deleted file mode 100644 index caeb46004..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/filter.go +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 resolver - -import ( - "fmt" - "reflect" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" -) - -func filter( - inputState map[string]interface{}, - pathSteps ast.VariadicOperator, - operator func(interface{}, interface{}) bool, - expectedValue interface{}) (map[string]interface{}, error) { - filtered, err := visitState(newPath(pathSteps), inputState, &filterVisitor{ - operator: operator, - expectedValue: expectedValue, - }) - - if err != nil { - return nil, fmt.Errorf("failed applying operation on the path: %w", err) - } - - if filtered == nil { - return nil, nil - } - - filteredMap, ok := filtered.(map[string]interface{}) - if !ok { - return nil, fmt.Errorf("failed converting filtering result to a map") - } - return filteredMap, nil -} -func eqfilter( - inputState map[string]interface{}, - pathSteps ast.VariadicOperator, - expectedValue interface{}) (map[string]interface{}, error) { - return filter(inputState, pathSteps, func(lhs, rhs interface{}) bool { return lhs == rhs }, expectedValue) -} -func nefilter( - inputState map[string]interface{}, - pathSteps ast.VariadicOperator, - expectedValue interface{}) (map[string]interface{}, error) { - return filter(inputState, pathSteps, func(lhs, rhs interface{}) bool { return lhs != rhs }, expectedValue) -} - -type filterVisitor struct { - mergeVisitResult bool - operator func(interface{}, interface{}) bool - expectedValue interface{} -} - -func (e filterVisitor) visitLastMap(p path, mapToFilter map[string]interface{}) (interface{}, error) { - obtainedValue, ok := mapToFilter[*p.currentStep.Identity] - if !ok { - return nil, nil - } - - // Filter by the path since there is no value to compare - if e.expectedValue == nil { - return map[string]interface{}{*p.currentStep.Identity: obtainedValue}, nil - } - - if reflect.TypeOf(obtainedValue) != reflect.TypeOf(e.expectedValue) { - return nil, pathError(p.currentStep, `type missmatch: the value in the path doesn't match the value to filter. `+ - `"%T" != "%T" -> %+v != %+v`, obtainedValue, e.expectedValue, obtainedValue, e.expectedValue) - } - if e.operator(obtainedValue, e.expectedValue) { - return mapToFilter, nil - } - return nil, nil -} - -func (e filterVisitor) visitLastSlice(p path, sliceToVisit []interface{}) (interface{}, error) { - if p.currentStep.Identity != nil { - return e.visitSlice(p, sliceToVisit) - } - return nil, pathError(p.currentStep, "filtering lists index with equal not implemented") -} - -func (e filterVisitor) visitMap(p path, mapToVisit map[string]interface{}) (interface{}, error) { - if p.currentStep.Number != nil { - return nil, pathError(p.currentStep, "failed filtering map: path with index not supported") - } - interfaceToVisit, ok := mapToVisit[*p.currentStep.Identity] - if !ok { - return nil, nil - } - visitResult, err := visitState(p.nextStep(), interfaceToVisit, &e) - if err != nil { - return nil, err - } - if visitResult == nil { - return nil, nil - } - filteredMap := map[string]interface{}{} - if e.mergeVisitResult { - for k, v := range mapToVisit { - filteredMap[k] = v - } - } - filteredMap[*p.currentStep.Identity] = visitResult - return filteredMap, nil -} - -func (e filterVisitor) visitSlice(p path, sliceToVisit []interface{}) (interface{}, error) { - if p.currentStep.Number != nil { - return nil, pathError(p.currentStep, "failed filtering slice: path with index not supported") - } - - filteredSlice := []interface{}{} - hasVisitResult := false - for _, interfaceToVisit := range sliceToVisit { - // Filter only the first slice by forcing "mergeVisitResult" to true - // for the the following ones. - visitResult, err := visitState(p, interfaceToVisit, &filterVisitor{ - mergeVisitResult: true, - operator: e.operator, - expectedValue: e.expectedValue}) - if err != nil { - return nil, err - } - if visitResult != nil { - hasVisitResult = true - filteredSlice = append(filteredSlice, visitResult) - } else if e.mergeVisitResult { - filteredSlice = append(filteredSlice, interfaceToVisit) - } - } - - if !hasVisitResult { - return nil, nil - } - return filteredSlice, nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/path.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/path.go deleted file mode 100644 index 84ede6877..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/path.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 resolver - -import ( - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" -) - -type path struct { - steps []ast.Node - currentStepIndex int - currentStep *ast.Node -} - -func newPath(steps []ast.Node) path { - return path{ - steps: steps, - currentStepIndex: 0, - currentStep: &steps[0], - } -} - -func (p path) nextStep() path { - if p.hasMoreSteps() { - p.currentStepIndex++ - } - p.currentStep = &p.steps[p.currentStepIndex] - return p -} - -func (p path) hasMoreSteps() bool { - return p.currentStepIndex+1 < len(p.steps) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/replace.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/replace.go deleted file mode 100644 index 59e48bd4b..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/replace.go +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 resolver - -import ( - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" -) - -func replace(inputState map[string]interface{}, pathSteps ast.VariadicOperator, replaceValue interface{}) (map[string]interface{}, error) { - replaced, err := visitState(newPath(pathSteps), inputState, &replaceOpVisitor{replaceValue}) - - if err != nil { - return nil, replaceError("failed applying operation on the path: %w", err) - } - - replacedMap, ok := replaced.(map[string]interface{}) - if !ok { - return nil, replaceError("failed converting result to a map") - } - return replacedMap, nil -} - -type replaceOpVisitor struct { - replaceValue interface{} -} - -func (r replaceOpVisitor) visitLastMap(p path, inputMap map[string]interface{}) (interface{}, error) { - modifiedMap := map[string]interface{}{} - for k, v := range inputMap { - modifiedMap[k] = v - } - - modifiedMap[*p.currentStep.Identity] = r.replaceValue - return modifiedMap, nil -} - -func (r replaceOpVisitor) visitLastSlice(p path, sliceToVisit []interface{}) (interface{}, error) { - if p.currentStep.Identity != nil { - return r.visitSlice(p, sliceToVisit) - } - return nil, pathError(p.currentStep, "replacing lists value at index not implemented") -} - -func (r replaceOpVisitor) visitMap(p path, mapToVisit map[string]interface{}) (interface{}, error) { - if p.currentStep.Number != nil { - return nil, pathError(p.currentStep, "failed replacing map: path with index not supported") - } - interfaceToVisit, ok := mapToVisit[*p.currentStep.Identity] - if !ok { - interfaceToVisit = map[string]interface{}{} - } - - visitResult, err := visitState(p.nextStep(), interfaceToVisit, &r) - if err != nil { - return nil, err - } - - replacedMap := map[string]interface{}{} - for k, v := range mapToVisit { - replacedMap[k] = v - } - replacedMap[*p.currentStep.Identity] = visitResult - return replacedMap, nil -} - -func (r replaceOpVisitor) visitSlice(p path, sliceToVisit []interface{}) (interface{}, error) { - if p.currentStep.Number != nil { - return nil, pathError(p.currentStep, "failed replacing slice: path with index not supported") - } - - replacedSlice := make([]interface{}, len(sliceToVisit)) - for i, interfaceToVisit := range sliceToVisit { - visitResult, err := visitState(p, interfaceToVisit, &r) - if err != nil { - return nil, err - } - replacedSlice[i] = visitResult - } - return replacedSlice, nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/resolver.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/resolver.go deleted file mode 100644 index 1a8dd0194..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/resolver.go +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 resolver - -import ( - "errors" - "fmt" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" - "github.com/nmstate/nmpolicy/nmpolicy/internal/expression" - "github.com/nmstate/nmpolicy/nmpolicy/internal/types" -) - -type captureEntryNameAndSteps struct { - captureEntryName string - steps ast.VariadicOperator -} - -type Resolver struct{} - -type resolver struct { - currentState types.NMState - capturedStates types.CapturedStates - captureExpressions types.CaptureExpressions - captureASTPool types.CaptureASTPool - currentNode *ast.Node - currentExpression *string -} - -func New() Resolver { - return Resolver{} -} - -func newResolver() *resolver { - return &resolver{ - currentState: types.NMState{}, - capturedStates: types.CapturedStates{}, - captureASTPool: types.CaptureASTPool{}, - } -} - -func (Resolver) Resolve(captureExpressions types.CaptureExpressions, - captureASTPool types.CaptureASTPool, - currentState types.NMState, - capturedStates types.CapturedStates) (types.CapturedStates, error) { - r := newResolver() - r.currentState = currentState - r.captureASTPool = captureASTPool - r.captureExpressions = captureExpressions - if capturedStates != nil { - r.capturedStates = capturedStates - } - capturedStates, err := r.resolve() - return capturedStates, r.wrapErrorWithCurrentExpression(err) -} - -func (Resolver) ResolveCaptureEntryPath(expr string, captureEntryPathAST ast.Node, - capturedStates types.CapturedStates) (interface{}, error) { - r := newResolver() - r.currentExpression = &expr - r.capturedStates = capturedStates - r.currentNode = &captureEntryPathAST - resolvedCaptureEntryPath, err := r.resolveCaptureEntryPath() - return resolvedCaptureEntryPath, r.wrapErrorWithCurrentExpression(err) -} - -func (r *resolver) resolve() (types.CapturedStates, error) { - for captureEntryName := range r.captureASTPool { - if _, err := r.resolveCaptureEntryName(captureEntryName); err != nil { - return nil, wrapWithResolveError(err) - } - } - return r.capturedStates, nil -} - -func (r *resolver) resolveCaptureEntryName(captureEntryName string) (types.NMState, error) { - expr, ok := r.captureExpressions[captureEntryName] - if ok { - r.currentExpression = &expr - } - capturedStateEntry, ok := r.capturedStates[captureEntryName] - if ok { - return capturedStateEntry.State, nil - } - captureASTEntry, ok := r.captureASTPool[captureEntryName] - if !ok { - return nil, fmt.Errorf("capture entry '%s' not found", captureEntryName) - } - r.currentNode = &captureASTEntry - var err error - capturedStateEntry = types.CapturedState{} - capturedStateEntry.State, err = r.resolveCaptureASTEntry() - if err != nil { - return nil, err - } - r.capturedStates[captureEntryName] = capturedStateEntry - return capturedStateEntry.State, nil -} - -func (r *resolver) resolveCaptureASTEntry() (types.NMState, error) { - if r.currentNode.EqFilter != nil { - return r.resolveEqFilter() - } else if r.currentNode.NeFilter != nil { - return r.resolveNeFilter() - } else if r.currentNode.Replace != nil { - return r.resolveReplace() - } else if r.currentNode.Path != nil { - return r.resolvePathFilter() - } - return nil, fmt.Errorf("root node has unsupported operation : %s", *r.currentNode) -} - -func (r *resolver) resolveEqFilter() (types.NMState, error) { - operator := r.currentNode.EqFilter - filteredState, err := r.resolveTernaryOperator(operator, eqfilter) - if err != nil { - return nil, wrapWithEqFilterError(err) - } - return filteredState, nil -} - -func (r *resolver) resolveNeFilter() (types.NMState, error) { - operator := r.currentNode.NeFilter - filteredState, err := r.resolveTernaryOperator(operator, nefilter) - if err != nil { - return nil, wrapWithNeFilterError(err) - } - return filteredState, nil -} - -func (r *resolver) resolveReplace() (types.NMState, error) { - operator := r.currentNode.Replace - replacedState, err := r.resolveTernaryOperator(operator, replace) - if err != nil { - return nil, wrapWithResolveError(err) - } - return replacedState, nil -} - -func (r *resolver) resolvePathFilter() (types.NMState, error) { - return eqfilter(r.currentState, *r.currentNode.Path, nil) -} - -func (r *resolver) resolveTernaryOperator(operator *ast.TernaryOperator, - resolverFunc func(map[string]interface{}, ast.VariadicOperator, interface{}) (map[string]interface{}, error)) (types.NMState, error) { - operatorNode := r.currentNode - r.currentNode = &(*operator)[0] - inputSource, err := r.resolveInputSource() - if err != nil { - return nil, err - } - - r.currentNode = &(*operator)[1] - path, err := r.resolvePath() - if err != nil { - return nil, err - } - r.currentNode = &(*operator)[2] - value, err := r.resolveTerminalOrCapturePath() - if err != nil { - return nil, err - } - - r.currentNode = operatorNode - resolvedState, err := resolverFunc(inputSource, path.steps, value) - if err != nil { - return nil, err - } - return resolvedState, nil -} - -func (r *resolver) resolveInputSource() (types.NMState, error) { - if ast.CurrentStateIdentity().DeepEqual(r.currentNode.Terminal) { - return r.currentState, nil - } else if r.currentNode.Path != nil { - resolvedPath, err := r.resolvePath() - if err != nil { - return nil, err - } - if resolvedPath.captureEntryName == "" { - return nil, fmt.Errorf("invalid path input source (%s), only capture reference is supported", r.currentNode) - } - capturedState, err := r.resolveCaptureEntryName(resolvedPath.captureEntryName) - if err != nil { - return nil, err - } - return capturedState, nil - } - - return nil, fmt.Errorf("invalid input source (%s), only current state or capture reference is supported", *r.currentNode) -} - -func (r *resolver) resolveTerminalOrCapturePath() (interface{}, error) { - if r.currentNode.Str != nil { - return *r.currentNode.Str, nil - } else if r.currentNode.Path != nil { - return r.resolveCaptureEntryPath() - } else if r.currentNode.Boolean != nil { - return *r.currentNode.Boolean, nil - } else { - return nil, fmt.Errorf("not supported value. Only string or capture entry path are supported") - } -} - -func (r *resolver) resolveCaptureEntryPath() (interface{}, error) { - resolvedPath, err := r.resolvePath() - if err != nil { - return nil, err - } - if resolvedPath.captureEntryName == "" { - return nil, fmt.Errorf("not supported filtered value path. Only paths with a capture entry reference are supported") - } - capturedStateEntry, err := r.resolveCaptureEntryName(resolvedPath.captureEntryName) - if err != nil { - return nil, err - } - return walk(capturedStateEntry, resolvedPath.steps) -} - -func (r *resolver) resolvePath() (*captureEntryNameAndSteps, error) { - if r.currentNode.Path == nil { - return nil, fmt.Errorf("invalid path type %T", *r.currentNode) - } else if len(*r.currentNode.Path) == 0 { - return nil, fmt.Errorf("empty path length") - } else if (*r.currentNode.Path)[0].Identity == nil { - return nil, fmt.Errorf("path first step has to be an identity") - } - resolvedPath := captureEntryNameAndSteps{ - steps: *r.currentNode.Path, - } - if *resolvedPath.steps[0].Identity == "capture" { - const captureRefSize = 2 - if len(resolvedPath.steps) < captureRefSize || resolvedPath.steps[1].Identity == nil { - return nil, fmt.Errorf("path capture ref is missing capture entry name") - } - resolvedPath.captureEntryName = *resolvedPath.steps[1].Identity - if len(resolvedPath.steps) > captureRefSize { - resolvedPath.steps = resolvedPath.steps[2:len(resolvedPath.steps)] - } - } - return &resolvedPath, nil -} - -func (r resolver) wrapErrorWithCurrentExpression(err error) error { - if err == nil { - return nil - } - - var pathError PathError - errorNode := r.currentNode - if errors.As(err, &pathError) { - errorNode = pathError.errorNode - } - - if errorNode == nil || r.currentExpression == nil { - return err - } - return expression.WrapError(err, *r.currentExpression, errorNode.Meta.Position) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/visitor.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/visitor.go deleted file mode 100644 index 97dc207d8..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/visitor.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 resolver - -type stateVisitor interface { - visitLastMap(path, map[string]interface{}) (interface{}, error) - visitLastSlice(path, []interface{}) (interface{}, error) - visitMap(path, map[string]interface{}) (interface{}, error) - visitSlice(path, []interface{}) (interface{}, error) -} - -func visitState(p path, inputState interface{}, v stateVisitor) (interface{}, error) { - originalMap, isMap := inputState.(map[string]interface{}) - if isMap { - if p.hasMoreSteps() { - if p.currentStep.Identity == nil { - return nil, pathError(p.currentStep, "unexpected non identity step for map state '%+v'", originalMap) - } - return v.visitMap(p, originalMap) - } - return v.visitLastMap(p, originalMap) - } - - originalSlice, isSlice := inputState.([]interface{}) - if isSlice { - if p.hasMoreSteps() { - return v.visitSlice(p, originalSlice) - } - return v.visitLastSlice(p, originalSlice) - } - return nil, pathError(p.currentStep, "invalid type %T for identity step '%v'", inputState, *p.currentStep) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/walk.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/walk.go deleted file mode 100644 index 7235e711c..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/resolver/walk.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2022 NMPolicy Authors. - * - * 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 resolver - -import ( - "fmt" - - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" -) - -func walk(inputState map[string]interface{}, pathSteps ast.VariadicOperator) (interface{}, error) { - visitResult, err := visitState(newPath(pathSteps), inputState, &walkOpVisitor{}) - if err != nil { - return nil, fmt.Errorf("failed walking path: %w", err) - } - - return visitResult, nil -} - -type walkOpVisitor struct{} - -func (walkOpVisitor) visitLastMap(p path, mapToAccess map[string]interface{}) (interface{}, error) { - return accessMapWithCurrentStep(p, mapToAccess) -} - -func (walkOpVisitor) visitLastSlice(p path, sliceToAccess []interface{}) (interface{}, error) { - return accessSliceWithCurrentStep(p, sliceToAccess) -} - -func (w walkOpVisitor) visitSlice(p path, sliceToVisit []interface{}) (interface{}, error) { - interfaceToVisit, err := accessSliceWithCurrentStep(p, sliceToVisit) - if err != nil { - return nil, err - } - return visitState(p.nextStep(), interfaceToVisit, &w) -} - -func (w walkOpVisitor) visitMap(p path, mapToVisit map[string]interface{}) (interface{}, error) { - interfaceToVisit, err := accessMapWithCurrentStep(p, mapToVisit) - if err != nil { - return nil, err - } - return visitState(p.nextStep(), interfaceToVisit, &w) -} - -func accessMapWithCurrentStep(p path, mapToAccess map[string]interface{}) (interface{}, error) { - if p.currentStep.Identity == nil { - return nil, pathError(p.currentStep, "unexpected non identity step for smap state '%+v'", mapToAccess) - } - v, ok := mapToAccess[*p.currentStep.Identity] - if !ok { - return nil, pathError(p.currentStep, "step not found at map state '%+v'", mapToAccess) - } - return v, nil -} - -func accessSliceWithCurrentStep(p path, sliceToAccess []interface{}) (interface{}, error) { - if p.currentStep.Number == nil { - return nil, pathError(p.currentStep, "unexpected non numeric step for slice state '%+v'", sliceToAccess) - } - if len(sliceToAccess) <= *p.currentStep.Number { - return nil, pathError(p.currentStep, "step not found at slice state '%+v'", sliceToAccess) - } - return sliceToAccess[*p.currentStep.Number], nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/types/types.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/types/types.go deleted file mode 100644 index 3c7331237..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/internal/types/types.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 types - -import ( - "github.com/nmstate/nmpolicy/nmpolicy/internal/ast" - nmpolicytypes "github.com/nmstate/nmpolicy/nmpolicy/types" -) - -type NMState map[string]interface{} -type CaptureExpressions map[string]string -type CapturedStates map[string]CapturedState -type CaptureASTPool map[string]ast.Node - -type PolicySpec struct { - Capture CaptureExpressions - DesiredState NMState -} - -type CachedState struct { - CapturedStates CapturedStates -} - -type GeneratedState struct { - Cache CachedState - DesiredState NMState -} - -type CapturedState struct { - State NMState - MetaInfo nmpolicytypes.MetaInfo -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/operations.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/operations.go deleted file mode 100644 index 3ba63da53..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/operations.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 nmpolicy - -import ( - "fmt" - - yaml "sigs.k8s.io/yaml" - - "github.com/nmstate/nmpolicy/nmpolicy/internal" - internaltypes "github.com/nmstate/nmpolicy/nmpolicy/internal/types" - "github.com/nmstate/nmpolicy/nmpolicy/types" -) - -// GenerateState creates a NMPolicy state based on the given input data: -// - NMPolicy spec. -// - NMState state, representing a given current state. -// - Cache state which includes (already resolved) named captures. -// -// GenerateState returns a generated state which includes: -// - Desired State: The NMState state which has been built by the policy. -// - Cache: Named NMState states which have been resolved by the policy. -// Can be saved for use as cache data (passed as input). -// - Meta Info: Extended information about the generated state (e.g. the policy version). -// -// On failure, an error is returned. -func GenerateState(policySpec types.PolicySpec, - currentState []byte, cachedState types.CachedState) (generatedState types.GeneratedState, err error) { - internalPolicySpec, err := toInternalPolicySpec(policySpec) - if err != nil { - return generatedState, fmt.Errorf("failed converting to internal policy spec: %v", err) - } - internalCurrentState, err := toInternalNMState(currentState) - if err != nil { - return generatedState, fmt.Errorf("failed converting to internal current state: %v", err) - } - internalCachedState, err := toInternalCachedState(cachedState) - if err != nil { - return generatedState, fmt.Errorf("failed converting to internal cached state: %v", err) - } - - internalGeneratedState, err := internal.GenerateState(internalPolicySpec, internalCurrentState, internalCachedState) - if err != nil { - return generatedState, err - } - - generatedState, err = toGeneratedState(internalGeneratedState) - if err != nil { - return generatedState, err - } - return generatedState, nil -} - -func toInternalPolicySpec(policySpec types.PolicySpec) (internaltypes.PolicySpec, error) { - internalDesiredState, err := toInternalNMState(policySpec.DesiredState) - if err != nil { - return internaltypes.PolicySpec{}, err - } - return internaltypes.PolicySpec{ - DesiredState: internalDesiredState, - Capture: internaltypes.CaptureExpressions(policySpec.Capture), - }, nil -} - -func toInternalNMState(nmState []byte) (internaltypes.NMState, error) { - internalNMState := internaltypes.NMState{} - if err := yaml.Unmarshal(nmState, &internalNMState); err != nil { - return nil, fmt.Errorf("failed converting to internal NMState: %w", err) - } - return internalNMState, nil -} - -func toNMState(internalNMState internaltypes.NMState) ([]byte, error) { - if len(internalNMState) == 0 { - return nil, nil - } - nmState, err := yaml.Marshal(internalNMState) - if err != nil { - return nil, fmt.Errorf("failed converting from internal NMState: %w", err) - } - return nmState, nil -} - -func toInternalCapturedState(capturedState types.CaptureState) (internaltypes.CapturedState, error) { - internalState, err := toInternalNMState(capturedState.State) - if err != nil { - return internaltypes.CapturedState{}, err - } - return internaltypes.CapturedState{ - State: internalState, - MetaInfo: capturedState.MetaInfo, - }, nil -} - -func toCapturedState(internalCapturedState internaltypes.CapturedState) (types.CaptureState, error) { - state, err := toNMState(internalCapturedState.State) - if err != nil { - return types.CaptureState{}, err - } - return types.CaptureState{ - State: state, - MetaInfo: internalCapturedState.MetaInfo, - }, nil -} - -func toInternalCachedState(cachedState types.CachedState) (internaltypes.CachedState, error) { - internalCachedState := internaltypes.CachedState{ - CapturedStates: internaltypes.CapturedStates{}, - } - for captureEntryName, capturedState := range cachedState.Capture { - internalCapturedState, err := toInternalCapturedState(capturedState) - if err != nil { - return internaltypes.CachedState{}, err - } - internalCachedState.CapturedStates[captureEntryName] = internalCapturedState - } - return internalCachedState, nil -} - -func toCachedState(internalCachedState internaltypes.CachedState) (types.CachedState, error) { - if len(internalCachedState.CapturedStates) == 0 { - return types.CachedState{}, nil - } - cachedState := types.CachedState{ - Capture: map[string]types.CaptureState{}, - } - for captureEntryName, internalCapturedState := range internalCachedState.CapturedStates { - capturedState, err := toCapturedState(internalCapturedState) - if err != nil { - return types.CachedState{}, err - } - cachedState.Capture[captureEntryName] = capturedState - } - return cachedState, nil -} - -func toGeneratedState(internalGeneratedState internaltypes.GeneratedState) (types.GeneratedState, error) { - desiredState, err := toNMState(internalGeneratedState.DesiredState) - if err != nil { - return types.GeneratedState{}, err - } - cachedState, err := toCachedState(internalGeneratedState.Cache) - if err != nil { - return types.GeneratedState{}, err - } - return types.GeneratedState{ - DesiredState: desiredState, - Cache: cachedState, - }, nil -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/types/json.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/types/json.go deleted file mode 100644 index 3e8592a98..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/types/json.go +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 types - -import "sigs.k8s.io/yaml" - -func (s *NMState) UnmarshalJSON(b []byte) error { - output, err := yaml.JSONToYAML(b) - if err != nil { - return err - } - *s = output - return nil -} - -func (s NMState) MarshalJSON() ([]byte, error) { - return yaml.YAMLToJSON([]byte(s)) -} diff --git a/vendor/github.com/nmstate/nmpolicy/nmpolicy/types/types.go b/vendor/github.com/nmstate/nmpolicy/nmpolicy/types/types.go deleted file mode 100644 index 4700d8b3f..000000000 --- a/vendor/github.com/nmstate/nmpolicy/nmpolicy/types/types.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2021 NMPolicy Authors. - * - * 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 types - -import ( - "time" -) - -type NMState []byte - -type PolicySpec struct { - Capture map[string]string - DesiredState NMState -} - -type CachedState struct { - Capture map[string]CaptureState -} - -type GeneratedState struct { - Cache CachedState - DesiredState NMState -} - -type CaptureState struct { - State NMState - MetaInfo MetaInfo -} - -type MetaInfo struct { - Version string - TimeStamp time.Time -} - -func NoCache() CachedState { return CachedState{} } diff --git a/vendor/modules.txt b/vendor/modules.txt index 5a4995054..d322d3c8a 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -186,20 +186,6 @@ github.com/nmstate/kubernetes-nmstate/api/shared github.com/nmstate/kubernetes-nmstate/api/v1 github.com/nmstate/kubernetes-nmstate/api/v1alpha1 github.com/nmstate/kubernetes-nmstate/api/v1beta1 -# github.com/nmstate/nmpolicy v0.6.0 -## explicit; go 1.17 -github.com/nmstate/nmpolicy/nmpolicy -github.com/nmstate/nmpolicy/nmpolicy/internal -github.com/nmstate/nmpolicy/nmpolicy/internal/ast -github.com/nmstate/nmpolicy/nmpolicy/internal/capture -github.com/nmstate/nmpolicy/nmpolicy/internal/expander -github.com/nmstate/nmpolicy/nmpolicy/internal/expression -github.com/nmstate/nmpolicy/nmpolicy/internal/lexer -github.com/nmstate/nmpolicy/nmpolicy/internal/lexer/scanner -github.com/nmstate/nmpolicy/nmpolicy/internal/parser -github.com/nmstate/nmpolicy/nmpolicy/internal/resolver -github.com/nmstate/nmpolicy/nmpolicy/internal/types -github.com/nmstate/nmpolicy/nmpolicy/types # github.com/onsi/ginkgo/v2 v2.11.0 ## explicit; go 1.18 github.com/onsi/ginkgo/v2