diff --git a/chaoscenter/upgrade-agents/control-plane/CONTRIBUTING.MD b/chaoscenter/upgrade-agents/control-plane/CONTRIBUTING.MD new file mode 100644 index 00000000000..6f4aedf01c1 --- /dev/null +++ b/chaoscenter/upgrade-agents/control-plane/CONTRIBUTING.MD @@ -0,0 +1,73 @@ +## Steps to Contribute + +Fixes and improvements can be directly addressed by sending a Pull Request on GitHub. Pull requests will be reviewed by one or more maintainers and merged when acceptable. + +We ask that before contributing, please make the effort to coordinate with the maintainers of the project before submitting large or high impact PRs. This will prevent you from doing extra work that may or may not be merged. + +Use your judgement about what constitutes a large change. If you aren't sure, send a message to the **#litmus-dev** slack or submit an issue on GitHub. + + +### **Sign your work with Developer Certificate of Origin** + +To contribute to this project, you must agree to the Developer Certificate of Origin (DCO) for each commit you make. The DCO is a simple statement that you, as a contributor, have the legal right to make the contribution. + +See the [DCO](https://developercertificate.org/) file for the full text of what you must agree to. + +To successfully sign off your contribution you just add a line to every git commit message: + +```git +Signed-off-by: Joe Smith +``` + +Use your real name (sorry, no pseudonyms or anonymous contributions.) + +If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. You can also use git [aliases](https://git-scm.com/book/tr/v2/Git-Basics-Git-Aliases) like `git config --global alias.ci 'commit -s'`. Now you can commit with git ci and the commit will be signed. + +## **Development Guide** + +Start MongoDB, Auth and GraphQL server as mentioned in the [ChaosCenter Development Guide](https://github.com/litmuschaos/litmus/wiki/ChaosCenter-Development-Guide) to set up the basic structure of the DB. Then start the upgrade manager located in `chaoscenter/upgrade-agents/control-plane` by setting up the environment variables + +``` +export DB_SERVER="mongodb://m1:27015,m2:27016,m3:27017/?replicaSet=rs0" +export DB_USER=admin +export DB_PASSWORD=1234 +export VERSION= +``` +To run the upgrade-manager, run + +``` +go run main.go +``` +The upgrade-manager would get the current version of Litmus through the DB. + +## **Version Upgrade Files** + +`/` folder contains files for the upgrade logic + +- `upgrade-manager.go` - Contains a map of versions with their corresponding version-managers for the versions. +- `vx.y.z/manager.go` - Instantiates the Version Manager and runs the upgradeExecutor in transactions which can be omitted if the operation doesn't support a transaction. +- `vx.y.z/upgrade.go` - Contains the logic of upgradeExecutor of what schema changes are to be made in the specific version. + +There are some other files not mentioned here. + +## **Example: Upgrade to version 3.9.0** + +In version 3.9.0 the following changes are done in DB schema + +- In projects collection (auth DB), member role is updated from `Editor` to `Executor` +- New `is_initial_login` field in users collection (auth DB) whose value is set as false + +Run the upgrade-agent while specifying the version `VERSION=3.9.0` in the environmental variable, and it should now be upgraded. + +## **Best Practices** + +1) If upgrade volume is huge, then transaction is not favorable. +2) Split the upgrades into proprietary functions depending on their purpose and database/collection names. +3) Use logging techniques as used in other versions to provide the user an insight of how the upgrades are being done. +4) While using a transaction, make sure the session context is properly passed into the relevant mongo operations and related functions. +5) Script should be written in a way that even if run twice, should not affect the already updated documents. + + +Below is the basic technical flow for the upgrade-agent + +![image info](./Upgrade-Agent-Flow.png) \ No newline at end of file diff --git a/chaoscenter/upgrade-agents/control-plane/Upgrade-Agent-Flow.png b/chaoscenter/upgrade-agents/control-plane/Upgrade-Agent-Flow.png new file mode 100644 index 00000000000..8e086829573 Binary files /dev/null and b/chaoscenter/upgrade-agents/control-plane/Upgrade-Agent-Flow.png differ diff --git a/chaoscenter/upgrade-agents/control-plane/go.mod b/chaoscenter/upgrade-agents/control-plane/go.mod index b8378a44376..cb37ddf9401 100644 --- a/chaoscenter/upgrade-agents/control-plane/go.mod +++ b/chaoscenter/upgrade-agents/control-plane/go.mod @@ -1,29 +1,40 @@ -module github.com/litmuschaos/litmus/litmus-portal/upgrader-agents/control-plane +module github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane go 1.22 require ( github.com/kelseyhightower/envconfig v1.4.0 - go.mongodb.org/mongo-driver v1.7.1 - go.uber.org/zap v1.18.1 + github.com/sirupsen/logrus v1.4.2 + go.mongodb.org/mongo-driver v1.11.9 +) + +require ( + github.com/jessevdk/go-flags v1.5.0 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect + golang.org/x/exp v0.0.0-20240529005216-23cca8864a10 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/term v0.20.0 // indirect + gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect ) require ( github.com/go-stack/stack v1.8.0 // indirect - github.com/golang/snappy v0.0.1 // indirect - github.com/google/go-cmp v0.5.5 // indirect - github.com/klauspost/compress v1.9.5 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/klauspost/compress v1.17.8 // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect + github.com/mongodb/mongo-tools v0.0.0-20240711192303-088725fbaf4b github.com/pkg/errors v0.9.1 // indirect + github.com/stretchr/testify v1.9.0 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect - github.com/xdg-go/scram v1.0.2 // indirect - github.com/xdg-go/stringprep v1.0.2 // indirect - github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect - go.uber.org/atomic v1.9.0 // indirect - go.uber.org/multierr v1.7.0 // indirect - golang.org/x/crypto v0.17.0 // indirect - golang.org/x/lint v0.0.0-20200302205851-738671d3881b // indirect - golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect - golang.org/x/text v0.14.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/sync v0.7.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/chaoscenter/upgrade-agents/control-plane/go.sum b/chaoscenter/upgrade-agents/control-plane/go.sum index 421b34fb91b..1d8fb9b2637 100644 --- a/chaoscenter/upgrade-agents/control-plane/go.sum +++ b/chaoscenter/upgrade-agents/control-plane/go.sum @@ -1,6 +1,4 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= -github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= 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= @@ -32,10 +30,15 @@ github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/V github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc= +github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4= github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA= @@ -43,14 +46,22 @@ github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dv github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg= github.com/klauspost/compress v1.9.5 h1:U+CaK85mrNNb4k8BNOfgJtJ/gr6kswUCFj6miSzVC6M= github.com/klauspost/compress v1.9.5/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= +github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 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/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= +github.com/mongodb/mongo-tools v0.0.0-20240711192303-088725fbaf4b h1:39IJuPXnaNCjLk6tMywL0OheXyx7S+BTIgn1LUwSrq8= +github.com/mongodb/mongo-tools v0.0.0-20240711192303-088725fbaf4b/go.mod h1:ZqxDY87qeUsPRQ/H8DAOhp4iQA2zQtn2zR/KmLSsA7U= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -63,6 +74,7 @@ github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= @@ -70,51 +82,63 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.0.2 h1:akYIkZ28e6A96dkWNJQu3nmCzH3YfwMPQExUYDaRv7w= github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= +github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= github.com/xdg-go/stringprep v1.0.2 h1:6iq84/ryjjeRmMJwxutI51F2GIPlP5BfTvXHeYjyhBc= github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= +github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a h1:fZHgsYlfvtyqToslyjUt3VOPF4J7aK/3MPcK7xp3PDk= +github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a/go.mod h1:ul22v+Nro/R083muKhosV54bj5niojjWZvU8xrevuH4= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.mongodb.org/mongo-driver v1.7.1 h1:jwqTeEM3x6L9xDXrCxN0Hbg7vdGfPBOTIkr0+/LYZDA= go.mongodb.org/mongo-driver v1.7.1/go.mod h1:Q4oFMbo1+MSNqICAdYMlC/zSTrwCogR4R8NzkI+yfU8= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= -go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0= -go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/multierr v1.7.0 h1:zaiO/rmgFjbmCXdSYJWQcdvOCsthmdaHfr3Gm2Kx4Ec= -go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= -go.uber.org/zap v1.18.1 h1:CSUJ2mjFszzEWt4CdKISEuChVIXGBn3lAPwkRGyVrc4= -go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= +go.mongodb.org/mongo-driver v1.11.9 h1:JY1e2WLxwNuwdBAPgQxjf4BWweUGP86lF55n89cGZVA= +go.mongodb.org/mongo-driver v1.11.9/go.mod h1:P8+TlbZtPFgjUrmnIF41z97iDnSMswJJu6cztZSlCTg= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/exp v0.0.0-20240529005216-23cca8864a10 h1:vpzMC/iZhYFAjJzHU0Cfuq+w1vLLsF2vLkDrPjzKYck= +golang.org/x/exp v0.0.0-20240529005216-23cca8864a10/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 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-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -122,32 +146,50 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= +golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= 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.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 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 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs= +gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk= 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-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/chaoscenter/upgrade-agents/control-plane/main.go b/chaoscenter/upgrade-agents/control-plane/main.go index 6882940796f..df8a2577797 100644 --- a/chaoscenter/upgrade-agents/control-plane/main.go +++ b/chaoscenter/upgrade-agents/control-plane/main.go @@ -2,13 +2,11 @@ package main import ( "log" - "os" - "strings" "github.com/kelseyhightower/envconfig" - "github.com/litmuschaos/litmus/litmus-portal/upgrader-agents/control-plane/pkg/database" - "github.com/litmuschaos/litmus/litmus-portal/upgrader-agents/control-plane/versions" - "go.uber.org/zap" + "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/pkg/database" + "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/versions" + logger "github.com/sirupsen/logrus" ) type Config struct { @@ -28,35 +26,23 @@ func init() { } func main() { - // logging level, dev mode enables debug logs - dev := os.Getenv("DEV_MODE") - var logger *zap.Logger - var err error - - // set log level - if strings.ToLower(dev) == "true" { - logger, err = zap.NewDevelopment() - } else { - logger, err = zap.NewProduction() - } - if err != nil { - log.Fatal("failed to create logger") - } // create database connection + var err error + logger := logger.New() dbClient, err := database.Connect() if err != nil { - logger.Fatal("failed to get db client", zap.Error(err)) + logger.WithError(err).Fatal("failed to get db client") } // create new upgrade manager mg, err := versions.NewUpgradeManager(logger, dbClient) if err != nil { - logger.Fatal("failed to create upgrade manager", zap.Error(err)) + logger.WithError(err).Fatal("failed to create upgrade manager") } if mg != nil { // execute upgrade manager if err = mg.Run(); err != nil { - logger.Fatal("failed to run upgrade manager", zap.Error(err)) + logger.WithError(err).Fatal("failed to run upgrade manager") } } diff --git a/chaoscenter/upgrade-agents/control-plane/pkg/database/constants.go b/chaoscenter/upgrade-agents/control-plane/pkg/database/constants.go index 0f5d53fd3bf..1a56dcb3999 100644 --- a/chaoscenter/upgrade-agents/control-plane/pkg/database/constants.go +++ b/chaoscenter/upgrade-agents/control-plane/pkg/database/constants.go @@ -1,6 +1,13 @@ package database const ( - ServerConfigCollection = "server-config-collection" - DbName = "litmus" + ServerConfigCollection = "serverConfig" + LitmusDB = "litmus" + EnvironmentCollection = "environment" + ProjectCollection = "project" + DBUri = "mongodb://m1:27015,m2:27016,m3:27017/?replicaSet=rs0" + AuthDB = "auth" + AdminDB = "admin" + UsersCollection = "users" + WorkflowCollection = "workflow-collection" ) diff --git a/chaoscenter/upgrade-agents/control-plane/pkg/database/mongo-export.go b/chaoscenter/upgrade-agents/control-plane/pkg/database/mongo-export.go new file mode 100644 index 00000000000..c453b96df0a --- /dev/null +++ b/chaoscenter/upgrade-agents/control-plane/pkg/database/mongo-export.go @@ -0,0 +1,59 @@ +package database + +import ( + "log" + "os" + + "github.com/mongodb/mongo-tools/mongoexport" + "github.com/mongodb/mongo-tools/mongoimport" +) + +func Export(filename string, RawArgs []string) error { + file, err := os.Create(filename) + if err != nil { + return err + } + defer file.Close() + + Options, err := mongoexport.ParseOptions(RawArgs, "", "") + if err != nil { + return err + } + MongoExport, err := mongoexport.New(Options) + if err != nil { + return err + } + defer MongoExport.Close() + + _, err = MongoExport.Export(file) + if err != nil { + return err + } + + return nil +} + +func Import(filename string, RawArgs []string) error { + + Options, err := mongoimport.ParseOptions(RawArgs, "", "") + if err != nil { + return err + } + + MongoImport, err := mongoimport.New(Options) + if err != nil { + return err + } + defer MongoImport.Close() + + // Import documents into 'test' collection + success, failed, err := MongoImport.ImportDocuments() + if err != nil { + return err + } + if failed > 0 { + log.Fatal("Could not import documents", success) + } + + return nil +} diff --git a/chaoscenter/upgrade-agents/control-plane/pkg/database/server-config.go b/chaoscenter/upgrade-agents/control-plane/pkg/database/server-config.go index ba9b0ec2aaa..5d1612ddd8f 100644 --- a/chaoscenter/upgrade-agents/control-plane/pkg/database/server-config.go +++ b/chaoscenter/upgrade-agents/control-plane/pkg/database/server-config.go @@ -15,7 +15,7 @@ type ServerConfig struct { // GetVersion returns the control plane version that is stored in the ServerConfig collection func GetVersion(dbClient *mongo.Client) (ServerConfig, error) { - collection := dbClient.Database(DbName).Collection(ServerConfigCollection) + collection := dbClient.Database(LitmusDB).Collection(ServerConfigCollection) result := collection.FindOne(context.Background(), bson.D{ {"key", "version"}, }) @@ -27,7 +27,7 @@ func GetVersion(dbClient *mongo.Client) (ServerConfig, error) { // UpdateVersion updates the control plane version in the ServerConfig collection func UpdateVersion(dbClient *mongo.Client, version string) error { - collection := dbClient.Database(DbName).Collection(ServerConfigCollection) + collection := dbClient.Database(LitmusDB).Collection(ServerConfigCollection) _, err := collection.UpdateOne(context.Background(), bson.D{ {"key", "version"}, }, bson.D{{"$set", bson.D{{ diff --git a/chaoscenter/upgrade-agents/control-plane/test.txt b/chaoscenter/upgrade-agents/control-plane/test.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/chaoscenter/upgrade-agents/control-plane/versions/upgrade-manager.go b/chaoscenter/upgrade-agents/control-plane/versions/upgrade-manager.go index f904ad1d36f..fa6cf287658 100644 --- a/chaoscenter/upgrade-agents/control-plane/versions/upgrade-manager.go +++ b/chaoscenter/upgrade-agents/control-plane/versions/upgrade-manager.go @@ -3,14 +3,17 @@ package versions import ( "fmt" "os" + "sort" + "strconv" + "strings" - v2_6_0 "github.com/litmuschaos/litmus/litmus-portal/upgrader-agents/control-plane/versions/v2.6.0" + v0_0_0 "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/versions/v0.0.0" - v2_4_0 "github.com/litmuschaos/litmus/litmus-portal/upgrader-agents/control-plane/versions/v2.4.0" + v3_9_0 "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/versions/v3.9.0" - "github.com/litmuschaos/litmus/litmus-portal/upgrader-agents/control-plane/pkg/database" + "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/pkg/database" + log "github.com/sirupsen/logrus" "go.mongodb.org/mongo-driver/mongo" - "go.uber.org/zap" ) // UpgradeExecutor holds the details regarding the version and IVersionManager for a particular version @@ -21,15 +24,70 @@ type UpgradeExecutor struct { // UpgradeManager provides the functionality required to upgrade from the PreviousVersion to the TargetVersion type UpgradeManager struct { - Logger *zap.Logger + Logger *log.Logger DBClient *mongo.Client - PreviousVersion string - TargetVersion string + PreviousVersion *Version + TargetVersion *Version +} + +type Version struct { + Major int + Minor int + Patch int + Beta int +} + +// Converts version from type string to type Version +// For example, "3.0.0-beta1" -> Version{Major: 3, Minor: 0, Patch: 0, Beta: 1} +// "3.1.0" -> Version{Major: 3, Minor: 1, Patch: 0, Beta: 0}, "3.1.1" -> Version{Major: 3, Minor: 1, Patch: 1, Beta: 0} +func ParseVersion(version string) *Version { + parts := strings.Split(version, "-beta") + mainParts := strings.Split(parts[0], ".") + + major, err := strconv.Atoi(mainParts[0]) + if err != nil { + return &Version{} + } + + minor, err := strconv.Atoi(mainParts[1]) + if err != nil { + return &Version{} + } + + mainPartsLength := len(mainParts) + + var patch int + + if mainPartsLength > 2 { + patch, err = strconv.Atoi(mainParts[2]) + if err != nil { + patch = 0 + } + } else { + patch = 0 + } + + if len(parts) > 1 { + beta, err := strconv.Atoi(parts[1]) + if err != nil { + return &Version{} + } + return &Version{Major: major, Minor: minor, Patch: patch, Beta: beta} + } else { + return &Version{Major: major, Minor: minor, Patch: patch, Beta: 0} + } } // NewUpgradeManager creates an instance of a upgrade manager with the proper configurations -func NewUpgradeManager(logger *zap.Logger, dbClient *mongo.Client) (*UpgradeManager, error) { +func NewUpgradeManager(logger *log.Logger, dbClient *mongo.Client) (*UpgradeManager, error) { + + // added for debug only to run version manager consistently + // database.UpdateVersion(dbClient, "3.3.0") + currentVersion := os.Getenv("VERSION") + log.WithFields(log.Fields{ + "targetVersion": currentVersion, + }).Info("About target version") if currentVersion == "" { return nil, fmt.Errorf("current version env data missing") } @@ -37,6 +95,11 @@ func NewUpgradeManager(logger *zap.Logger, dbClient *mongo.Client) (*UpgradeMana if err != nil { return nil, fmt.Errorf("failed to get previous version data from db, error=%w", err) } + + log.WithFields(log.Fields{ + "currentVersion": config.Value, + }).Info("About current version") + if config.Value == nil || config.Value.(string) == "" { return nil, fmt.Errorf("failed to get previous version data from db, value=%v", config.Value) } @@ -48,165 +111,135 @@ func NewUpgradeManager(logger *zap.Logger, dbClient *mongo.Client) (*UpgradeMana return &UpgradeManager{ Logger: logger, DBClient: dbClient, - PreviousVersion: config.Value.(string), - TargetVersion: currentVersion, + PreviousVersion: ParseVersion(config.Value.(string)), + TargetVersion: ParseVersion(currentVersion), }, nil } -// getUpgradePath returns a map that determines the possible upgrade path for any upgrade -func (m *UpgradeManager) getUpgradePath() map[string]UpgradeExecutor { +// getVersionMap returns a map that determines the possible upgrade path for any upgrade +func (m *UpgradeManager) getVersionMap() map[string]UpgradeExecutor { // key : previous version, // value :{ Version Manger that upgrades the system from priv version to next, NextVersion points to next version in the path} return map[string]UpgradeExecutor{ - "2.3.0": { - NextVersion: "2.4.0", - VersionManager: v2_4_0.NewVersionManger(m.Logger, m.DBClient), - }, - - "2.4.0": { - NextVersion: "2.5.0", - VersionManager: nil, - }, - - "2.5.0": { - NextVersion: "2.6.0", - VersionManager: v2_6_0.NewVersionManger(m.Logger, m.DBClient), - }, - - "2.6.0": { - NextVersion: "2.7.0", - VersionManager: nil, - }, - - "2.7.0": { - NextVersion: "2.8.0", - VersionManager: nil, - }, - - "2.8.0": { - NextVersion: "2.9.0", - VersionManager: nil, - }, - - "2.9.0": { - NextVersion: "2.10.0", - VersionManager: nil, - }, - - "2.10.0": { - NextVersion: "2.11.0", - VersionManager: nil, - }, - - "2.11.0": { - NextVersion: "2.12.0", - VersionManager: nil, + "0.0.0": { + NextVersion: "", + VersionManager: v0_0_0.NewVersionManger(m.Logger, m.DBClient), }, - - "2.12.0": { - NextVersion: "2.13.0", - VersionManager: nil, + "3.9.0": { + NextVersion: "", + VersionManager: v3_9_0.NewVersionManger(m.Logger, m.DBClient), }, + } +} - "2.13.0": { - NextVersion: "2.14.0", - VersionManager: nil, - }, +func arrayToVersion(versionArray []int) string { + if versionArray[3] == 0 { + return strconv.Itoa(versionArray[0]) + "." + strconv.Itoa(versionArray[1]) + "." + strconv.Itoa(versionArray[2]) + } else { + return strconv.Itoa(versionArray[0]) + "." + strconv.Itoa(versionArray[1]) + "." + strconv.Itoa(versionArray[2]) + "-beta" + strconv.Itoa(versionArray[3]) + } +} - "2.14.0": { - NextVersion: "3.0-beta1", - VersionManager: nil, - }, +func (v Version) getVersion() string { + if v.Beta != 0 { + return strconv.Itoa(v.Major) + "." + strconv.Itoa(v.Minor) + "." + strconv.Itoa(v.Patch) + "-beta" + strconv.Itoa(v.Beta) + } else { + return strconv.Itoa(v.Major) + "." + strconv.Itoa(v.Minor) + "." + strconv.Itoa(v.Patch) + } +} - "3.0-beta1": { - NextVersion: "3.0.0-beta2", - VersionManager: nil, - }, +// sortVersionArray sorts the version array containing the versions as strings in ascending order +func sortVersionArray(versionArray []string) []string { + var versionMatrix [][]int - "3.0.0-beta2": { - NextVersion: "3.0.0-beta3", - VersionManager: nil, - }, + for _, v := range versionArray { + var versionInt []int - "3.0.0-beta3": { - NextVersion: "3.0.0-beta4", - VersionManager: nil, - }, + version := ParseVersion(v) + versionInt = append(versionInt, version.Major, version.Minor, version.Patch, version.Beta) + versionMatrix = append(versionMatrix, versionInt) + } + sort.Slice(versionMatrix, func(i, j int) bool { + for k := 0; k < len(versionMatrix[i]) && k < len(versionMatrix[j]); k++ { + if versionMatrix[i][k] != versionMatrix[j][k] { + return versionMatrix[i][k] < versionMatrix[j][k] + } + } + return len(versionMatrix[i]) < len(versionMatrix[j]) + }) - "3.0.0-beta4": { - NextVersion: "3.0.0-beta5", - VersionManager: nil, - }, + var sortedVersionArray []string - "3.0.0-beta5": { - NextVersion: "3.0.0-beta6", - VersionManager: nil, - }, + for _, v := range versionMatrix { + sortedVersionArray = append(sortedVersionArray, arrayToVersion(v)) + } + // Print the sorted matrixay + return sortedVersionArray +} - "3.0.0-beta6": { - NextVersion: "3.0.0-beta7", - VersionManager: nil, - }, +func parseVersionMap(m map[string]UpgradeExecutor, previousVersion string, targetVersion string) []string { + var versions []string + for version := range m { + versions = append(versions, version) + } + _, okP := m[previousVersion] + _, okT := m[targetVersion] - "3.0.0-beta7": { - NextVersion: "3.0.0-beta8", - VersionManager: nil, - }, + if !okP { + versions = append(versions, previousVersion) + } - // latest version, no more upgrades available - "3.0.0-beta8": { - NextVersion: "", - VersionManager: nil, - }, + if !okT { + versions = append(versions, targetVersion) } + return sortVersionArray(versions) } -// verifyPath verifies whether the current upgrade from PreviousVersion to TargetVersion -// is possible given the configured upgrade path -func (m *UpgradeManager) verifyPath(upgradePath map[string]UpgradeExecutor) error { - - _, okP := upgradePath[m.PreviousVersion] - _, okT := upgradePath[m.TargetVersion] +func linearSearchArray(version string, versionMapArray []string) int { - if !okP && !okT { - return fmt.Errorf("previous version=%v or target version=%v not found in upgrade path", m.PreviousVersion, m.TargetVersion) - } - versionIterator := m.PreviousVersion - for versionIterator != "" { - versionIterator = upgradePath[versionIterator].NextVersion - if versionIterator == m.TargetVersion { - return nil + for i, v := range versionMapArray { + if v == version { + return i } } - return fmt.Errorf("upgrade path not found from previous version=%v to target version=%v", m.PreviousVersion, m.TargetVersion) + return -1 +} + +// traceUpgradePath traces the upgrade path between the two versions by taking in them and the map +func traceUpgradePath(previousVersion Version, targetVersion Version, getVersionMap map[string]UpgradeExecutor) []string { + versionStringMap := parseVersionMap(getVersionMap, previousVersion.getVersion(), targetVersion.getVersion()) + + startIndex := linearSearchArray(previousVersion.getVersion(), versionStringMap) + endIndex := linearSearchArray(targetVersion.getVersion(), versionStringMap) + return versionStringMap[startIndex+1 : endIndex+1] } // Run executes all the steps required in the upgrade path from PreviousVersion to TargetVersion func (m *UpgradeManager) Run() error { - upgradePath := m.getUpgradePath() + versionMap := m.getVersionMap() - // verify if upgrade possible - if err := m.verifyPath(upgradePath); err != nil { - return err - } + upgradePath := traceUpgradePath(*m.PreviousVersion, *m.TargetVersion, versionMap) + log.WithFields(log.Fields{ + "upgradePath": upgradePath, + }).Info("Sequential upgrade path to be followed") - // start upgrade from previous version to target version - versionIterator := m.PreviousVersion - // loop till the target version is reached - for versionIterator != m.TargetVersion { - // Skipping schema upgrade, if version manager not available (Only version will be upgraded) - if upgradePath[versionIterator].VersionManager != nil { - if err := upgradePath[versionIterator].VersionManager.Run(); err != nil { - return fmt.Errorf("failed to upgrade to version %v, error : %w", versionIterator, err) + for _, v := range upgradePath { + + _, exists := versionMap[v] + if exists && versionMap[v].VersionManager != nil { + if err := versionMap[v].VersionManager.Run(); err != nil { + return fmt.Errorf("failed to upgrade to version %v, error : %w", v, err) } + database.UpdateVersion(m.DBClient, v) + log.WithFields(log.Fields{ + "version": v, + }).Info("Version upgraded to an intermediate version") } - versionIterator = upgradePath[versionIterator].NextVersion - } - - err := database.UpdateVersion(m.DBClient, m.TargetVersion) - if err != nil { - return fmt.Errorf("failed to update version in server config collection, error=%w", err) } + database.UpdateVersion(m.DBClient, upgradePath[len(upgradePath)-1]) + log.WithFields(log.Fields{ + "version": m.TargetVersion.getVersion(), + }).Info("Version upgrade successful") return nil } diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v0.0.0/manager.go b/chaoscenter/upgrade-agents/control-plane/versions/v0.0.0/manager.go new file mode 100644 index 00000000000..5798d442ee0 --- /dev/null +++ b/chaoscenter/upgrade-agents/control-plane/versions/v0.0.0/manager.go @@ -0,0 +1,44 @@ +package v0_0_0 + +import ( + "context" + log "github.com/sirupsen/logrus" + "go.mongodb.org/mongo-driver/mongo" +) + +/* Template for Upgrade Manager to be followed for introducing new upgrade files*/ + +// VersionManager implements IVersionManger +type VersionManager struct { + Logger *log.Logger + DBClient *mongo.Client + Context *context.Context +} + +// NewVersionManger provides a new instance of a new VersionManager +func NewVersionManger(logger *log.Logger, dbClient *mongo.Client) *VersionManager { + return &VersionManager{Logger: logger, DBClient: dbClient} +} + +// Run executes all the steps required for the Version Manger +// to upgrade from the previous version to `this` version +func (vm VersionManager) Run() error { + ctx := context.Background() + err := upgradeUsersCollection(vm.Logger, vm.DBClient, ctx) + if err != nil { + return err + } + + err = upgradeEnvironmentCollectionIndexes(vm.Logger, vm.DBClient, ctx) + if err != nil { + return err + } + + err = upgradeWorkflow(vm.Logger, vm.DBClient, ctx) + + if err != nil { + return err + } + + return err +} diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v0.0.0/upgrade.go b/chaoscenter/upgrade-agents/control-plane/versions/v0.0.0/upgrade.go new file mode 100644 index 00000000000..23e6078870c --- /dev/null +++ b/chaoscenter/upgrade-agents/control-plane/versions/v0.0.0/upgrade.go @@ -0,0 +1,143 @@ +package v0_0_0 + +// remove +import ( + "context" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + + "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/pkg/database" + log "github.com/sirupsen/logrus" +) + +/* This example upgrade renames auth collection users to client*/ + +func upgradeUsersCollection(logger *log.Logger, dbClient *mongo.Client, ctx context.Context) error { + + logVersion := log.Fields{ + "version": "0.0.0", + "database": database.AdminDB, + "collection": database.UsersCollection, + } + + res := dbClient.Database(database.AdminDB).RunCommand( + context.Background(), + bson.D{{"renameCollection", "auth.users"}, {"to", "auth.client"}}, + ) + if res.Err() != nil { + log.WithFields(logVersion).Fatal("Error while renaming collection 'auth.users' to 'auth.client'") + return res.Err() + } + + logger.WithFields(logVersion).Info("Users collection renamed to admin while upgrading to intermediate version v3.8.0") + + logger.WithFields(logVersion).Info("Collection 'auth.users' renamed to 'auth.client' successfully.") + + return nil +} + +func upgradeEnvironmentCollectionIndexes(logger *log.Logger, dbClient *mongo.Client, ctx context.Context) error { + var indexes []string + var environmentIDIndexName string + + environmentCollection := dbClient.Database(database.LitmusDB).Collection(database.EnvironmentCollection) + indexView := environmentCollection.Indexes() + cursor, err := indexView.List(ctx) + if err != nil { + log.Error("error listing indexes: %w", err) + return err + } + defer cursor.Close(ctx) + + environmentIDIndexExists := false + + logVersion := log.Fields{ + "version": "0.0.0", + "database": database.LitmusDB, + "collection": database.EnvironmentCollection, + } + + for cursor.Next(ctx) { + var index bson.M + if err := cursor.Decode(&index); err != nil { + log.Fatal("error decoding index: %w", err) + } + indexes = append(indexes, index["name"].(string)) + if keys, ok := index["key"].(bson.M); ok { + if _, found := keys["environment_id"]; found { + environmentIDIndexExists = true + environmentIDIndexName = index["name"].(string) + } + } + } + + logIndexes := log.Fields{ + "version": "3.4.0", + "database": database.LitmusDB, + "collection": database.EnvironmentCollection, + "indexes": indexes, + } + + logger.WithFields(logIndexes).Info("Indexes found in environment collection while upgrading to intermediate version v3.4.0") + + logFields := log.Fields{ + "collection": database.EnvironmentCollection, + "db": database.LitmusDB, + } + + if environmentIDIndexExists { + _, err := environmentCollection.Indexes().DropOne(ctx, environmentIDIndexName) + if err != nil { + log.Fatal("error dropping index: %w", err) + } + logger.WithFields(logFields).Info("Deleted an existing index in environment collection while upgrading to intermediate v3.4.0") + + indexModel := mongo.IndexModel{ + Keys: bson.M{"environment_id": 1}, + Options: options.Index(). + SetUnique(true). + SetPartialFilterExpression(bson.D{ + {"isRemoved", false}, + }), + } + + _, err = environmentCollection.Indexes().CreateOne(ctx, indexModel) + if err != nil { + log.Fatal("error creating index: %w", err) + } + + log.WithFields(logVersion).Info("Created a new index with partial filter expression environment_id while upgrading to intermediate v3.4.0") + + } else { + log.Fatal("environment id index not found in version v3.4.0") + } + + return nil +} + +func upgradeWorkflow(logger *log.Logger, dbClient *mongo.Client, ctx context.Context) error { + workflowCollection := dbClient.Database("litmus").Collection("workflow-collection") + + logVersion := log.Fields{ + "version": "0.0.0", + "database": database.LitmusDB, + "collection": database.WorkflowCollection, + } + + //delete the existing workflow_name index + _, err := workflowCollection.Indexes().DropOne(context.Background(), "workflow_name_1") + if err != nil { + logger.WithFields(logVersion).Fatal("Error while dropping workflow") + } + + //create a new workflow index with partial filter expression + _, err = workflowCollection.Indexes().CreateOne(context.Background(), + mongo.IndexModel{Keys: bson.M{"workflow_name": 1}, + Options: options.Index().SetUnique(true).SetPartialFilterExpression(bson.D{{ + "isRemoved", false, + }})}) + + return err +} diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v2.4.0/auth.go b/chaoscenter/upgrade-agents/control-plane/versions/v2.4.0/auth.go deleted file mode 100644 index df30b0a8bb8..00000000000 --- a/chaoscenter/upgrade-agents/control-plane/versions/v2.4.0/auth.go +++ /dev/null @@ -1,62 +0,0 @@ -package v2_4_0 - -import ( - "context" - "fmt" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.uber.org/zap" -) - -// upgradeAuthDb: migrates project collection from litmus-db to auth-db, renames usercredentials collection to users" -func upgradeAuthDb(logger *zap.Logger, dbClient *mongo.Client) error { - - // migration of project collection to auth DB - projectLitmusCollection := dbClient.Database("litmus").Collection("project") //project collection from litmus DB - userLitmusCollection := dbClient.Database("litmus").Collection("user") // user collection from litmus DB - usersAuthCollection := dbClient.Database("auth").Collection("users") // users collection from auth DB - authDBProjectCollection := dbClient.Database("auth").Collection("project") // project collected in auth DB - - // fetching the projects from project collection in litmus DB - cursor, err := projectLitmusCollection.Find(context.Background(), bson.M{}) - if err != nil { - fmt.Errorf("Error in getting project collection: %w", err) - } - - var result []interface{} - if err := cursor.All(context.Background(), &result); err != nil { - fmt.Errorf("Error: %w", err) - } - - // inserting the project documents in project collection(auth DB) - _, err = authDBProjectCollection.InsertMany(context.TODO(), result) - if err != nil { - fmt.Errorf("Error: %w", err) - } - - // deleting project collection in litmus DB - err = projectLitmusCollection.Drop(context.Background()) - if err != nil { - fmt.Errorf("Error: %w", err) - } - - // deleting user collection in litmus DB - err = userLitmusCollection.Drop(context.Background()) - if err != nil { - fmt.Errorf("Error: %w", err) - } - - // deleting users collection in auth DB - err = usersAuthCollection.Drop(context.Background()) - if err != nil { - fmt.Errorf("Error: %w", err) - } - - // renaming usercredentials collection to users - res := dbClient.Database("admin").RunCommand(context.Background(), bson.D{{"renameCollection", "auth.usercredentials"}, {"to", "auth.users"}}) - if res.Err() != nil { - return res.Err() - } - return err -} diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v2.4.0/manager.go b/chaoscenter/upgrade-agents/control-plane/versions/v2.4.0/manager.go deleted file mode 100644 index 9794896f752..00000000000 --- a/chaoscenter/upgrade-agents/control-plane/versions/v2.4.0/manager.go +++ /dev/null @@ -1,27 +0,0 @@ -package v2_4_0 - -import ( - "go.mongodb.org/mongo-driver/mongo" - "go.uber.org/zap" -) - -// VersionManager implements IVersionManger -type VersionManager struct { - Logger *zap.Logger - DBClient *mongo.Client -} - -// NewVersionManger provides a new instance of a new VersionManager -func NewVersionManger(logger *zap.Logger, dbClient *mongo.Client) *VersionManager { - return &VersionManager{Logger: logger, DBClient: dbClient} -} - -// Run executes all the steps required for the Version Manger -// to upgrade from the previous version to `this` version -func (vm VersionManager) Run() error { - if err := upgradeAuthDb(vm.Logger, vm.DBClient); err != nil { - return err - } - // other upgrade step ..... - return nil -} diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v2.6.0/manager.go b/chaoscenter/upgrade-agents/control-plane/versions/v2.6.0/manager.go deleted file mode 100644 index 20ac2ae396e..00000000000 --- a/chaoscenter/upgrade-agents/control-plane/versions/v2.6.0/manager.go +++ /dev/null @@ -1,31 +0,0 @@ -package v2_6_0 - -import ( - "context" - "fmt" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" - "go.uber.org/zap" -) - -// upgradeWorkflowCollection updated the index related changes in workflow-collection -func upgradeWorkflowCollection(logger *zap.Logger, dbClient *mongo.Client) error { - workflowCollection := dbClient.Database("litmus").Collection("workflow-collection") - - //delete the existing workflow_name index - _, err := workflowCollection.Indexes().DropOne(context.Background(), "workflow_name_1") - if err != nil { - fmt.Errorf("error: %w", err) - } - - //create a new workflow index with partial filter expression - _, err = workflowCollection.Indexes().CreateOne(context.Background(), - mongo.IndexModel{Keys: bson.M{"workflow_name": 1}, - Options: options.Index().SetUnique(true).SetPartialFilterExpression(bson.D{{ - "isRemoved", false, - }})}) - - return err -} diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v2.6.0/workflow.go b/chaoscenter/upgrade-agents/control-plane/versions/v2.6.0/workflow.go deleted file mode 100644 index 3db30f689af..00000000000 --- a/chaoscenter/upgrade-agents/control-plane/versions/v2.6.0/workflow.go +++ /dev/null @@ -1,26 +0,0 @@ -package v2_6_0 - -import ( - "go.mongodb.org/mongo-driver/mongo" - "go.uber.org/zap" -) - -// VersionManager implements IVersionManger -type VersionManager struct { - Logger *zap.Logger - DBClient *mongo.Client -} - -// NewVersionManger provides a new instance of a new VersionManager -func NewVersionManger(logger *zap.Logger, dbClient *mongo.Client) *VersionManager { - return &VersionManager{Logger: logger, DBClient: dbClient} -} - -// Run executes all the steps required for the Version Manger -// to upgrade from the previous version to `this` version -func (vm VersionManager) Run() error { - if err := upgradeWorkflowCollection(vm.Logger, vm.DBClient); err != nil { - return nil - } - return nil -} diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v3.9.0/manager.go b/chaoscenter/upgrade-agents/control-plane/versions/v3.9.0/manager.go new file mode 100644 index 00000000000..0ba5ccddfc9 --- /dev/null +++ b/chaoscenter/upgrade-agents/control-plane/versions/v3.9.0/manager.go @@ -0,0 +1,75 @@ +package v3_9_0 + +import ( + "context" + + "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/pkg/database" + log "github.com/sirupsen/logrus" + "go.mongodb.org/mongo-driver/mongo" +) + +// VersionManager implements IVersionManger +type VersionManager struct { + Logger *log.Logger + DBClient *mongo.Client + Context *context.Context +} + +// NewVersionManger provides a new instance of a new VersionManager +func NewVersionManger(logger *log.Logger, dbClient *mongo.Client) *VersionManager { + return &VersionManager{Logger: logger, DBClient: dbClient} +} + +// Run executes all the steps required for the Version Manger +// to upgrade from the previous version to `this` version +func (vm VersionManager) Run() error { + ctx := context.Background() + session, err := vm.DBClient.StartSession() + + defer session.EndSession(ctx) + + logVersion := log.Fields{ + "version": "3.9.0", + "database": database.LitmusDB, + "collection": database.ProjectCollection, + } + + if err != nil { + // log.Fatal(logVersion, err) + log.WithFields(logVersion).Fatal("Error while starting session") + } + + defer session.EndSession(ctx) + + err = mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error { + // Start the transaction + err := session.StartTransaction() + if err != nil { + log.Fatal("error starting transaction: %w", err) + } + + if err := upgradeProjectCollection(vm.Logger, vm.DBClient, sc); err != nil { + return err + } + + if err := upgradeUsersCollection(vm.Logger, vm.DBClient, sc); err != nil { + return err + } + // Commit the transaction + err = session.CommitTransaction(sc) + + if err != nil { + return err + } + + return nil + }) + if err != nil { + // Abort the transaction if it fails + abortError := session.AbortTransaction(ctx) + if abortError != nil { + log.Fatal("error committing transaction: %w", err) + } + } + return err +} diff --git a/chaoscenter/upgrade-agents/control-plane/versions/v3.9.0/upgrade.go b/chaoscenter/upgrade-agents/control-plane/versions/v3.9.0/upgrade.go new file mode 100644 index 00000000000..9e5abf8f3ee --- /dev/null +++ b/chaoscenter/upgrade-agents/control-plane/versions/v3.9.0/upgrade.go @@ -0,0 +1,89 @@ +package v3_9_0 + +import ( + "context" + + "github.com/litmuschaos/litmus/chaoscenter/upgrader-agents/control-plane/pkg/database" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + + log "github.com/sirupsen/logrus" +) + +const ( + oldRole = "Editor" + newRole = "Executor" +) + +func upgradeProjectCollection(logger *log.Logger, dbClient *mongo.Client, ctx context.Context) error { + + var err error + collection := dbClient.Database(database.AuthDB).Collection(database.ProjectCollection) + + // Update the role from Editor to Executor + filter := bson.M{"members.role": oldRole} + update := bson.M{ + "$set": bson.M{"members.$[elem].role": newRole}, + } + arrayFilters := options.Update().SetArrayFilters(options.ArrayFilters{ + Filters: []interface{}{ + bson.M{"elem.role": oldRole}, + }, + }) + + logFields := log.Fields{ + "version": "3.9.0", + "database": database.AuthDB, + "collection": database.ProjectCollection, + } + logger.WithFields(logFields).Info("Updating editor to executor") + updateResult, err := collection.UpdateMany(ctx, filter, update, arrayFilters) + if err != nil { + logger.WithFields(logFields).Fatal("Error while updating documents in version v3.9.0") + return err + } + + logUpdateDocuments := log.Fields{ + "documents_matched": updateResult.MatchedCount, + "documents_updated": updateResult.ModifiedCount, + "version": "3.9.0", + } + + logger.WithFields(logUpdateDocuments).Infof("Matched %v documents and updated %v documents in project collection", updateResult.MatchedCount, updateResult.ModifiedCount) + + return nil + +} + +func upgradeUsersCollection(logger *log.Logger, dbClient *mongo.Client, ctx context.Context) error { + usersCollection := dbClient.Database(database.AuthDB).Collection(database.UsersCollection) + + logFields := log.Fields{ + "version": "3.9.0", + "database": database.AuthDB, + "collection": database.UsersCollection, + } + + logger.WithFields(logFields).Info("Adding is_initial_login field") + + // Add the new field is_initial_lgin to all documents in Users Collection + filter := bson.M{} + update := bson.M{ + "$set": bson.M{"is_initial_login": false}, + } + + updateResult, err := usersCollection.UpdateMany(ctx, filter, update) + if err != nil { + logger.WithFields(logFields).Fatal("Error while updating documents in version v3.9.0: ", err) + return err + } + logDocumentsCount := log.Fields{ + "documents_matched": updateResult.MatchedCount, + "documents_updated": updateResult.ModifiedCount, + "version": "3.9.0", + } + + logger.WithFields(logDocumentsCount).Infof("Matched %v documents and updated %v documents in users collection.", updateResult.MatchedCount, updateResult.ModifiedCount) + return nil +}