diff --git a/plugins/cmd/kubectl-plan/README.md b/plugins/cmd/kubectl-plan/README.md new file mode 100644 index 000000000..8d48541dd --- /dev/null +++ b/plugins/cmd/kubectl-plan/README.md @@ -0,0 +1,7 @@ +# kubectl-plan + +kubectl-plan is an experimental kubectl plugin that dry-runs +apply operations and shows the changes in an easy to read format. + +It is still under development and highly experimental, it should +not be treated as stable. \ No newline at end of file diff --git a/plugins/cmd/kubectl-plan/main.go b/plugins/cmd/kubectl-plan/main.go new file mode 100644 index 000000000..3deef3ccd --- /dev/null +++ b/plugins/cmd/kubectl-plan/main.go @@ -0,0 +1,35 @@ +// Copyright 2023 The kpt 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 main + +import ( + "context" + "fmt" + "os" + + "github.com/GoogleContainerTools/kpt/plugins/pkg/cmd/plan" +) + +func main() { + if err := Run(context.Background()); err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } +} + +func Run(ctx context.Context) error { + root := plan.NewCommand() + return root.ExecuteContext(ctx) +} diff --git a/plugins/go.mod b/plugins/go.mod new file mode 100644 index 000000000..7f5a41e22 --- /dev/null +++ b/plugins/go.mod @@ -0,0 +1,60 @@ +module github.com/GoogleContainerTools/kpt/plugins + +go 1.21.3 + +require ( + github.com/google/go-cmp v0.5.9 + github.com/spf13/cobra v1.8.0 + k8s.io/apimachinery v0.28.4 + k8s.io/client-go v0.28.4 + k8s.io/klog/v2 v2.100.1 + sigs.k8s.io/controller-runtime v0.13.0 + sigs.k8s.io/kubebuilder-declarative-pattern v0.13.0 + sigs.k8s.io/kubebuilder-declarative-pattern/mockkubeapiserver v0.0.0-20231030230424-f6a5c89244f2 + sigs.k8s.io/kustomize/kyaml v0.15.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/emicklei/go-restful/v3 v3.10.1 // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/go-errors/errors v1.4.2 // indirect + github.com/go-logr/logr v1.2.4 // indirect + github.com/go-openapi/jsonpointer v0.19.6 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/swag v0.22.3 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/gofuzz v1.2.0 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/imdario/mergo v0.3.13 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/stretchr/testify v1.8.4 // indirect + go.uber.org/atomic v1.10.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/net v0.17.0 // indirect + golang.org/x/oauth2 v0.8.0 // indirect + golang.org/x/sys v0.13.0 // indirect + golang.org/x/term v0.13.0 // indirect + golang.org/x/text v0.13.0 // indirect + golang.org/x/time v0.3.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/api v0.28.4 // indirect + k8s.io/kube-openapi v0.0.0-20230717233707-2695361300d9 // indirect + k8s.io/utils v0.0.0-20230505201702-9f6742963106 // indirect + sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect + sigs.k8s.io/yaml v1.3.0 // indirect +) diff --git a/plugins/go.sum b/plugins/go.sum new file mode 100644 index 000000000..12fc4af96 --- /dev/null +++ b/plugins/go.sum @@ -0,0 +1,190 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emicklei/go-restful/v3 v3.10.1 h1:rc42Y5YTp7Am7CS630D7JmhRjq4UlEUuEKfrDac4bSQ= +github.com/emicklei/go-restful/v3 v3.10.1/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +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 h1:a9vnzlIBPQBBkeaR9IuMUfmVOrQlkoC4YfPoFkX3T7A= +github.com/go-logr/zapr v1.2.3/go.mod h1:eIauM6P8qSvTw5o2ez6UEAfGjQKrxQTl5EoK+Qa2oG4= +github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= +github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= +github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +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/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +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-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= +github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +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= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.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 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= +github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +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.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/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +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 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +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.9.4 h1:xR7vG4IXt5RWx6FfIjyAtsoMAtnc3C/rFXBBd2AjZwE= +github.com/onsi/ginkgo/v2 v2.9.4/go.mod h1:gCQYp2Q+kSoIj7ykSVb9nskRSsR6PUj4AiLywzIhbKM= +github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE= +github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg= +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/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= +go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= +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/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +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.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8= +golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE= +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/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-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +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 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= +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.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +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 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +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= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.8.0 h1:vSDcovVPld282ceKgDimkRSC8kpaH1dgyc9UMzlt84Y= +golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +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= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/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= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +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.28.4 h1:8ZBrLjwosLl/NYgv1P7EQLqoO8MGQApnbgH8tu3BMzY= +k8s.io/api v0.28.4/go.mod h1:axWTGrY88s/5YE+JSt4uUi6NMM+gur1en2REMR7IRj0= +k8s.io/apimachinery v0.28.4 h1:zOSJe1mc+GxuMnFzD4Z/U1wst50X28ZNsn5bhgIIao8= +k8s.io/apimachinery v0.28.4/go.mod h1:wI37ncBvfAoswfq626yPTe6Bz1c22L7uaJ8dho83mgg= +k8s.io/client-go v0.28.4 h1:Np5ocjlZcTrkyRJ3+T3PkXDpe4UpatQxj85+xjaD2wY= +k8s.io/client-go v0.28.4/go.mod h1:0VDZFpgoZfelyP5Wqu0/r/TRYcLYuJ2U1KEeoaPa1N4= +k8s.io/klog/v2 v2.100.1 h1:7WCHKK6K8fNhTqfBhISHQ97KrnJNFZMcQvKp7gP/tmg= +k8s.io/klog/v2 v2.100.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= +k8s.io/kube-openapi v0.0.0-20230717233707-2695361300d9 h1:LyMgNKD2P8Wn1iAwQU5OhxCKlKJy0sHc+PcDwFB24dQ= +k8s.io/kube-openapi v0.0.0-20230717233707-2695361300d9/go.mod h1:wZK2AVp1uHCp4VamDVgBP2COHZjqD1T68Rf0CM3YjSM= +k8s.io/utils v0.0.0-20230505201702-9f6742963106 h1:EObNQ3TW2D+WptiYXlApGNLVy0zm/JIBVY9i+M4wpAU= +k8s.io/utils v0.0.0-20230505201702-9f6742963106/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/controller-runtime v0.13.0 h1:iqa5RNciy7ADWnIc8QxCbOX5FEKVR3uxVxKHRMc2WIQ= +sigs.k8s.io/controller-runtime v0.13.0/go.mod h1:Zbz+el8Yg31jubvAEyglRZGdLAjplZl+PgtYNI6WNTI= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/kubebuilder-declarative-pattern v0.13.0 h1:bXWUEkEyuzpPKv2UbPBGjnmBiVxwYRsfkH/wD01x2nw= +sigs.k8s.io/kubebuilder-declarative-pattern v0.13.0/go.mod h1:afaOqnacEy12TnauavyAu3BuEaeWMDLKbG55Tvr8noI= +sigs.k8s.io/kubebuilder-declarative-pattern/mockkubeapiserver v0.0.0-20231030230424-f6a5c89244f2 h1:KUl4G2tnSd46YbS0Wa4wbRAoC1cVkpCwxV2ED57YscY= +sigs.k8s.io/kubebuilder-declarative-pattern/mockkubeapiserver v0.0.0-20231030230424-f6a5c89244f2/go.mod h1:usFQkfq1WKoOAOnR6jKO0x48i6RpLAIhh3ytuJAzC/c= +sigs.k8s.io/kustomize/kyaml v0.15.0 h1:ynlLMAxDhrY9otSg5GYE2TcIz31XkGZ2Pkj7SdolD84= +sigs.k8s.io/kustomize/kyaml v0.15.0/go.mod h1:+uMkBahdU1KNOj78Uta4rrXH+iH7wvg+nW7+GULvREA= +sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= +sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= +sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= +sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/plugins/pkg/cmd/plan/cluster_target.go b/plugins/pkg/cmd/plan/cluster_target.go new file mode 100644 index 000000000..9d8fab065 --- /dev/null +++ b/plugins/pkg/cmd/plan/cluster_target.go @@ -0,0 +1,121 @@ +// Copyright 2023 The kpt 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 plan + +import ( + "context" + "encoding/json" + "fmt" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/restmapper" +) + +// ClusterTarget supports actions against a running kubernetes cluster. +type ClusterTarget struct { + client dynamic.Interface + restMapper resourceFinder +} + +func NewClusterTarget(restConfig *rest.Config) (*ClusterTarget, error) { + client, err := dynamic.NewForConfig(restConfig) + if err != nil { + return nil, fmt.Errorf("creating kubernetes client: %w", err) + } + + restMapper, err := restmapper.NewControllerRESTMapper(restConfig) + if err != nil { + return nil, fmt.Errorf("building REST mapper: %w", err) + } + + return &ClusterTarget{ + client: client, + restMapper: restMapper, + }, nil +} + +type resourceFinder interface { + RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) +} + +// ResourceForGVK gets the GVR / Scope for the specified object. +func (c *ClusterTarget) ResourceForGVK(ctx context.Context, gvk schema.GroupVersionKind) (*clusterResourceTarget, error) { + mapping, err := c.restMapper.RESTMapping(gvk.GroupKind(), gvk.Version) + if err != nil { + return nil, fmt.Errorf("cannot get RESTMapping for %v: %w", gvk, err) + } + return &clusterResourceTarget{info: mapping, client: c.client}, nil +} + +// Apply is a wrapper around applying changes to a live cluster. +func (c *clusterResourceTarget) Apply(ctx context.Context, obj *unstructured.Unstructured, options metav1.PatchOptions) (*unstructured.Unstructured, error) { + target, err := c.buildResource(ctx, obj) + if err != nil { + return nil, err + } + + j, err := json.Marshal(obj) + if err != nil { + return nil, fmt.Errorf("error marshalling object to JSON: %w", err) + } + + // Apply with server-side apply (specified with ApplyPatchType) + patched, err := target.Patch(ctx, obj.GetName(), types.ApplyPatchType, j, options) + if err != nil { + return nil, fmt.Errorf("server-side-apply failed: %w", err) + } + + return patched, nil +} + +// buildResource creates the dynamic ResourceInterface for the object +func (c *clusterResourceTarget) buildResource(ctx context.Context, obj *unstructured.Unstructured) (dynamic.ResourceInterface, error) { + if c.info.Scope == meta.RESTScopeRoot { + return c.client.Resource(c.info.Resource), nil + } else { + namespace := obj.GetNamespace() + if namespace == "" { + return nil, fmt.Errorf("namespace was not set, but is required for namespace-scoped objects") + } + return c.client.Resource(c.info.Resource).Namespace(namespace), nil + } +} + +// Get reads the current version of an object. +func (c *clusterResourceTarget) Get(ctx context.Context, obj *unstructured.Unstructured, options metav1.GetOptions) (*unstructured.Unstructured, error) { + target, err := c.buildResource(ctx, obj) + if err != nil { + return nil, err + } + + existing, err := target.Get(ctx, obj.GetName(), options) + if err != nil { + return nil, fmt.Errorf("get failed: %w", err) + } + + return existing, nil +} + +type clusterResourceTarget struct { + info *meta.RESTMapping + + client dynamic.Interface +} diff --git a/plugins/pkg/cmd/plan/golden_test.go b/plugins/pkg/cmd/plan/golden_test.go new file mode 100644 index 000000000..8c6a4a5bd --- /dev/null +++ b/plugins/pkg/cmd/plan/golden_test.go @@ -0,0 +1,115 @@ +// Copyright 2023 The kpt 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 plan + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" + + "github.com/google/go-cmp/cmp" + "k8s.io/client-go/rest" + "k8s.io/klog/v2" + "sigs.k8s.io/kubebuilder-declarative-pattern/mockkubeapiserver" + "sigs.k8s.io/yaml" +) + +func TestPlanner(t *testing.T) { + k8s, err := mockkubeapiserver.NewMockKubeAPIServer(":0") + if err != nil { + t.Fatalf("error building mock kube-apiserver: %v", err) + } + defer func() { + if err := k8s.Stop(); err != nil { + t.Fatalf("error closing mock kube-apiserver: %v", err) + } + }() + addr, err := k8s.StartServing() + if err != nil { + t.Errorf("error starting mock kube-apiserver: %v", err) + } + klog.Infof("mock kubeapiserver will listen on %v", addr) + + restConfig := &rest.Config{ + Host: addr.String(), + } + + dir := "testdata" + files, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("failed to read directory %q: %v", dir, err) + } + for _, file := range files { + p := filepath.Join(dir, file.Name()) + if !file.IsDir() { + t.Errorf("found non-directory %q", p) + continue + } + + t.Run(file.Name(), func(t *testing.T) { + p := filepath.Join(dir, file.Name()) + + ctx := context.Background() + + objects, err := loadObjectsFromFilesystem(filepath.Join(p, "apply.yaml")) + if err != nil { + t.Fatalf("error loading objects: %v", err) + } + + target, err := NewClusterTarget(restConfig) + if err != nil { + t.Fatalf("error building target: %v", err) + } + + planner := &Planner{} + + plan, err := planner.BuildPlan(ctx, objects, target) + if err != nil { + t.Fatalf("error from BuildPlan: %v", err) + } + + actual, err := yaml.Marshal(plan) + if err != nil { + t.Fatalf("yaml.Marshal failed: %v", err) + } + CompareGoldenFile(t, filepath.Join(p, "plan.yaml"), actual) + }) + } +} + +func CompareGoldenFile(t *testing.T, p string, got []byte) { + if os.Getenv("WRITE_GOLDEN_OUTPUT") != "" { + // Short-circuit when the output is correct + b, err := os.ReadFile(p) + if err == nil && bytes.Equal(b, got) { + return + } + + if err := os.WriteFile(p, got, 0644); err != nil { + t.Fatalf("failed to write golden output %s: %v", p, err) + } + t.Errorf("wrote output to %s", p) + } else { + want, err := os.ReadFile(p) + if err != nil { + t.Fatalf("failed to read file %q: %v", p, err) + } + if diff := cmp.Diff(string(want), string(got)); diff != "" { + t.Errorf("unexpected diff in %s: %s", p, diff) + } + } +} diff --git a/plugins/pkg/cmd/plan/loader.go b/plugins/pkg/cmd/plan/loader.go new file mode 100644 index 000000000..61b5c1652 --- /dev/null +++ b/plugins/pkg/cmd/plan/loader.go @@ -0,0 +1,101 @@ +// Copyright 2023 The kpt 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 plan + +import ( + "bufio" + "bytes" + "fmt" + "io" + "os" + "path/filepath" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/serializer/yaml" +) + +// loadObjectsFromFilesystem parses yaml objects from the provided directory or file path. +func loadObjectsFromFilesystem(p string) ([]*unstructured.Unstructured, error) { + var objects []*unstructured.Unstructured + stat, err := os.Stat(p) + if err != nil { + return nil, fmt.Errorf("could not get filesystem info for %q: %w", p, err) + } + + if stat.IsDir() { + files, err := os.ReadDir(p) + if err != nil { + return nil, fmt.Errorf("could not read directory %q: %w", p, err) + } + for _, f := range files { + childP := filepath.Join(p, f.Name()) + childObjects, err := loadObjectsFromFilesystem(childP) + if err != nil { + return nil, err + } + objects = append(objects, childObjects...) + } + return objects, nil + } + + f, err := os.Open(p) + if err != nil { + return nil, fmt.Errorf("error opening %q: %w", p, err) + } + defer f.Close() + objs, err := parseObjects(f) + if err != nil { + return nil, fmt.Errorf("error reading objects: %w", err) + } + return objs, nil +} + +// parseObjects parses yaml objects from the provided reader. +func parseObjects(r io.Reader) ([]*unstructured.Unstructured, error) { + codec := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme) + + var objs []*unstructured.Unstructured + + scanner := bufio.NewScanner(r) + scanner.Split(scanYAML) + + for scanner.Scan() { + b := scanner.Bytes() + obj, _, err := codec.Decode(b, nil, &unstructured.Unstructured{}) + if err != nil { + return nil, err + } + objs = append(objs, obj.(*unstructured.Unstructured)) + } + + return objs, nil +} + +// scanYAML is a split function for a Scanner that returns each yaml object. +func scanYAML(data []byte, atEOF bool) (advance int, token []byte, err error) { + if atEOF && len(data) == 0 { + return 0, nil, nil + } + if i := bytes.Index(data, []byte("\n---\n")); i >= 0 { + // We have a full object. + return i + 1, data[0:i], nil + } + // If we're at EOF, we have a final, non-terminated object. Return it. + if atEOF { + return len(data), data, nil + } + // Request more data. + return 0, nil, nil +} diff --git a/plugins/pkg/cmd/plan/model.go b/plugins/pkg/cmd/plan/model.go new file mode 100644 index 000000000..f9cf63b0c --- /dev/null +++ b/plugins/pkg/cmd/plan/model.go @@ -0,0 +1,46 @@ +// Copyright 2023 The kpt 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 plan + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) + +// Plan stores the expected changes when applying changes to a cluster. +// For consistency, we represent it as a KRM object, but we don't expect it to be applied to a cluster. +type Plan struct { + metav1.TypeMeta + + Spec PlanSpec `json:"spec,omitempty"` +} + +// PlanSpec is the Spec for a Plan object. +type PlanSpec struct { + Actions []Action `json:"actions,omitempty"` +} + +// ActionType is an enum type for the type of change (no-change/create/update etc). +type ActionType string + +// Action represents an individual object change. +type Action struct { + Type ActionType `json:"action,omitempty"` + APIVersion string `json:"apiVersion,omitempty"` + Kind string `json:"kind,omitempty"` + Name string `json:"name,omitempty"` + Namespace string `json:"namespace,omitempty"` + Object *unstructured.Unstructured `json:"object,omitempty"` +} diff --git a/plugins/pkg/cmd/plan/plan.go b/plugins/pkg/cmd/plan/plan.go new file mode 100644 index 000000000..f13f667d8 --- /dev/null +++ b/plugins/pkg/cmd/plan/plan.go @@ -0,0 +1,121 @@ +// Copyright 2023 The kpt 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 plan + +import ( + "context" + "fmt" + "io" + + "github.com/spf13/cobra" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client/config" +) + +// NewCommand builds a cobra command for the plan operation. +func NewCommand() *cobra.Command { + opt := &PlanOptions{} + + cmd := &cobra.Command{ + Use: "plan [DIR]...", + // Short: + // Long: + // Example: + PreRunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + + objects, err := readObjects(ctx, cmd, args) + if err != nil { + return err + } + opt.Objects = objects + + opt.Out = cmd.OutOrStdout() + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + restConfig, err := buildRESTConfig() + if err != nil { + return err + } + opt.RESTConfig = restConfig + + return RunPlan(cmd.Context(), opt) + }, + } + + return cmd +} + +// buildRESTConfig gets the kube config (rest.Config) for the current kubernetes cluster. +func buildRESTConfig() (*rest.Config, error) { + restConfig, err := config.GetConfig() + if err != nil { + return nil, fmt.Errorf("getting kubeconfig: %w", err) + } + return restConfig, nil +} + +// readObjects reads objects from the arguments supplied on the command line +func readObjects(ctx context.Context, cmd *cobra.Command, args []string) ([]*unstructured.Unstructured, error) { + if len(args) == 0 { + return nil, fmt.Errorf("must pass file or - (for stdin) with objects to apply") + } + if len(args) != 1 { + return nil, fmt.Errorf("expected exactly 1 arg, got %d", len(args)) + } + + if args[0] == "-" { + objs, err := parseObjects(cmd.InOrStdin()) + if err != nil { + return nil, fmt.Errorf("error reading objects: %w", err) + } + return objs, nil + } else { + return loadObjectsFromFilesystem(args[0]) + } +} + +// PlanOptions holds options for a plan operation. +type PlanOptions struct { + Out io.Writer + Objects []*unstructured.Unstructured + + RESTConfig *rest.Config +} + +// RunPlan executes a plan operation. +func RunPlan(ctx context.Context, opt *PlanOptions) error { + target, err := buildTarget(ctx, opt.RESTConfig) + if err != nil { + return err + } + + p := &Planner{} + + plan, err := p.BuildPlan(ctx, opt.Objects, target) + if err != nil { + return err + } + + printPlan(ctx, plan, opt.Out) + + return nil +} + +func buildTarget(ctx context.Context, restConfig *rest.Config) (*ClusterTarget, error) { + return NewClusterTarget(restConfig) +} diff --git a/plugins/pkg/cmd/plan/planner.go b/plugins/pkg/cmd/plan/planner.go new file mode 100644 index 000000000..3a9120b57 --- /dev/null +++ b/plugins/pkg/cmd/plan/planner.go @@ -0,0 +1,122 @@ +// Copyright 2023 The kpt 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 plan + +import ( + "context" + "errors" + "fmt" + "reflect" + + "github.com/google/go-cmp/cmp" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/klog/v2" +) + +// Planner holds the core planning logic and state. +type Planner struct { +} + +// BuildPlan is the entry point for building a plan. +func (r *Planner) BuildPlan(ctx context.Context, objects []*unstructured.Unstructured, target *ClusterTarget) (*Plan, error) { + plan := &Plan{} + + plan.APIVersion = "plan.kpt.dev/v1alpha1" + plan.Kind = "Plan" + + // TODO: prefetch & invalidate REST Mappings here, so we know they are valid later? + + force := true + applyOptions := metav1.PatchOptions{ + FieldManager: "kpt/plan", + Force: &force, + DryRun: []string{"All"}, + } + + for _, object := range objects { + gvk := object.GroupVersionKind() + + var action Action + action.Namespace = object.GetNamespace() + action.Name = object.GetName() + action.Kind = gvk.Kind + action.APIVersion = object.GetAPIVersion() + action.Object = object + + id := gvk.Kind + ":" + action.Namespace + "/" + action.Name + + resource, err := target.ResourceForGVK(ctx, gvk) + if err != nil { + // The Kind doesn't even exist; the object can't exist already + // TODO: We should invalide mappings above, in case our cache is out of date + action.Type = "Create" + plan.Spec.Actions = append(plan.Spec.Actions, action) + continue + } + + beforeApply, err := resource.Get(ctx, object, metav1.GetOptions{}) + if err != nil { + if apierrors.IsNotFound(unwrap(err)) { + action.Type = "Create" + plan.Spec.Actions = append(plan.Spec.Actions, action) + continue + } + return nil, fmt.Errorf("failed to read object %s: %w", id, err) + } + + klog.V(5).Infof("applying %s...", id) + afterApply, err := resource.Apply(ctx, object, applyOptions) + if err == nil { + klog.V(4).Infof("applied OK %s", id) + + // Ignore changes in managed fields, since they are not relevant to the user + beforeApply.SetManagedFields(nil) + afterApply.SetManagedFields(nil) + + if reflect.DeepEqual(beforeApply, afterApply) { + action.Type = "Unchanged" + plan.Spec.Actions = append(plan.Spec.Actions, action) + } else { + diff := cmp.Diff(beforeApply, afterApply) + if diff != "" { + klog.Infof("diff is %v", diff) + } + action.Type = "ApplyChanges" + plan.Spec.Actions = append(plan.Spec.Actions, action) + } + } + + if err != nil { + if action.Type == "" { + klog.Errorf("unknown error applying (%s) %#v", id, err) + action.Type = "Error" + } + plan.Spec.Actions = append(plan.Spec.Actions, action) + continue + } + } + + return plan, nil +} + +func unwrap(err error) error { + var apiStatusError *apierrors.StatusError + if errors.As(err, &apiStatusError) { + return apiStatusError + } + return err +} diff --git a/plugins/pkg/cmd/plan/printer.go b/plugins/pkg/cmd/plan/printer.go new file mode 100644 index 000000000..a3088af9b --- /dev/null +++ b/plugins/pkg/cmd/plan/printer.go @@ -0,0 +1,39 @@ +// Copyright 2023 The kpt 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 plan + +import ( + "context" + "fmt" + "io" + "text/tabwriter" +) + +// printPlan writes a plan to out for human consumption (usually will be stdout) +func printPlan(ctx context.Context, plan *Plan, out io.Writer) error { + minwidth := 0 + tabwidth := 4 + padding := 1 + padchar := byte(' ') + flags := uint(0) //tabwriter.AlignRight | tabwriter.Debug + w := tabwriter.NewWriter(out, minwidth, tabwidth, padding, padchar, flags) + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n", "ACTION", "KIND", "NAMESPACE", "NAME") + for _, action := range plan.Spec.Actions { + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n", action.Type, action.Kind, action.Namespace, action.Name) + } + w.Flush() + + return nil +} diff --git a/plugins/pkg/cmd/plan/testdata/simplecreate/apply.yaml b/plugins/pkg/cmd/plan/testdata/simplecreate/apply.yaml new file mode 100644 index 000000000..a979277bf --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simplecreate/apply.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + namespace: default + name: cm1 +data: + foo: bar diff --git a/plugins/pkg/cmd/plan/testdata/simplecreate/existing.yaml b/plugins/pkg/cmd/plan/testdata/simplecreate/existing.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/plugins/pkg/cmd/plan/testdata/simplecreate/plan.yaml b/plugins/pkg/cmd/plan/testdata/simplecreate/plan.yaml new file mode 100644 index 000000000..e72ee6bb5 --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simplecreate/plan.yaml @@ -0,0 +1,17 @@ +apiVersion: plan.kpt.dev/v1alpha1 +kind: Plan +spec: + actions: + - action: Create + apiVersion: v1 + kind: ConfigMap + name: cm1 + namespace: default + object: + apiVersion: v1 + data: + foo: bar + kind: ConfigMap + metadata: + name: cm1 + namespace: default diff --git a/plugins/pkg/cmd/plan/testdata/simplenochange/apply.yaml b/plugins/pkg/cmd/plan/testdata/simplenochange/apply.yaml new file mode 100644 index 000000000..a979277bf --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simplenochange/apply.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + namespace: default + name: cm1 +data: + foo: bar diff --git a/plugins/pkg/cmd/plan/testdata/simplenochange/existing.yaml b/plugins/pkg/cmd/plan/testdata/simplenochange/existing.yaml new file mode 100644 index 000000000..a979277bf --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simplenochange/existing.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + namespace: default + name: cm1 +data: + foo: bar diff --git a/plugins/pkg/cmd/plan/testdata/simplenochange/plan.yaml b/plugins/pkg/cmd/plan/testdata/simplenochange/plan.yaml new file mode 100644 index 000000000..e72ee6bb5 --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simplenochange/plan.yaml @@ -0,0 +1,17 @@ +apiVersion: plan.kpt.dev/v1alpha1 +kind: Plan +spec: + actions: + - action: Create + apiVersion: v1 + kind: ConfigMap + name: cm1 + namespace: default + object: + apiVersion: v1 + data: + foo: bar + kind: ConfigMap + metadata: + name: cm1 + namespace: default diff --git a/plugins/pkg/cmd/plan/testdata/simpleupdate/apply.yaml b/plugins/pkg/cmd/plan/testdata/simpleupdate/apply.yaml new file mode 100644 index 000000000..a87cbf0d9 --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simpleupdate/apply.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + namespace: default + name: cm1 +data: + foo: bar2 diff --git a/plugins/pkg/cmd/plan/testdata/simpleupdate/existing.yaml b/plugins/pkg/cmd/plan/testdata/simpleupdate/existing.yaml new file mode 100644 index 000000000..706935758 --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simpleupdate/existing.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + namespace: default + name: cm1 +data: + foo: bar1 diff --git a/plugins/pkg/cmd/plan/testdata/simpleupdate/plan.yaml b/plugins/pkg/cmd/plan/testdata/simpleupdate/plan.yaml new file mode 100644 index 000000000..7bf9ff8f3 --- /dev/null +++ b/plugins/pkg/cmd/plan/testdata/simpleupdate/plan.yaml @@ -0,0 +1,17 @@ +apiVersion: plan.kpt.dev/v1alpha1 +kind: Plan +spec: + actions: + - action: Create + apiVersion: v1 + kind: ConfigMap + name: cm1 + namespace: default + object: + apiVersion: v1 + data: + foo: bar2 + kind: ConfigMap + metadata: + name: cm1 + namespace: default