From b6f854ff185ac375974248f208cb6f4ea8e45705 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Mon, 19 Jun 2023 14:54:48 +0300 Subject: [PATCH 01/12] Implement config builder parts as the command config build --- .github/workflows/build-client.yaml | 7 +- cmd/kubectl-k8ssandra/config/builder.go | 74 + cmd/kubectl-k8ssandra/config/config.go | 37 + cmd/kubectl-k8ssandra/k8ssandra/k8ssandra.go | 2 + go.mod | 1 + go.sum | 34 + pkg/config/builder.go | 212 ++ pkg/config/builder_test.go | 106 + pkg/config/types.go | 57 + testfiles/4.1/cassandra.yaml | 1819 ++++++++++++++++++ testfiles/cassandra-rackdc.properties | 39 + 11 files changed, 2386 insertions(+), 2 deletions(-) create mode 100644 cmd/kubectl-k8ssandra/config/builder.go create mode 100644 cmd/kubectl-k8ssandra/config/config.go create mode 100644 pkg/config/builder.go create mode 100644 pkg/config/builder_test.go create mode 100644 pkg/config/types.go create mode 100644 testfiles/4.1/cassandra.yaml create mode 100644 testfiles/cassandra-rackdc.properties diff --git a/.github/workflows/build-client.yaml b/.github/workflows/build-client.yaml index 1ad5e03..fb391d7 100644 --- a/.github/workflows/build-client.yaml +++ b/.github/workflows/build-client.yaml @@ -39,12 +39,14 @@ jobs: build_docker_image: name: Build k8ssandra-client Docker Image runs-on: ubuntu-latest - if: github.ref == 'refs/heads/master' + if: github.ref == 'refs/heads/main' steps: - name: Check out code into the Go module directory uses: actions/checkout@v3 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 + uses: docker/setup-buildx-action@v2 + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 - name: Login to DockerHub uses: docker/login-action@v2 with: @@ -59,6 +61,7 @@ jobs: id: docker_build uses: docker/build-push-action@v3 with: + load: false file: cmd/kubectl-k8ssandra/Dockerfile push: ${{ github.event_name != 'pull_request' }} tags: k8ssandra/k8ssandra-client:${{ steps.vars.outputs.sha_short }}, k8ssandra/k8ssandra-client:latest diff --git a/cmd/kubectl-k8ssandra/config/builder.go b/cmd/kubectl-k8ssandra/config/builder.go new file mode 100644 index 0000000..1add535 --- /dev/null +++ b/cmd/kubectl-k8ssandra/config/builder.go @@ -0,0 +1,74 @@ +package config + +import ( + "context" + "fmt" + + "github.com/k8ssandra/k8ssandra-client/pkg/config" + "github.com/spf13/cobra" + "k8s.io/cli-runtime/pkg/genericclioptions" +) + +var ( + configBuilderExample = ` + # Process the config files from cass-operator input + %[1]s build [] + ` +) + +type builderOptions struct { + configFlags *genericclioptions.ConfigFlags + genericclioptions.IOStreams +} + +func newBuilderOptions(streams genericclioptions.IOStreams) *builderOptions { + return &builderOptions{ + configFlags: genericclioptions.NewConfigFlags(true), + IOStreams: streams, + } +} + +// NewCmd provides a cobra command wrapping newAddOptions +func NewBuilderCmd(streams genericclioptions.IOStreams) *cobra.Command { + o := newBuilderOptions(streams) + + cmd := &cobra.Command{ + Use: "build [flags]", + Short: "Build config files from cass-operator input", + Example: fmt.Sprintf(configBuilderExample, "kubectl k8ssandra config"), + RunE: func(c *cobra.Command, args []string) error { + if err := o.Complete(c, args); err != nil { + return err + } + if err := o.Validate(); err != nil { + return err + } + if err := o.Run(); err != nil { + return err + } + + return nil + }, + } + + fl := cmd.Flags() + o.configFlags.AddFlags(fl) + return cmd +} + +// Complete parses the arguments and necessary flags to options +func (c *builderOptions) Complete(cmd *cobra.Command, args []string) error { + return nil +} + +// Validate ensures that all required arguments and flag values are provided +func (c *builderOptions) Validate() error { + return nil +} + +// Run processes the input, creates a connection to Kubernetes and processes a secret to add the users +func (c *builderOptions) Run() error { + ctx := context.Background() + + return config.Build(ctx) +} diff --git a/cmd/kubectl-k8ssandra/config/config.go b/cmd/kubectl-k8ssandra/config/config.go new file mode 100644 index 0000000..91744e7 --- /dev/null +++ b/cmd/kubectl-k8ssandra/config/config.go @@ -0,0 +1,37 @@ +package config + +import ( + "github.com/spf13/cobra" + "k8s.io/cli-runtime/pkg/genericclioptions" +) + +type ClientOptions struct { + configFlags *genericclioptions.ConfigFlags + genericclioptions.IOStreams +} + +// NewClientOptions provides an instance of ClientOptions with default values +func NewClientOptions(streams genericclioptions.IOStreams) *ClientOptions { + return &ClientOptions{ + configFlags: genericclioptions.NewConfigFlags(true), + IOStreams: streams, + } +} + +// NewCmd provides a cobra command wrapping ClientOptions +func NewCmd(streams genericclioptions.IOStreams) *cobra.Command { + o := NewClientOptions(streams) + + cmd := &cobra.Command{ + Use: "config [subcommand] [flags]", + } + + // Add subcommands + cmd.AddCommand(NewBuilderCmd(streams)) + // TODO Add the idea of allowing to modify cassandra-yaml with interactive editor from the + // command line + + o.configFlags.AddFlags(cmd.Flags()) + + return cmd +} diff --git a/cmd/kubectl-k8ssandra/k8ssandra/k8ssandra.go b/cmd/kubectl-k8ssandra/k8ssandra/k8ssandra.go index 45d9db4..b8b5b5d 100644 --- a/cmd/kubectl-k8ssandra/k8ssandra/k8ssandra.go +++ b/cmd/kubectl-k8ssandra/k8ssandra/k8ssandra.go @@ -8,6 +8,7 @@ import ( // "github.com/k8ssandra/k8ssandra-client/cmd/kubectl-k8ssandra/list" // "github.com/k8ssandra/k8ssandra-client/cmd/kubectl-k8ssandra/migrate" // "github.com/k8ssandra/k8ssandra-client/cmd/kubectl-k8ssandra/nodetool" + "github.com/k8ssandra/k8ssandra-client/cmd/kubectl-k8ssandra/config" "github.com/k8ssandra/k8ssandra-client/cmd/kubectl-k8ssandra/operate" "github.com/k8ssandra/k8ssandra-client/cmd/kubectl-k8ssandra/users" @@ -49,6 +50,7 @@ func NewCmd(streams genericclioptions.IOStreams) *cobra.Command { // cmd.AddCommand(migrate.NewCmd(streams)) cmd.AddCommand(users.NewCmd(streams)) // cmd.AddCommand(migrate.NewInstallCmd(streams)) + cmd.AddCommand(config.NewCmd(streams)) // cmd.Flags().BoolVar(&o.listNamespaces, "list", o.listNamespaces, "if true, print the list of all namespaces in the current KUBECONFIG") o.configFlags.AddFlags(cmd.Flags()) diff --git a/go.mod b/go.mod index 027fc83..1d3089a 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( github.com/Masterminds/semver/v3 v3.1.1 // indirect github.com/Masterminds/sprig/v3 v3.2.2 // indirect github.com/Masterminds/squirrel v1.5.3 // indirect + github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d // indirect github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535 // indirect github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect diff --git a/go.sum b/go.sum index c9186bc..8f6db55 100644 --- a/go.sum +++ b/go.sum @@ -39,6 +39,10 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= +github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= +github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.0.0 h1:dtDWrepsVPfW9H/4y7dDgFc2MBUSeJhlaDtK13CxFlU= github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= @@ -61,8 +65,13 @@ github.com/Masterminds/squirrel v1.5.3 h1:YPpoceAcxuzIljlr5iWpNKaql7hLeG1KLSrhvd github.com/Masterminds/squirrel v1.5.3/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= github.com/Microsoft/go-winio v0.5.1 h1:aPJp2QD7OOrhO5tQXqQoGSJc+DjDtWTGLOmNyAm6FgY= github.com/Microsoft/hcsshim v0.9.3 h1:k371PzBuRrz2b+ebGuI2nVgVhgsVX60jMfSw80NECxo= +github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d h1:UrqY+r/OJnIp5u0s1SbQ8dVfLCZJsnvazdBP5hS4iRs= +github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d h1:O47TZtmKaBkPubAQBONxtC61E7GPOLkGDhJDWChl17s= +github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d/go.mod h1:tRDczOw8/ipMRMBrO3kvAWxqQNnVXglAzhIqrXmKRAg= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= @@ -70,6 +79,7 @@ github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hC github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535 h1:4daAzAu0S6Vi7/lbWECcX0j45yZReDZ56BQsrVBOEEY= github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= @@ -82,6 +92,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= +github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/bshuster-repo/logrus-logstash-hook v1.0.0 h1:e+C0SB5R1pu//O4MQ3f9cFuPGoOVeF2fE4Og9otCc70= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/bugsnag/bugsnag-go v0.0.0-20141110184014-b1d153021fcd h1:rFt+Y/IK1aEZkEHchZRSq9OQbsSzIT/OrI8YFFmRIng= @@ -117,6 +129,7 @@ github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2 github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= github.com/containerd/containerd v1.6.6 h1:xJNPhbrmz8xAMDNoVjHy9YHtWwEQNS+CDkcIRh7t8Y0= github.com/containerd/containerd v1.6.6/go.mod h1:ZoP1geJldzCVY3Tonoz7b1IXk8rIX0Nltt5QE4OMNk0= +github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= @@ -150,6 +163,8 @@ github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDD github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1 h1:ZClxb8laGDf5arXfYcAtECDFgAgHklGI8CxgjHnXKJ4= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= +github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= +github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful/v3 v3.10.2 h1:hIovbnmBTLjHXkqEBUz3HGpXZdM7ZrE9fJIZIqlJLqE= github.com/emicklei/go-restful/v3 v3.10.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -175,6 +190,7 @@ github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/flowstack/go-jsonschema v0.1.1/go.mod h1:yL7fNggx1o8rm9RlgXv7hTBWxdBM0rVwpMwimd3F3N0= +github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= @@ -192,6 +208,7 @@ github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2 github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= 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= @@ -312,6 +329,8 @@ github.com/gosuri/uitable v0.0.4 h1:IG2xLKRvErL3uhY6e1BylFzG+aJiwQviDDTfOKeKTpY= github.com/gosuri/uitable v0.0.4/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= @@ -347,8 +366,10 @@ github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLf github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= +github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= 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/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -358,6 +379,7 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1 github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/k8ssandra/cass-operator v1.15.1-0.20230613083330-58dc7268f372 h1:2tpKA5pSwf8F1br1GzUf2BuvkNZjF5WJnTjkqlPdB3M= github.com/k8ssandra/cass-operator v1.15.1-0.20230613083330-58dc7268f372/go.mod h1:SweDRjqzPDrZsGzoN0b/YzWKk+DCy0+4htELKRoMVI8= github.com/karrick/godirwalk v1.16.1 h1:DynhcF+bztK8gooS0+NDJFrdNZjJ3gzVzC545UNA9iw= @@ -388,6 +410,7 @@ github.com/lib/pq v1.10.6 h1:jbk+ZieJ0D7EVGJYpL9QTz7/YW6UHbmdnZWYyK5cdBs= github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= +github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= @@ -468,6 +491,9 @@ github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4AN 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/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo/v2 v2.9.4 h1:xR7vG4IXt5RWx6FfIjyAtsoMAtnc3C/rFXBBd2AjZwE= @@ -520,12 +546,14 @@ github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6po github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rubenv/sql-migrate v1.1.1 h1:haR5Hn8hbW9/SpAICrXoZqXnywS7Q5WijwkQENPeNWY= github.com/rubenv/sql-migrate v1.1.1/go.mod h1:/7TZymwxN8VWumcIxw1jjHEcR1djpdkMHQPT4FWdnbQ= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= +github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= @@ -534,6 +562,7 @@ github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= @@ -565,12 +594,14 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xlab/treeprint v1.1.0 h1:G/1DjNkPpfZCFt9CSh6b5/nY4VimlbHF3Rh4obvtzDk= github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -584,6 +615,7 @@ github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50 h1:hlE8//ciYMzt github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f h1:ERexzlUfuTvpE74urLSbIQW0Z/6hF9t8U4NsJLaioAY= github.com/ziutek/mymysql v1.5.4 h1:GB0qdRGsTwQSBVYuVShFBKaXSnSnYYC2d9knnE1LHFs= github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0= +go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= @@ -982,6 +1014,7 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -997,6 +1030,7 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= +gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= helm.sh/helm/v3 v3.9.4 h1:TCI1QhJUeLVOdccfdw+vnSEO3Td6gNqibptB04QtExY= helm.sh/helm/v3 v3.9.4/go.mod h1:3eaWAIqzvlRSD06gR9MMwmp2KBKwlu9av1/1BZpjeWY= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/pkg/config/builder.go b/pkg/config/builder.go new file mode 100644 index 0000000..a13536e --- /dev/null +++ b/pkg/config/builder.go @@ -0,0 +1,212 @@ +package config + +import ( + "context" + "encoding/json" + "net" + "os" + "path/filepath" + "strconv" + + "github.com/adutra/goalesce" + "gopkg.in/yaml.v3" +) + +/* + - Need to find the original Cassandra / DSE configuration (the path) in our images + - Merge given input with what we have there as a default + + - Merge certain keys to different files (only cassandra-yaml -> yamls) + - Rack information, cluster information etc + - Was there some other information we might want here? + - Merge JSON & YAML? +*/ + +/* + For NodeInfo struct, these are set by the cass-operator. + // TODO We did add some more also, add support for them? + // TODO Also, RACK_NAME and others could be moved to a JSON key which cass-operator could create.. + // TODO Do we need PRODUCT_VERSION for anything anymore? + + {:pod-ip (System/getenv "POD_IP") + :config-file-data (System/getenv "CONFIG_FILE_DATA") + :product-version (System/getenv "PRODUCT_VERSION") + :rack-name (System/getenv "RACK_NAME") + :product-name (or (System/getenv "PRODUCT_NAME") "dse") + :use-host-ip-for-broadcast (or (System/getenv "USE_HOST_IP_FOR_BROADCAST") "false") + :host-ip (System/getenv "HOST_IP") + + // TODO Could we also refactor the POD_IP / HOST_IP processing? Why can't the decision happen in cass-operator? +*/ + +func Build(ctx context.Context) error { + // Parse input from cass-operator + configInput, err := parseConfigInput() + if err != nil { + return err + } + + nodeInfo, err := parseNodeInfo() + if err != nil { + return err + } + + // Create rack information + if err := createRackProperties(configInput, nodeInfo, outputConfigFileDir()); err != nil { + return err + } + + // Create cassandra-env.sh + if err := createCassandraEnv(configInput, outputConfigFileDir()); err != nil { + return err + } + + // Create jvm*-server.options + if err := createJVMOptions(configInput, outputConfigFileDir()); err != nil { + return err + } + + // Create cassandra.yaml + if err := createCassandraYaml(configInput, nodeInfo, defaultConfigFileDir(), outputConfigFileDir()); err != nil { + return err + } + + return nil +} + +// Refactor to methods to saner names and files.. + +func parseConfigInput() (*ConfigInput, error) { + configInputStr := os.Getenv("CONFIG_FILE_DATA") + configInput := &ConfigInput{} + if err := json.Unmarshal([]byte(configInputStr), configInput); err != nil { + return nil, err + } + + return configInput, nil +} + +func parseNodeInfo() (*NodeInfo, error) { + rackName := os.Getenv("RACK_NAME") + + n := &NodeInfo{ + Rack: rackName, + } + + podIp := os.Getenv("POD_IP") + + useHostIp := false + useHostIpStr := os.Getenv("USE_HOST_IP_FOR_BROADCAST") + if useHostIpStr != "" { + var err error + useHostIp, err = strconv.ParseBool(useHostIpStr) + if err != nil { + return nil, err + } + } + + if useHostIp { + podIp = os.Getenv("HOST_IP") + } + + if ip := net.ParseIP(podIp); ip != nil { + n.IP = ip + } + + return n, nil +} + +// findConfigFiles returns the path of config files in the cass-management-api (for Cassandra 4.1.x and up) +func defaultConfigFileDir() string { + // $CASSANDRA_CONF could modify this, but we override it in the mgmt-api + return "/opt/cassandra/conf" +} + +func outputConfigFileDir() string { + // docker-entrypoint.sh will copy the files from here, so we need all the outputs to target this + return "/configs" +} + +func createRackProperties(configInput *ConfigInput, nodeInfo *NodeInfo, targetDir string) error { + // Write cassandra-rackdc.properties file with Datacenter and Rack information + + // Load the current file + + // Set dc to DatacenterInfo.Name + // Set rack to NodeInfo.Rack + return nil +} + +func createCassandraEnv(configInput *ConfigInput, targetDir string) error { + // Modify cassandra-env.sh if it's in the jvm-options / jvm-server-options / additional-jvm-options? + // This probably needs a template that is used to ensure backwards compatibility + return nil +} + +func createJVMOptions(configInput *ConfigInput, targetDir string) error { + return nil +} + +// cassandra.yaml related functions + +func createCassandraYaml(configInput *ConfigInput, nodeInfo *NodeInfo, sourceDir, targetDir string) error { + // Read the base file + yamlPath := filepath.Join(sourceDir, "cassandra.yaml") + + yamlFile, err := os.ReadFile(yamlPath) + if err != nil { + return err + } + + // Unmarshal, Marshal to remove all comments (and some fields if necessary) + cassandraYaml := make(map[string]interface{}) + + if err := yaml.Unmarshal(yamlFile, cassandraYaml); err != nil { + return err + } + + // Merge with the ConfigInput's cassadraYaml changes - configInput.CassYaml changes have to take priority + merged, err := goalesce.DeepMerge(cassandraYaml, configInput.CassYaml) + if err != nil { + return err + } + + // Take the NodeInfo information and add those modifications to the merge output (a priority) + // Take the mandatory changes we require and merge them (a priority again) + merged = k8ssandraOverrides(merged, configInput, nodeInfo) + + // Write to the targetDir the new modified file + targetFile := filepath.Join(targetDir, "cassandra.yaml") + return writeYaml(merged, targetFile) +} + +func k8ssandraOverrides(merged map[string]interface{}, configInput *ConfigInput, nodeInfo *NodeInfo) map[string]interface{} { + // Add fields which we require and their values, these should override whatever user sets + merged["seed_provider"] = []map[string]interface{}{ + { + "class_name": "org.apache.cassandra.locator.K8SeedProvider", + "parameters": []map[string]interface{}{ + { + "seeds": configInput.ClusterInfo.Seeds, + }, + }, + }, + } + + listenIP := nodeInfo.IP.String() + merged["listen_address"] = listenIP + merged["rpc_address"] = listenIP + delete(merged, "broadcast_address") // Sets it to the same as listen_address + delete(merged, "rpc_broadcast_address") // Sets it to the same as rpc_address + + return merged +} + +func writeYaml(doc map[string]interface{}, targetFile string) error { + b, err := yaml.Marshal(doc) + if err != nil { + return err + } + + return os.WriteFile(targetFile, b, 0) // TODO Fix Perm +} diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go new file mode 100644 index 0000000..a9e5ed5 --- /dev/null +++ b/pkg/config/builder_test.go @@ -0,0 +1,106 @@ +package config + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/k8ssandra/k8ssandra-client/internal/envtest" + "github.com/stretchr/testify/require" +) + +var existingConfig = ` +{ + "cassandra-env-sh": { + "additional-jvm-opts": [ + "-Dcassandra.system_distributed_replication=test-dc:1", + "-Dcom.sun.management.jmxremote.authenticate=true" + ] + }, + "cassandra-yaml": { + "authenticator": "PasswordAuthenticator", + "authorizer": "CassandraAuthorizer", + "num_tokens": 256, + "role_manager": "CassandraRoleManager", + "start_rpc": false + }, + "cluster-info": { + "name": "test", + "seeds": "test-seed-service,test-dc-additional-seed-service" + }, + "datacenter-info": { + "graph-enabled": 0, + "name": "dc1", + "solr-enabled": 0, + "spark-enabled": 0 + } +} +` + +func TestConfigInfoParsing(t *testing.T) { + require := require.New(t) + t.Setenv("CONFIG_FILE_DATA", existingConfig) + configInput, err := parseConfigInput() + require.NoError(err) + require.NotNil(configInput) + require.NotNil(configInput.CassYaml) + require.NotNil(configInput.ClusterInfo) + require.NotNil(configInput.DatacenterInfo) + + require.Equal("test", configInput.ClusterInfo.Name) + require.Equal("dc1", configInput.DatacenterInfo.Name) +} + +func TestParseNodeInfo(t *testing.T) { + require := require.New(t) + t.Setenv("POD_IP", "172.27.0.1") + t.Setenv("RACK_NAME", "r1") + nodeInfo, err := parseNodeInfo() + require.NoError(err) + require.NotNil(nodeInfo) + require.Equal("172.27.0.1", nodeInfo.IP.String()) + require.Equal("r1", nodeInfo.Rack) + + t.Setenv("HOST_IP", "10.0.0.1") + nodeInfo, err = parseNodeInfo() + require.NoError(err) + require.NotNil(nodeInfo) + require.Equal("172.27.0.1", nodeInfo.IP.String()) + + t.Setenv("USE_HOST_IP_FOR_BROADCAST", "false") + nodeInfo, err = parseNodeInfo() + require.NoError(err) + require.NotNil(nodeInfo) + require.Equal("172.27.0.1", nodeInfo.IP.String()) + + t.Setenv("USE_HOST_IP_FOR_BROADCAST", "true") + nodeInfo, err = parseNodeInfo() + require.NoError(err) + require.NotNil(nodeInfo) + require.Equal("10.0.0.1", nodeInfo.IP.String()) +} + +func TestCassandraYamlWriting(t *testing.T) { + require := require.New(t) + cassYamlDir := filepath.Join(envtest.RootDir(), "testfiles", "4.1") + tempDir, err := os.MkdirTemp("", "client-test") + + fmt.Printf("tempDir: %s\n", tempDir) + require.NoError(err) + + // Create mandatory configs.. + t.Setenv("CONFIG_FILE_DATA", existingConfig) + configInput, err := parseConfigInput() + require.NoError(err) + require.NotNil(configInput) + t.Setenv("POD_IP", "172.27.0.1") + t.Setenv("RACK_NAME", "r1") + nodeInfo, err := parseNodeInfo() + require.NoError(err) + require.NotNil(nodeInfo) + + require.NoError(createCassandraYaml(configInput, nodeInfo, cassYamlDir, tempDir)) + + // TODO Read back and verify all our changes are there +} diff --git a/pkg/config/types.go b/pkg/config/types.go new file mode 100644 index 0000000..4f26151 --- /dev/null +++ b/pkg/config/types.go @@ -0,0 +1,57 @@ +package config + +import "net" + +/* + (defrecord ClusterInfo [name seeds]) + (defrecord DatacenterInfo [name + graph-enabled + solr-enabled + spark-enabled]) + ;; Note, we are using the current _address field names as of DSE 6.0. + ;; Namely native_transport_address and native_transport_rpc_address. + ;; Clients should not be passing in the old names. + (defrecord NodeInfo [name + rack + listen_address + broadcast_address + native_transport_address + native_transport_broadcast_address + initial_token + auto_bootstrap + agent_version + configured-paths + facts]) +*/ + +// From cass-operator JSON input + +type ConfigInput struct { + ClusterInfo ClusterInfo `json:"cluster-info"` + DatacenterInfo DatacenterInfo `json:"datacenter-info"` + CassYaml map[string]interface{} `json:"cassandra-yaml,omitempty"` + + // jvm-options parts.. +} + +type ClusterInfo struct { + Name string `json:"name"` + Seeds string `json:"seeds"` // comma separated list of seeds +} + +type DatacenterInfo struct { + Name string `json:"name"` + + // These are ignored for now + // "graph-enabled": graphEnabled, + // "solr-enabled": solrEnabled, + // "spark-enabled": sparkEnabled, +} + +// Built from other sources + +type NodeInfo struct { + Name string + Rack string + IP net.IP +} diff --git a/testfiles/4.1/cassandra.yaml b/testfiles/4.1/cassandra.yaml new file mode 100644 index 0000000..4b2711c --- /dev/null +++ b/testfiles/4.1/cassandra.yaml @@ -0,0 +1,1819 @@ + +# Cassandra storage config YAML + +# NOTE: +# See https://cassandra.apache.org/doc/latest/configuration/ for +# full explanations of configuration directives +# /NOTE + +# The name of the cluster. This is mainly used to prevent machines in +# one logical cluster from joining another. +cluster_name: 'Test Cluster' + +# This defines the number of tokens randomly assigned to this node on the ring +# The more tokens, relative to other nodes, the larger the proportion of data +# that this node will store. You probably want all nodes to have the same number +# of tokens assuming they have equal hardware capability. +# +# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility, +# and will use the initial_token as described below. +# +# Specifying initial_token will override this setting on the node's initial start, +# on subsequent starts, this setting will apply even if initial token is set. +# +# See https://cassandra.apache.org/doc/latest/getting_started/production.html#tokens for +# best practice information about num_tokens. +# +num_tokens: 16 + +# Triggers automatic allocation of num_tokens tokens for this node. The allocation +# algorithm attempts to choose tokens in a way that optimizes replicated load over +# the nodes in the datacenter for the replica factor. +# +# The load assigned to each node will be close to proportional to its number of +# vnodes. +# +# Only supported with the Murmur3Partitioner. + +# Replica factor is determined via the replication strategy used by the specified +# keyspace. +# allocate_tokens_for_keyspace: KEYSPACE + +# Replica factor is explicitly set, regardless of keyspace or datacenter. +# This is the replica factor within the datacenter, like NTS. +allocate_tokens_for_local_replication_factor: 3 + +# initial_token allows you to specify tokens manually. While you can use it with +# vnodes (num_tokens > 1, above) -- in which case you should provide a +# comma-separated list -- it's primarily used when adding nodes to legacy clusters +# that do not have vnodes enabled. +# initial_token: + +# May either be "true" or "false" to enable globally +hinted_handoff_enabled: true + +# When hinted_handoff_enabled is true, a black list of data centers that will not +# perform hinted handoff +# hinted_handoff_disabled_datacenters: +# - DC1 +# - DC2 + +# this defines the maximum amount of time a dead host will have hints +# generated. After it has been dead this long, new hints for it will not be +# created until it has been seen alive and gone down again. +# Min unit: ms +max_hint_window: 3h + +# Maximum throttle in KiBs per second, per delivery thread. This will be +# reduced proportionally to the number of nodes in the cluster. (If there +# are two nodes in the cluster, each delivery thread will use the maximum +# rate; if there are three, each will throttle to half of the maximum, +# since we expect two nodes to be delivering hints simultaneously.) +# Min unit: KiB +hinted_handoff_throttle: 1024KiB + +# Number of threads with which to deliver hints; +# Consider increasing this number when you have multi-dc deployments, since +# cross-dc handoff tends to be slower +max_hints_delivery_threads: 2 + +# Directory where Cassandra should store hints. +# If not set, the default directory is $CASSANDRA_HOME/data/hints. +# hints_directory: /var/lib/cassandra/hints + +# How often hints should be flushed from the internal buffers to disk. +# Will *not* trigger fsync. +# Min unit: ms +hints_flush_period: 10000ms + +# Maximum size for a single hints file, in mebibytes. +# Min unit: MiB +max_hints_file_size: 128MiB + +# The file size limit to store hints for an unreachable host, in mebibytes. +# Once the local hints files have reached the limit, no more new hints will be created. +# Set a non-positive value will disable the size limit. +# max_hints_size_per_host: 0MiB + +# Enable / disable automatic cleanup for the expired and orphaned hints file. +# Disable the option in order to preserve those hints on the disk. +auto_hints_cleanup_enabled: false + +# Compression to apply to the hint files. If omitted, hints files +# will be written uncompressed. LZ4, Snappy, and Deflate compressors +# are supported. +#hints_compression: +# - class_name: LZ4Compressor +# parameters: +# - + +# Enable / disable persistent hint windows. +# +# If set to false, a hint will be stored only in case a respective node +# that hint is for is down less than or equal to max_hint_window. +# +# If set to true, a hint will be stored in case there is not any +# hint which was stored earlier than max_hint_window. This is for cases +# when a node keeps to restart and hints are not delivered yet, we would be saving +# hints for that node indefinitely. +# +# Defaults to true. +# +# hint_window_persistent_enabled: true + +# Maximum throttle in KiBs per second, total. This will be +# reduced proportionally to the number of nodes in the cluster. +# Min unit: KiB +batchlog_replay_throttle: 1024KiB + +# Authentication backend, implementing IAuthenticator; used to identify users +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator, +# PasswordAuthenticator}. +# +# - AllowAllAuthenticator performs no checks - set it to disable authentication. +# - PasswordAuthenticator relies on username/password pairs to authenticate +# users. It keeps usernames and hashed passwords in system_auth.roles table. +# Please increase system_auth keyspace replication factor if you use this authenticator. +# If using PasswordAuthenticator, CassandraRoleManager must also be used (see below) +authenticator: AllowAllAuthenticator + +# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer, +# CassandraAuthorizer}. +# +# - AllowAllAuthorizer allows any action to any user - set it to disable authorization. +# - CassandraAuthorizer stores permissions in system_auth.role_permissions table. Please +# increase system_auth keyspace replication factor if you use this authorizer. +authorizer: AllowAllAuthorizer + +# Part of the Authentication & Authorization backend, implementing IRoleManager; used +# to maintain grants and memberships between roles. +# Out of the box, Cassandra provides org.apache.cassandra.auth.CassandraRoleManager, +# which stores role information in the system_auth keyspace. Most functions of the +# IRoleManager require an authenticated login, so unless the configured IAuthenticator +# actually implements authentication, most of this functionality will be unavailable. +# +# - CassandraRoleManager stores role data in the system_auth keyspace. Please +# increase system_auth keyspace replication factor if you use this role manager. +role_manager: CassandraRoleManager + +# Network authorization backend, implementing INetworkAuthorizer; used to restrict user +# access to certain DCs +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllNetworkAuthorizer, +# CassandraNetworkAuthorizer}. +# +# - AllowAllNetworkAuthorizer allows access to any DC to any user - set it to disable authorization. +# - CassandraNetworkAuthorizer stores permissions in system_auth.network_permissions table. Please +# increase system_auth keyspace replication factor if you use this authorizer. +network_authorizer: AllowAllNetworkAuthorizer + +# Depending on the auth strategy of the cluster, it can be beneficial to iterate +# from root to table (root -> ks -> table) instead of table to root (table -> ks -> root). +# As the auth entries are whitelisting, once a permission is found you know it to be +# valid. We default to false as the legacy behavior is to query at the table level then +# move back up to the root. See CASSANDRA-17016 for details. +# traverse_auth_from_root: false + +# Validity period for roles cache (fetching granted roles can be an expensive +# operation depending on the role manager, CassandraRoleManager is one example) +# Granted roles are cached for authenticated sessions in AuthenticatedUser and +# after the period specified here, become eligible for (async) reload. +# Defaults to 2000, set to 0 to disable caching entirely. +# Will be disabled automatically for AllowAllAuthenticator. +# For a long-running cache using roles_cache_active_update, consider +# setting to something longer such as a daily validation: 86400000 +# Min unit: ms +roles_validity: 2000ms + +# Refresh interval for roles cache (if enabled). +# After this interval, cache entries become eligible for refresh. Upon next +# access, an async reload is scheduled and the old value returned until it +# completes. If roles_validity is non-zero, then this must be +# also. +# This setting is also used to inform the interval of auto-updating if +# using roles_cache_active_update. +# Defaults to the same value as roles_validity. +# For a long-running cache, consider setting this to 60000 (1 hour) etc. +# Min unit: ms +# roles_update_interval: 2000ms + +# If true, cache contents are actively updated by a background task at the +# interval set by roles_update_interval. If false, cache entries +# become eligible for refresh after their update interval. Upon next access, +# an async reload is scheduled and the old value returned until it completes. +# roles_cache_active_update: false + +# Validity period for permissions cache (fetching permissions can be an +# expensive operation depending on the authorizer, CassandraAuthorizer is +# one example). Defaults to 2000, set to 0 to disable. +# Will be disabled automatically for AllowAllAuthorizer. +# For a long-running cache using permissions_cache_active_update, consider +# setting to something longer such as a daily validation: 86400000ms +# Min unit: ms +permissions_validity: 2000ms + +# Refresh interval for permissions cache (if enabled). +# After this interval, cache entries become eligible for refresh. Upon next +# access, an async reload is scheduled and the old value returned until it +# completes. If permissions_validity is non-zero, then this must be +# also. +# This setting is also used to inform the interval of auto-updating if +# using permissions_cache_active_update. +# Defaults to the same value as permissions_validity. +# For a longer-running permissions cache, consider setting to update hourly (60000) +# Min unit: ms +# permissions_update_interval: 2000ms + +# If true, cache contents are actively updated by a background task at the +# interval set by permissions_update_interval. If false, cache entries +# become eligible for refresh after their update interval. Upon next access, +# an async reload is scheduled and the old value returned until it completes. +# permissions_cache_active_update: false + +# Validity period for credentials cache. This cache is tightly coupled to +# the provided PasswordAuthenticator implementation of IAuthenticator. If +# another IAuthenticator implementation is configured, this cache will not +# be automatically used and so the following settings will have no effect. +# Please note, credentials are cached in their encrypted form, so while +# activating this cache may reduce the number of queries made to the +# underlying table, it may not bring a significant reduction in the +# latency of individual authentication attempts. +# Defaults to 2000, set to 0 to disable credentials caching. +# For a long-running cache using credentials_cache_active_update, consider +# setting to something longer such as a daily validation: 86400000 +# Min unit: ms +credentials_validity: 2000ms + +# Refresh interval for credentials cache (if enabled). +# After this interval, cache entries become eligible for refresh. Upon next +# access, an async reload is scheduled and the old value returned until it +# completes. If credentials_validity is non-zero, then this must be +# also. +# This setting is also used to inform the interval of auto-updating if +# using credentials_cache_active_update. +# Defaults to the same value as credentials_validity. +# For a longer-running permissions cache, consider setting to update hourly (60000) +# Min unit: ms +# credentials_update_interval: 2000ms + +# If true, cache contents are actively updated by a background task at the +# interval set by credentials_update_interval. If false (default), cache entries +# become eligible for refresh after their update interval. Upon next access, +# an async reload is scheduled and the old value returned until it completes. +# credentials_cache_active_update: false + +# The partitioner is responsible for distributing groups of rows (by +# partition key) across nodes in the cluster. The partitioner can NOT be +# changed without reloading all data. If you are adding nodes or upgrading, +# you should set this to the same partitioner that you are currently using. +# +# The default partitioner is the Murmur3Partitioner. Older partitioners +# such as the RandomPartitioner, ByteOrderedPartitioner, and +# OrderPreservingPartitioner have been included for backward compatibility only. +# For new clusters, you should NOT change this value. +# +partitioner: org.apache.cassandra.dht.Murmur3Partitioner + +# Directories where Cassandra should store data on disk. If multiple +# directories are specified, Cassandra will spread data evenly across +# them by partitioning the token ranges. +# If not set, the default directory is $CASSANDRA_HOME/data/data. +# data_file_directories: +# - /var/lib/cassandra/data + +# Directory were Cassandra should store the data of the local system keyspaces. +# By default Cassandra will store the data of the local system keyspaces in the first of the data directories specified +# by data_file_directories. +# This approach ensures that if one of the other disks is lost Cassandra can continue to operate. For extra security +# this setting allows to store those data on a different directory that provides redundancy. +# local_system_data_file_directory: + +# commit log. when running on magnetic HDD, this should be a +# separate spindle than the data directories. +# If not set, the default directory is $CASSANDRA_HOME/data/commitlog. +# commitlog_directory: /var/lib/cassandra/commitlog + +# Enable / disable CDC functionality on a per-node basis. This modifies the logic used +# for write path allocation rejection (standard: never reject. cdc: reject Mutation +# containing a CDC-enabled table if at space limit in cdc_raw_directory). +cdc_enabled: false + +# CommitLogSegments are moved to this directory on flush if cdc_enabled: true and the +# segment contains mutations for a CDC-enabled table. This should be placed on a +# separate spindle than the data directories. If not set, the default directory is +# $CASSANDRA_HOME/data/cdc_raw. +# cdc_raw_directory: /var/lib/cassandra/cdc_raw + +# Policy for data disk failures: +# +# die +# shut down gossip and client transports and kill the JVM for any fs errors or +# single-sstable errors, so the node can be replaced. +# +# stop_paranoid +# shut down gossip and client transports even for single-sstable errors, +# kill the JVM for errors during startup. +# +# stop +# shut down gossip and client transports, leaving the node effectively dead, but +# can still be inspected via JMX, kill the JVM for errors during startup. +# +# best_effort +# stop using the failed disk and respond to requests based on +# remaining available sstables. This means you WILL see obsolete +# data at CL.ONE! +# +# ignore +# ignore fatal errors and let requests fail, as in pre-1.2 Cassandra +disk_failure_policy: stop + +# Policy for commit disk failures: +# +# die +# shut down the node and kill the JVM, so the node can be replaced. +# +# stop +# shut down the node, leaving the node effectively dead, but +# can still be inspected via JMX. +# +# stop_commit +# shutdown the commit log, letting writes collect but +# continuing to service reads, as in pre-2.0.5 Cassandra +# +# ignore +# ignore fatal errors and let the batches fail +commit_failure_policy: stop + +# Maximum size of the native protocol prepared statement cache +# +# Valid values are either "auto" (omitting the value) or a value greater 0. +# +# Note that specifying a too large value will result in long running GCs and possbily +# out-of-memory errors. Keep the value at a small fraction of the heap. +# +# If you constantly see "prepared statements discarded in the last minute because +# cache limit reached" messages, the first step is to investigate the root cause +# of these messages and check whether prepared statements are used correctly - +# i.e. use bind markers for variable parts. +# +# Do only change the default value, if you really have more prepared statements than +# fit in the cache. In most cases it is not neccessary to change this value. +# Constantly re-preparing statements is a performance penalty. +# +# Default value ("auto") is 1/256th of the heap or 10MiB, whichever is greater +# Min unit: MiB +prepared_statements_cache_size: + +# Maximum size of the key cache in memory. +# +# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the +# minimum, sometimes more. The key cache is fairly tiny for the amount of +# time it saves, so it's worthwhile to use it at large numbers. +# The row cache saves even more time, but must contain the entire row, +# so it is extremely space-intensive. It's best to only use the +# row cache if you have hot rows or static rows. +# +# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup. +# +# Default value is empty to make it "auto" (min(5% of Heap (in MiB), 100MiB)). Set to 0 to disable key cache. +# Min unit: MiB +key_cache_size: + +# Duration in seconds after which Cassandra should +# save the key cache. Caches are saved to saved_caches_directory as +# specified in this configuration file. +# +# Saved caches greatly improve cold-start speeds, and is relatively cheap in +# terms of I/O for the key cache. Row cache saving is much more expensive and +# has limited use. +# +# Default is 14400 or 4 hours. +# Min unit: s +key_cache_save_period: 4h + +# Number of keys from the key cache to save +# Disabled by default, meaning all keys are going to be saved +# key_cache_keys_to_save: 100 + +# Row cache implementation class name. Available implementations: +# +# org.apache.cassandra.cache.OHCProvider +# Fully off-heap row cache implementation (default). +# +# org.apache.cassandra.cache.SerializingCacheProvider +# This is the row cache implementation availabile +# in previous releases of Cassandra. +# row_cache_class_name: org.apache.cassandra.cache.OHCProvider + +# Maximum size of the row cache in memory. +# Please note that OHC cache implementation requires some additional off-heap memory to manage +# the map structures and some in-flight memory during operations before/after cache entries can be +# accounted against the cache capacity. This overhead is usually small compared to the whole capacity. +# Do not specify more memory that the system can afford in the worst usual situation and leave some +# headroom for OS block level cache. Do never allow your system to swap. +# +# Default value is 0, to disable row caching. +# Min unit: MiB +row_cache_size: 0MiB + +# Duration in seconds after which Cassandra should save the row cache. +# Caches are saved to saved_caches_directory as specified in this configuration file. +# +# Saved caches greatly improve cold-start speeds, and is relatively cheap in +# terms of I/O for the key cache. Row cache saving is much more expensive and +# has limited use. +# +# Default is 0 to disable saving the row cache. +# Min unit: s +row_cache_save_period: 0s + +# Number of keys from the row cache to save. +# Specify 0 (which is the default), meaning all keys are going to be saved +# row_cache_keys_to_save: 100 + +# Maximum size of the counter cache in memory. +# +# Counter cache helps to reduce counter locks' contention for hot counter cells. +# In case of RF = 1 a counter cache hit will cause Cassandra to skip the read before +# write entirely. With RF > 1 a counter cache hit will still help to reduce the duration +# of the lock hold, helping with hot counter cell updates, but will not allow skipping +# the read entirely. Only the local (clock, count) tuple of a counter cell is kept +# in memory, not the whole counter, so it's relatively cheap. +# +# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup. +# +# Default value is empty to make it "auto" (min(2.5% of Heap (in MiB), 50MiB)). Set to 0 to disable counter cache. +# NOTE: if you perform counter deletes and rely on low gcgs, you should disable the counter cache. +# Min unit: MiB +counter_cache_size: + +# Duration in seconds after which Cassandra should +# save the counter cache (keys only). Caches are saved to saved_caches_directory as +# specified in this configuration file. +# +# Default is 7200 or 2 hours. +# Min unit: s +counter_cache_save_period: 7200s + +# Number of keys from the counter cache to save +# Disabled by default, meaning all keys are going to be saved +# counter_cache_keys_to_save: 100 + +# saved caches +# If not set, the default directory is $CASSANDRA_HOME/data/saved_caches. +# saved_caches_directory: /var/lib/cassandra/saved_caches + +# Number of seconds the server will wait for each cache (row, key, etc ...) to load while starting +# the Cassandra process. Setting this to zero is equivalent to disabling all cache loading on startup +# while still having the cache during runtime. +# Min unit: s +# cache_load_timeout: 30s + +# commitlog_sync may be either "periodic", "group", or "batch." +# +# When in batch mode, Cassandra won't ack writes until the commit log +# has been flushed to disk. Each incoming write will trigger the flush task. +# commitlog_sync_batch_window_in_ms is a deprecated value. Previously it had +# almost no value, and is being removed. +# +# commitlog_sync_batch_window_in_ms: 2 +# +# group mode is similar to batch mode, where Cassandra will not ack writes +# until the commit log has been flushed to disk. The difference is group +# mode will wait up to commitlog_sync_group_window between flushes. +# +# Min unit: ms +# commitlog_sync_group_window: 1000ms +# +# the default option is "periodic" where writes may be acked immediately +# and the CommitLog is simply synced every commitlog_sync_period +# milliseconds. +commitlog_sync: periodic +# Min unit: ms +commitlog_sync_period: 10000ms + +# When in periodic commitlog mode, the number of milliseconds to block writes +# while waiting for a slow disk flush to complete. +# Min unit: ms +# periodic_commitlog_sync_lag_block: + +# The size of the individual commitlog file segments. A commitlog +# segment may be archived, deleted, or recycled once all the data +# in it (potentially from each columnfamily in the system) has been +# flushed to sstables. +# +# The default size is 32, which is almost always fine, but if you are +# archiving commitlog segments (see commitlog_archiving.properties), +# then you probably want a finer granularity of archiving; 8 or 16 MB +# is reasonable. +# Max mutation size is also configurable via max_mutation_size setting in +# cassandra.yaml. The default is half the size commitlog_segment_size in bytes. +# This should be positive and less than 2048. +# +# NOTE: If max_mutation_size is set explicitly then commitlog_segment_size must +# be set to at least twice the size of max_mutation_size +# +# Min unit: MiB +commitlog_segment_size: 32MiB + +# Compression to apply to the commit log. If omitted, the commit log +# will be written uncompressed. LZ4, Snappy, and Deflate compressors +# are supported. +# commitlog_compression: +# - class_name: LZ4Compressor +# parameters: +# - + +# Compression to apply to SSTables as they flush for compressed tables. +# Note that tables without compression enabled do not respect this flag. +# +# As high ratio compressors like LZ4HC, Zstd, and Deflate can potentially +# block flushes for too long, the default is to flush with a known fast +# compressor in those cases. Options are: +# +# none : Flush without compressing blocks but while still doing checksums. +# fast : Flush with a fast compressor. If the table is already using a +# fast compressor that compressor is used. +# table: Always flush with the same compressor that the table uses. This +# was the pre 4.0 behavior. +# +# flush_compression: fast + +# any class that implements the SeedProvider interface and has a +# constructor that takes a Map of parameters will do. +seed_provider: + # Addresses of hosts that are deemed contact points. + # Cassandra nodes use this list of hosts to find each other and learn + # the topology of the ring. You must change this if you are running + # multiple nodes! + - class_name: org.apache.cassandra.locator.SimpleSeedProvider + parameters: + # seeds is actually a comma-delimited list of addresses. + # Ex: ",," + - seeds: "127.0.0.1:7000" + +# For workloads with more data than can fit in memory, Cassandra's +# bottleneck will be reads that need to fetch data from +# disk. "concurrent_reads" should be set to (16 * number_of_drives) in +# order to allow the operations to enqueue low enough in the stack +# that the OS and drives can reorder them. Same applies to +# "concurrent_counter_writes", since counter writes read the current +# values before incrementing and writing them back. +# +# On the other hand, since writes are almost never IO bound, the ideal +# number of "concurrent_writes" is dependent on the number of cores in +# your system; (8 * number_of_cores) is a good rule of thumb. +concurrent_reads: 32 +concurrent_writes: 32 +concurrent_counter_writes: 32 + +# For materialized view writes, as there is a read involved, so this should +# be limited by the less of concurrent reads or concurrent writes. +concurrent_materialized_view_writes: 32 + +# Maximum memory to use for inter-node and client-server networking buffers. +# +# Defaults to the smaller of 1/16 of heap or 128MB. This pool is allocated off-heap, +# so is in addition to the memory allocated for heap. The cache also has on-heap +# overhead which is roughly 128 bytes per chunk (i.e. 0.2% of the reserved size +# if the default 64k chunk size is used). +# Memory is only allocated when needed. +# Min unit: MiB +# networking_cache_size: 128MiB + +# Enable the sstable chunk cache. The chunk cache will store recently accessed +# sections of the sstable in-memory as uncompressed buffers. +# file_cache_enabled: false + +# Maximum memory to use for sstable chunk cache and buffer pooling. +# 32MB of this are reserved for pooling buffers, the rest is used for chunk cache +# that holds uncompressed sstable chunks. +# Defaults to the smaller of 1/4 of heap or 512MB. This pool is allocated off-heap, +# so is in addition to the memory allocated for heap. The cache also has on-heap +# overhead which is roughly 128 bytes per chunk (i.e. 0.2% of the reserved size +# if the default 64k chunk size is used). +# Memory is only allocated when needed. +# Min unit: MiB +# file_cache_size: 512MiB + +# Flag indicating whether to allocate on or off heap when the sstable buffer +# pool is exhausted, that is when it has exceeded the maximum memory +# file_cache_size, beyond which it will not cache buffers but allocate on request. + +# buffer_pool_use_heap_if_exhausted: true + +# The strategy for optimizing disk read +# Possible values are: +# ssd (for solid state disks, the default) +# spinning (for spinning disks) +# disk_optimization_strategy: ssd + +# Total permitted memory to use for memtables. Cassandra will stop +# accepting writes when the limit is exceeded until a flush completes, +# and will trigger a flush based on memtable_cleanup_threshold +# If omitted, Cassandra will set both to 1/4 the size of the heap. +# Min unit: MiB +# memtable_heap_space: 2048MiB +# Min unit: MiB +# memtable_offheap_space: 2048MiB + +# memtable_cleanup_threshold is deprecated. The default calculation +# is the only reasonable choice. See the comments on memtable_flush_writers +# for more information. +# +# Ratio of occupied non-flushing memtable size to total permitted size +# that will trigger a flush of the largest memtable. Larger mct will +# mean larger flushes and hence less compaction, but also less concurrent +# flush activity which can make it difficult to keep your disks fed +# under heavy write load. +# +# memtable_cleanup_threshold defaults to 1 / (memtable_flush_writers + 1) +# memtable_cleanup_threshold: 0.11 + +# Specify the way Cassandra allocates and manages memtable memory. +# Options are: +# +# heap_buffers +# on heap nio buffers +# +# offheap_buffers +# off heap (direct) nio buffers +# +# offheap_objects +# off heap objects +memtable_allocation_type: heap_buffers + +# Limit memory usage for Merkle tree calculations during repairs. The default +# is 1/16th of the available heap. The main tradeoff is that smaller trees +# have less resolution, which can lead to over-streaming data. If you see heap +# pressure during repairs, consider lowering this, but you cannot go below +# one mebibyte. If you see lots of over-streaming, consider raising +# this or using subrange repair. +# +# For more details see https://issues.apache.org/jira/browse/CASSANDRA-14096. +# +# Min unit: MiB +# repair_session_space: + +# Total space to use for commit logs on disk. +# +# If space gets above this value, Cassandra will flush every dirty CF +# in the oldest segment and remove it. So a small total commitlog space +# will tend to cause more flush activity on less-active columnfamilies. +# +# The default value is the smaller of 8192, and 1/4 of the total space +# of the commitlog volume. +# +# commitlog_total_space: 8192MiB + +# This sets the number of memtable flush writer threads per disk +# as well as the total number of memtables that can be flushed concurrently. +# These are generally a combination of compute and IO bound. +# +# Memtable flushing is more CPU efficient than memtable ingest and a single thread +# can keep up with the ingest rate of a whole server on a single fast disk +# until it temporarily becomes IO bound under contention typically with compaction. +# At that point you need multiple flush threads. At some point in the future +# it may become CPU bound all the time. +# +# You can tell if flushing is falling behind using the MemtablePool.BlockedOnAllocation +# metric which should be 0, but will be non-zero if threads are blocked waiting on flushing +# to free memory. +# +# memtable_flush_writers defaults to two for a single data directory. +# This means that two memtables can be flushed concurrently to the single data directory. +# If you have multiple data directories the default is one memtable flushing at a time +# but the flush will use a thread per data directory so you will get two or more writers. +# +# Two is generally enough to flush on a fast disk [array] mounted as a single data directory. +# Adding more flush writers will result in smaller more frequent flushes that introduce more +# compaction overhead. +# +# There is a direct tradeoff between number of memtables that can be flushed concurrently +# and flush size and frequency. More is not better you just need enough flush writers +# to never stall waiting for flushing to free memory. +# +# memtable_flush_writers: 2 + +# Total space to use for change-data-capture logs on disk. +# +# If space gets above this value, Cassandra will throw WriteTimeoutException +# on Mutations including tables with CDC enabled. A CDCCompactor is responsible +# for parsing the raw CDC logs and deleting them when parsing is completed. +# +# The default value is the min of 4096 MiB and 1/8th of the total space +# of the drive where cdc_raw_directory resides. +# Min unit: MiB +# cdc_total_space: 4096MiB + +# When we hit our cdc_raw limit and the CDCCompactor is either running behind +# or experiencing backpressure, we check at the following interval to see if any +# new space for cdc-tracked tables has been made available. Default to 250ms +# Min unit: ms +# cdc_free_space_check_interval: 250ms + +# A fixed memory pool size in MB for for SSTable index summaries. If left +# empty, this will default to 5% of the heap size. If the memory usage of +# all index summaries exceeds this limit, SSTables with low read rates will +# shrink their index summaries in order to meet this limit. However, this +# is a best-effort process. In extreme conditions Cassandra may need to use +# more than this amount of memory. +# Min unit: KiB +index_summary_capacity: + +# How frequently index summaries should be resampled. This is done +# periodically to redistribute memory from the fixed-size pool to sstables +# proportional their recent read rates. Setting to null value will disable this +# process, leaving existing index summaries at their current sampling level. +# Min unit: m +index_summary_resize_interval: 60m + +# Whether to, when doing sequential writing, fsync() at intervals in +# order to force the operating system to flush the dirty +# buffers. Enable this to avoid sudden dirty buffer flushing from +# impacting read latencies. Almost always a good idea on SSDs; not +# necessarily on platters. +trickle_fsync: false +# Min unit: KiB +trickle_fsync_interval: 10240KiB + +# TCP port, for commands and data +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +storage_port: 7000 + +# SSL port, for legacy encrypted communication. This property is unused unless enabled in +# server_encryption_options (see below). As of cassandra 4.0, this property is deprecated +# as a single port can be used for either/both secure and insecure connections. +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +ssl_storage_port: 7001 + +# Address or interface to bind to and tell other Cassandra nodes to connect to. +# You _must_ change this if you want multiple nodes to be able to communicate! +# +# Set listen_address OR listen_interface, not both. +# +# Leaving it blank leaves it up to InetAddress.getLocalHost(). This +# will always do the Right Thing _if_ the node is properly configured +# (hostname, name resolution, etc), and the Right Thing is to use the +# address associated with the hostname (it might not be). If unresolvable +# it will fall back to InetAddress.getLoopbackAddress(), which is wrong for production systems. +# +# Setting listen_address to 0.0.0.0 is always wrong. +# +listen_address: localhost + +# Set listen_address OR listen_interface, not both. Interfaces must correspond +# to a single address, IP aliasing is not supported. +# listen_interface: eth0 + +# If you choose to specify the interface by name and the interface has an ipv4 and an ipv6 address +# you can specify which should be chosen using listen_interface_prefer_ipv6. If false the first ipv4 +# address will be used. If true the first ipv6 address will be used. Defaults to false preferring +# ipv4. If there is only one address it will be selected regardless of ipv4/ipv6. +# listen_interface_prefer_ipv6: false + +# Address to broadcast to other Cassandra nodes +# Leaving this blank will set it to the same value as listen_address +# broadcast_address: 1.2.3.4 + +# When using multiple physical network interfaces, set this +# to true to listen on broadcast_address in addition to +# the listen_address, allowing nodes to communicate in both +# interfaces. +# Ignore this property if the network configuration automatically +# routes between the public and private networks such as EC2. +# listen_on_broadcast_address: false + +# Internode authentication backend, implementing IInternodeAuthenticator; +# used to allow/disallow connections from peer nodes. +# internode_authenticator: org.apache.cassandra.auth.AllowAllInternodeAuthenticator + +# Whether to start the native transport server. +# The address on which the native transport is bound is defined by rpc_address. +start_native_transport: true +# port for the CQL native transport to listen for clients on +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +native_transport_port: 9042 +# Enabling native transport encryption in client_encryption_options allows you to either use +# encryption for the standard port or to use a dedicated, additional port along with the unencrypted +# standard native_transport_port. +# Enabling client encryption and keeping native_transport_port_ssl disabled will use encryption +# for native_transport_port. Setting native_transport_port_ssl to a different value +# from native_transport_port will use encryption for native_transport_port_ssl while +# keeping native_transport_port unencrypted. +# native_transport_port_ssl: 9142 +# The maximum threads for handling requests (note that idle threads are stopped +# after 30 seconds so there is not corresponding minimum setting). +# native_transport_max_threads: 128 +# +# The maximum size of allowed frame. Frame (requests) larger than this will +# be rejected as invalid. The default is 16MiB. If you're changing this parameter, +# you may want to adjust max_value_size accordingly. This should be positive and less than 2048. +# Min unit: MiB +# native_transport_max_frame_size: 16MiB + +# The maximum number of concurrent client connections. +# The default is -1, which means unlimited. +# native_transport_max_concurrent_connections: -1 + +# The maximum number of concurrent client connections per source ip. +# The default is -1, which means unlimited. +# native_transport_max_concurrent_connections_per_ip: -1 + +# Controls whether Cassandra honors older, yet currently supported, protocol versions. +# The default is true, which means all supported protocols will be honored. +native_transport_allow_older_protocols: true + +# Controls when idle client connections are closed. Idle connections are ones that had neither reads +# nor writes for a time period. +# +# Clients may implement heartbeats by sending OPTIONS native protocol message after a timeout, which +# will reset idle timeout timer on the server side. To close idle client connections, corresponding +# values for heartbeat intervals have to be set on the client side. +# +# Idle connection timeouts are disabled by default. +# Min unit: ms +# native_transport_idle_timeout: 60000ms + +# When enabled, limits the number of native transport requests dispatched for processing per second. +# Behavior once the limit has been breached depends on the value of THROW_ON_OVERLOAD specified in +# the STARTUP message sent by the client during connection establishment. (See section "4.1.1. STARTUP" +# in "CQL BINARY PROTOCOL v5".) With the THROW_ON_OVERLOAD flag enabled, messages that breach the limit +# are dropped, and an OverloadedException is thrown for the client to handle. When the flag is not +# enabled, the server will stop consuming messages from the channel/socket, putting backpressure on +# the client while already dispatched messages are processed. +# native_transport_rate_limiting_enabled: false +# native_transport_max_requests_per_second: 1000000 + +# The address or interface to bind the native transport server to. +# +# Set rpc_address OR rpc_interface, not both. +# +# Leaving rpc_address blank has the same effect as on listen_address +# (i.e. it will be based on the configured hostname of the node). +# +# Note that unlike listen_address, you can specify 0.0.0.0, but you must also +# set broadcast_rpc_address to a value other than 0.0.0.0. +# +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +rpc_address: localhost + +# Set rpc_address OR rpc_interface, not both. Interfaces must correspond +# to a single address, IP aliasing is not supported. +# rpc_interface: eth1 + +# If you choose to specify the interface by name and the interface has an ipv4 and an ipv6 address +# you can specify which should be chosen using rpc_interface_prefer_ipv6. If false the first ipv4 +# address will be used. If true the first ipv6 address will be used. Defaults to false preferring +# ipv4. If there is only one address it will be selected regardless of ipv4/ipv6. +# rpc_interface_prefer_ipv6: false + +# RPC address to broadcast to drivers and other Cassandra nodes. This cannot +# be set to 0.0.0.0. If left blank, this will be set to the value of +# rpc_address. If rpc_address is set to 0.0.0.0, broadcast_rpc_address must +# be set. +# broadcast_rpc_address: 1.2.3.4 + +# enable or disable keepalive on rpc/native connections +rpc_keepalive: true + +# Uncomment to set socket buffer size for internode communication +# Note that when setting this, the buffer size is limited by net.core.wmem_max +# and when not setting it it is defined by net.ipv4.tcp_wmem +# See also: +# /proc/sys/net/core/wmem_max +# /proc/sys/net/core/rmem_max +# /proc/sys/net/ipv4/tcp_wmem +# /proc/sys/net/ipv4/tcp_wmem +# and 'man tcp' +# Min unit: B +# internode_socket_send_buffer_size: + +# Uncomment to set socket buffer size for internode communication +# Note that when setting this, the buffer size is limited by net.core.wmem_max +# and when not setting it it is defined by net.ipv4.tcp_wmem +# Min unit: B +# internode_socket_receive_buffer_size: + +# Set to true to have Cassandra create a hard link to each sstable +# flushed or streamed locally in a backups/ subdirectory of the +# keyspace data. Removing these links is the operator's +# responsibility. +incremental_backups: false + +# Whether or not to take a snapshot before each compaction. Be +# careful using this option, since Cassandra won't clean up the +# snapshots for you. Mostly useful if you're paranoid when there +# is a data format change. +snapshot_before_compaction: false + +# Whether or not a snapshot is taken of the data before keyspace truncation +# or dropping of column families. The STRONGLY advised default of true +# should be used to provide data safety. If you set this flag to false, you will +# lose data on truncation or drop. +auto_snapshot: true + +# Adds a time-to-live (TTL) to auto snapshots generated by table +# truncation or drop (when enabled). +# After the TTL is elapsed, the snapshot is automatically cleared. +# By default, auto snapshots *do not* have TTL, uncomment the property below +# to enable TTL on auto snapshots. +# Accepted units: d (days), h (hours) or m (minutes) +# auto_snapshot_ttl: 30d + +# The act of creating or clearing a snapshot involves creating or removing +# potentially tens of thousands of links, which can cause significant performance +# impact, especially on consumer grade SSDs. A non-zero value here can +# be used to throttle these links to avoid negative performance impact of +# taking and clearing snapshots +snapshot_links_per_second: 0 + +# Granularity of the collation index of rows within a partition. +# Increase if your rows are large, or if you have a very large +# number of rows per partition. The competing goals are these: +# +# - a smaller granularity means more index entries are generated +# and looking up rows withing the partition by collation column +# is faster +# - but, Cassandra will keep the collation index in memory for hot +# rows (as part of the key cache), so a larger granularity means +# you can cache more hot rows +# Min unit: KiB +column_index_size: 64KiB + +# Per sstable indexed key cache entries (the collation index in memory +# mentioned above) exceeding this size will not be held on heap. +# This means that only partition information is held on heap and the +# index entries are read from disk. +# +# Note that this size refers to the size of the +# serialized index information and not the size of the partition. +# Min unit: KiB +column_index_cache_size: 2KiB + +# Number of simultaneous compactions to allow, NOT including +# validation "compactions" for anti-entropy repair. Simultaneous +# compactions can help preserve read performance in a mixed read/write +# workload, by mitigating the tendency of small sstables to accumulate +# during a single long running compactions. The default is usually +# fine and if you experience problems with compaction running too +# slowly or too fast, you should look at +# compaction_throughput first. +# +# concurrent_compactors defaults to the smaller of (number of disks, +# number of cores), with a minimum of 2 and a maximum of 8. +# +# If your data directories are backed by SSD, you should increase this +# to the number of cores. +# concurrent_compactors: 1 + +# Number of simultaneous repair validations to allow. If not set or set to +# a value less than 1, it defaults to the value of concurrent_compactors. +# To set a value greeater than concurrent_compactors at startup, the system +# property cassandra.allow_unlimited_concurrent_validations must be set to +# true. To dynamically resize to a value > concurrent_compactors on a running +# node, first call the bypassConcurrentValidatorsLimit method on the +# org.apache.cassandra.db:type=StorageService mbean +# concurrent_validations: 0 + +# Number of simultaneous materialized view builder tasks to allow. +concurrent_materialized_view_builders: 1 + +# Throttles compaction to the given total throughput across the entire +# system. The faster you insert data, the faster you need to compact in +# order to keep the sstable count down, but in general, setting this to +# 16 to 32 times the rate you are inserting data is more than sufficient. +# Setting this to 0 disables throttling. Note that this accounts for all types +# of compaction, including validation compaction (building Merkle trees +# for repairs). +compaction_throughput: 64MiB/s + +# When compacting, the replacement sstable(s) can be opened before they +# are completely written, and used in place of the prior sstables for +# any range that has been written. This helps to smoothly transfer reads +# between the sstables, reducing page cache churn and keeping hot rows hot +# Set sstable_preemptive_open_interval to null for disabled which is equivalent to +# sstable_preemptive_open_interval_in_mb being negative +# Min unit: MiB +sstable_preemptive_open_interval: 50MiB + +# Starting from 4.1 sstables support UUID based generation identifiers. They are disabled by default +# because once enabled, there is no easy way to downgrade. When the node is restarted with this option +# set to true, each newly created sstable will have a UUID based generation identifier and such files are +# not readable by previous Cassandra versions. At some point, this option will become true by default +# and eventually get removed from the configuration. +uuid_sstable_identifiers_enabled: false + +# When enabled, permits Cassandra to zero-copy stream entire eligible +# SSTables between nodes, including every component. +# This speeds up the network transfer significantly subject to +# throttling specified by entire_sstable_stream_throughput_outbound, +# and entire_sstable_inter_dc_stream_throughput_outbound +# for inter-DC transfers. +# Enabling this will reduce the GC pressure on sending and receiving node. +# When unset, the default is enabled. While this feature tries to keep the +# disks balanced, it cannot guarantee it. This feature will be automatically +# disabled if internode encryption is enabled. +# stream_entire_sstables: true + +# Throttles entire SSTable outbound streaming file transfers on +# this node to the given total throughput in Mbps. +# Setting this value to 0 it disables throttling. +# When unset, the default is 200 Mbps or 24 MiB/s. +# entire_sstable_stream_throughput_outbound: 24MiB/s + +# Throttles entire SSTable file streaming between datacenters. +# Setting this value to 0 disables throttling for entire SSTable inter-DC file streaming. +# When unset, the default is 200 Mbps or 24 MiB/s. +# entire_sstable_inter_dc_stream_throughput_outbound: 24MiB/s + +# Throttles all outbound streaming file transfers on this node to the +# given total throughput in Mbps. This is necessary because Cassandra does +# mostly sequential IO when streaming data during bootstrap or repair, which +# can lead to saturating the network connection and degrading rpc performance. +# When unset, the default is 200 Mbps or 24 MiB/s. +# stream_throughput_outbound: 24MiB/s + +# Throttles all streaming file transfer between the datacenters, +# this setting allows users to throttle inter dc stream throughput in addition +# to throttling all network stream traffic as configured with +# stream_throughput_outbound_megabits_per_sec +# When unset, the default is 200 Mbps or 24 MiB/s. +# inter_dc_stream_throughput_outbound: 24MiB/s + +# Server side timeouts for requests. The server will return a timeout exception +# to the client if it can't complete an operation within the corresponding +# timeout. Those settings are a protection against: +# 1) having client wait on an operation that might never terminate due to some +# failures. +# 2) operations that use too much CPU/read too much data (leading to memory build +# up) by putting a limit to how long an operation will execute. +# For this reason, you should avoid putting these settings too high. In other words, +# if you are timing out requests because of underlying resource constraints then +# increasing the timeout will just cause more problems. Of course putting them too +# low is equally ill-advised since clients could get timeouts even for successful +# operations just because the timeout setting is too tight. + +# How long the coordinator should wait for read operations to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +read_request_timeout: 5000ms +# How long the coordinator should wait for seq or index scans to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +range_request_timeout: 10000ms +# How long the coordinator should wait for writes to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +write_request_timeout: 2000ms +# How long the coordinator should wait for counter writes to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +counter_write_request_timeout: 5000ms +# How long a coordinator should continue to retry a CAS operation +# that contends with other proposals for the same row. +# Lowest acceptable value is 10 ms. +# Min unit: ms +cas_contention_timeout: 1000ms +# How long the coordinator should wait for truncates to complete +# (This can be much longer, because unless auto_snapshot is disabled +# we need to flush first so we can snapshot before removing the data.) +# Lowest acceptable value is 10 ms. +# Min unit: ms +truncate_request_timeout: 60000ms +# The default timeout for other, miscellaneous operations. +# Lowest acceptable value is 10 ms. +# Min unit: ms +request_timeout: 10000ms + +# Defensive settings for protecting Cassandra from true network partitions. +# See (CASSANDRA-14358) for details. +# +# The amount of time to wait for internode tcp connections to establish. +# Min unit: ms +# internode_tcp_connect_timeout: 2000ms +# +# The amount of time unacknowledged data is allowed on a connection before we throw out the connection +# Note this is only supported on Linux + epoll, and it appears to behave oddly above a setting of 30000 +# (it takes much longer than 30s) as of Linux 4.12. If you want something that high set this to 0 +# which picks up the OS default and configure the net.ipv4.tcp_retries2 sysctl to be ~8. +# Min unit: ms +# internode_tcp_user_timeout: 30000ms + +# The amount of time unacknowledged data is allowed on a streaming connection. +# The default is 5 minutes. Increase it or set it to 0 in order to increase the timeout. +# Min unit: ms +# internode_streaming_tcp_user_timeout: 300000ms + +# Global, per-endpoint and per-connection limits imposed on messages queued for delivery to other nodes +# and waiting to be processed on arrival from other nodes in the cluster. These limits are applied to the on-wire +# size of the message being sent or received. +# +# The basic per-link limit is consumed in isolation before any endpoint or global limit is imposed. +# Each node-pair has three links: urgent, small and large. So any given node may have a maximum of +# N*3*(internode_application_send_queue_capacity+internode_application_receive_queue_capacity) +# messages queued without any coordination between them although in practice, with token-aware routing, only RF*tokens +# nodes should need to communicate with significant bandwidth. +# +# The per-endpoint limit is imposed on all messages exceeding the per-link limit, simultaneously with the global limit, +# on all links to or from a single node in the cluster. +# The global limit is imposed on all messages exceeding the per-link limit, simultaneously with the per-endpoint limit, +# on all links to or from any node in the cluster. +# +# Min unit: B +# internode_application_send_queue_capacity: 4MiB +# internode_application_send_queue_reserve_endpoint_capacity: 128MiB +# internode_application_send_queue_reserve_global_capacity: 512MiB +# internode_application_receive_queue_capacity: 4MiB +# internode_application_receive_queue_reserve_endpoint_capacity: 128MiB +# internode_application_receive_queue_reserve_global_capacity: 512MiB + + +# How long before a node logs slow queries. Select queries that take longer than +# this timeout to execute, will generate an aggregated log message, so that slow queries +# can be identified. Set this value to zero to disable slow query logging. +# Min unit: ms +slow_query_log_timeout: 500ms + +# Enable operation timeout information exchange between nodes to accurately +# measure request timeouts. If disabled, replicas will assume that requests +# were forwarded to them instantly by the coordinator, which means that +# under overload conditions we will waste that much extra time processing +# already-timed-out requests. +# +# Warning: It is generally assumed that users have setup NTP on their clusters, and that clocks are modestly in sync, +# since this is a requirement for general correctness of last write wins. +# internode_timeout: true + +# Set period for idle state control messages for earlier detection of failed streams +# This node will send a keep-alive message periodically on the streaming's control channel. +# This ensures that any eventual SocketTimeoutException will occur within 2 keep-alive cycles +# If the node cannot send, or timeouts sending, the keep-alive message on the netty control channel +# the stream session is closed. +# Default value is 300s (5 minutes), which means stalled streams +# are detected within 10 minutes +# Specify 0 to disable. +# Min unit: s +# streaming_keep_alive_period: 300s + +# Limit number of connections per host for streaming +# Increase this when you notice that joins are CPU-bound rather that network +# bound (for example a few nodes with big files). +# streaming_connections_per_host: 1 + +# Settings for stream stats tracking; used by system_views.streaming table +# How long before a stream is evicted from tracking; this impacts both historic and currently running +# streams. +# streaming_state_expires: 3d +# How much memory may be used for tracking before evicting session from tracking; once crossed +# historic and currently running streams maybe impacted. +# streaming_state_size: 40MiB +# Enable/Disable tracking of streaming stats +# streaming_stats_enabled: true + +# Allows denying configurable access (rw/rr) to operations on configured ks, table, and partitions, intended for use by +# operators to manage cluster health vs application access. See CASSANDRA-12106 and CEP-13 for more details. +# partition_denylist_enabled: false + +# denylist_writes_enabled: true +# denylist_reads_enabled: true +# denylist_range_reads_enabled: true + +# The interval at which keys in the cache for denylisting will "expire" and async refresh from the backing DB. +# Note: this serves only as a fail-safe, as the usage pattern is expected to be "mutate state, refresh cache" on any +# changes to the underlying denylist entries. See documentation for details. +# Min unit: s +# denylist_refresh: 600s + +# In the event of errors on attempting to load the denylist cache, retry on this interval. +# Min unit: s +# denylist_initial_load_retry: 5s + +# We cap the number of denylisted keys allowed per table to keep things from growing unbounded. Nodes will warn above +# this limit while allowing new denylisted keys to be inserted. Denied keys are loaded in natural query / clustering +# ordering by partition key in case of overflow. +# denylist_max_keys_per_table: 1000 + +# We cap the total number of denylisted keys allowed in the cluster to keep things from growing unbounded. +# Nodes will warn on initial cache load that there are too many keys and be direct the operator to trim down excess +# entries to within the configured limits. +# denylist_max_keys_total: 10000 + +# Since the denylist in many ways serves to protect the health of the cluster from partitions operators have identified +# as being in a bad state, we usually want more robustness than just CL.ONE on operations to/from these tables to +# ensure that these safeguards are in place. That said, we allow users to configure this if they're so inclined. +# denylist_consistency_level: QUORUM + +# phi value that must be reached for a host to be marked down. +# most users should never need to adjust this. +# phi_convict_threshold: 8 + +# endpoint_snitch -- Set this to a class that implements +# IEndpointSnitch. The snitch has two functions: +# +# - it teaches Cassandra enough about your network topology to route +# requests efficiently +# - it allows Cassandra to spread replicas around your cluster to avoid +# correlated failures. It does this by grouping machines into +# "datacenters" and "racks." Cassandra will do its best not to have +# more than one replica on the same "rack" (which may not actually +# be a physical location) +# +# CASSANDRA WILL NOT ALLOW YOU TO SWITCH TO AN INCOMPATIBLE SNITCH +# ONCE DATA IS INSERTED INTO THE CLUSTER. This would cause data loss. +# This means that if you start with the default SimpleSnitch, which +# locates every node on "rack1" in "datacenter1", your only options +# if you need to add another datacenter are GossipingPropertyFileSnitch +# (and the older PFS). From there, if you want to migrate to an +# incompatible snitch like Ec2Snitch you can do it by adding new nodes +# under Ec2Snitch (which will locate them in a new "datacenter") and +# decommissioning the old ones. +# +# Out of the box, Cassandra provides: +# +# SimpleSnitch: +# Treats Strategy order as proximity. This can improve cache +# locality when disabling read repair. Only appropriate for +# single-datacenter deployments. +# +# GossipingPropertyFileSnitch +# This should be your go-to snitch for production use. The rack +# and datacenter for the local node are defined in +# cassandra-rackdc.properties and propagated to other nodes via +# gossip. If cassandra-topology.properties exists, it is used as a +# fallback, allowing migration from the PropertyFileSnitch. +# +# PropertyFileSnitch: +# Proximity is determined by rack and data center, which are +# explicitly configured in cassandra-topology.properties. +# +# Ec2Snitch: +# Appropriate for EC2 deployments in a single Region. Loads Region +# and Availability Zone information from the EC2 API. The Region is +# treated as the datacenter, and the Availability Zone as the rack. +# Only private IPs are used, so this will not work across multiple +# Regions. +# +# Ec2MultiRegionSnitch: +# Uses public IPs as broadcast_address to allow cross-region +# connectivity. (Thus, you should set seed addresses to the public +# IP as well.) You will need to open the storage_port or +# ssl_storage_port on the public IP firewall. (For intra-Region +# traffic, Cassandra will switch to the private IP after +# establishing a connection.) +# +# RackInferringSnitch: +# Proximity is determined by rack and data center, which are +# assumed to correspond to the 3rd and 2nd octet of each node's IP +# address, respectively. Unless this happens to match your +# deployment conventions, this is best used as an example of +# writing a custom Snitch class and is provided in that spirit. +# +# You can use a custom Snitch by setting this to the full class name +# of the snitch, which will be assumed to be on your classpath. +endpoint_snitch: SimpleSnitch + +# controls how often to perform the more expensive part of host score +# calculation +# Min unit: ms +dynamic_snitch_update_interval: 100ms +# controls how often to reset all host scores, allowing a bad host to +# possibly recover +# Min unit: ms +dynamic_snitch_reset_interval: 600000ms +# if set greater than zero, this will allow +# 'pinning' of replicas to hosts in order to increase cache capacity. +# The badness threshold will control how much worse the pinned host has to be +# before the dynamic snitch will prefer other replicas over it. This is +# expressed as a double which represents a percentage. Thus, a value of +# 0.2 means Cassandra would continue to prefer the static snitch values +# until the pinned host was 20% worse than the fastest. +dynamic_snitch_badness_threshold: 1.0 + +# Configure server-to-server internode encryption +# +# JVM and netty defaults for supported SSL socket protocols and cipher suites can +# be replaced using custom encryption options. This is not recommended +# unless you have policies in place that dictate certain settings, or +# need to disable vulnerable ciphers or protocols in case the JVM cannot +# be updated. +# +# FIPS compliant settings can be configured at JVM level and should not +# involve changing encryption settings here: +# https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/FIPS.html +# +# **NOTE** this default configuration is an insecure configuration. If you need to +# enable server-to-server encryption generate server keystores (and truststores for mutual +# authentication) per: +# http://download.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore +# Then perform the following configuration changes: +# +# Step 1: Set internode_encryption= and explicitly set optional=true. Restart all nodes +# +# Step 2: Set optional=false (or remove it) and if you generated truststores and want to use mutual +# auth set require_client_auth=true. Restart all nodes +server_encryption_options: + # On outbound connections, determine which type of peers to securely connect to. + # The available options are : + # none : Do not encrypt outgoing connections + # dc : Encrypt connections to peers in other datacenters but not within datacenters + # rack : Encrypt connections to peers in other racks but not within racks + # all : Always use encrypted connections + internode_encryption: none + # When set to true, encrypted and unencrypted connections are allowed on the storage_port + # This should _only be true_ while in unencrypted or transitional operation + # optional defaults to true if internode_encryption is none + # optional: true + # If enabled, will open up an encrypted listening socket on ssl_storage_port. Should only be used + # during upgrade to 4.0; otherwise, set to false. + legacy_ssl_storage_port_enabled: false + # Set to a valid keystore if internode_encryption is dc, rack or all + keystore: conf/.keystore + keystore_password: cassandra + # Configure the way Cassandra creates SSL contexts. + # To use PEM-based key material, see org.apache.cassandra.security.PEMBasedSslContextFactory + # ssl_context_factory: + # # Must be an instance of org.apache.cassandra.security.ISslContextFactory + # class_name: org.apache.cassandra.security.DefaultSslContextFactory + # Verify peer server certificates + require_client_auth: false + # Set to a valid trustore if require_client_auth is true + truststore: conf/.truststore + truststore_password: cassandra + # Verify that the host name in the certificate matches the connected host + require_endpoint_verification: false + # More advanced defaults: + # protocol: TLS + # store_type: JKS + # cipher_suites: [ + # TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + # TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + # TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, + # TLS_RSA_WITH_AES_256_CBC_SHA + # ] + +# Configure client-to-server encryption. +# +# **NOTE** this default configuration is an insecure configuration. If you need to +# enable client-to-server encryption generate server keystores (and truststores for mutual +# authentication) per: +# http://download.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore +# Then perform the following configuration changes: +# +# Step 1: Set enabled=true and explicitly set optional=true. Restart all nodes +# +# Step 2: Set optional=false (or remove it) and if you generated truststores and want to use mutual +# auth set require_client_auth=true. Restart all nodes +client_encryption_options: + # Enable client-to-server encryption + enabled: false + # When set to true, encrypted and unencrypted connections are allowed on the native_transport_port + # This should _only be true_ while in unencrypted or transitional operation + # optional defaults to true when enabled is false, and false when enabled is true. + # optional: true + # Set keystore and keystore_password to valid keystores if enabled is true + keystore: conf/.keystore + keystore_password: cassandra + # Configure the way Cassandra creates SSL contexts. + # To use PEM-based key material, see org.apache.cassandra.security.PEMBasedSslContextFactory + # ssl_context_factory: + # # Must be an instance of org.apache.cassandra.security.ISslContextFactory + # class_name: org.apache.cassandra.security.DefaultSslContextFactory + # Verify client certificates + require_client_auth: false + # Set trustore and truststore_password if require_client_auth is true + # truststore: conf/.truststore + # truststore_password: cassandra + # More advanced defaults: + # protocol: TLS + # store_type: JKS + # cipher_suites: [ + # TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + # TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + # TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, + # TLS_RSA_WITH_AES_256_CBC_SHA + # ] + +# internode_compression controls whether traffic between nodes is +# compressed. +# Can be: +# +# all +# all traffic is compressed +# +# dc +# traffic between different datacenters is compressed +# +# none +# nothing is compressed. +internode_compression: dc + +# Enable or disable tcp_nodelay for inter-dc communication. +# Disabling it will result in larger (but fewer) network packets being sent, +# reducing overhead from the TCP protocol itself, at the cost of increasing +# latency if you block for cross-datacenter responses. +inter_dc_tcp_nodelay: false + +# TTL for different trace types used during logging of the repair process. +# Min unit: s +trace_type_query_ttl: 1d +# Min unit: s +trace_type_repair_ttl: 7d + +# If unset, all GC Pauses greater than gc_log_threshold will log at +# INFO level +# UDFs (user defined functions) are disabled by default. +# As of Cassandra 3.0 there is a sandbox in place that should prevent execution of evil code. +user_defined_functions_enabled: false + +# Enables scripted UDFs (JavaScript UDFs). +# Java UDFs are always enabled, if user_defined_functions_enabled is true. +# Enable this option to be able to use UDFs with "language javascript" or any custom JSR-223 provider. +# This option has no effect, if user_defined_functions_enabled is false. +scripted_user_defined_functions_enabled: false + +# Enables encrypting data at-rest (on disk). Different key providers can be plugged in, but the default reads from +# a JCE-style keystore. A single keystore can hold multiple keys, but the one referenced by +# the "key_alias" is the only key that will be used for encrypt opertaions; previously used keys +# can still (and should!) be in the keystore and will be used on decrypt operations +# (to handle the case of key rotation). +# +# It is strongly recommended to download and install Java Cryptography Extension (JCE) +# Unlimited Strength Jurisdiction Policy Files for your version of the JDK. +# (current link: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html) +# +# Currently, only the following file types are supported for transparent data encryption, although +# more are coming in future cassandra releases: commitlog, hints +transparent_data_encryption_options: + enabled: false + chunk_length_kb: 64 + cipher: AES/CBC/PKCS5Padding + key_alias: testing:1 + # CBC IV length for AES needs to be 16 bytes (which is also the default size) + # iv_length: 16 + key_provider: + - class_name: org.apache.cassandra.security.JKSKeyProvider + parameters: + - keystore: conf/.keystore + keystore_password: cassandra + store_type: JCEKS + key_password: cassandra + + +##################### +# SAFETY THRESHOLDS # +##################### + +# When executing a scan, within or across a partition, we need to keep the +# tombstones seen in memory so we can return them to the coordinator, which +# will use them to make sure other replicas also know about the deleted rows. +# With workloads that generate a lot of tombstones, this can cause performance +# problems and even exaust the server heap. +# (http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets) +# Adjust the thresholds here if you understand the dangers and want to +# scan more tombstones anyway. These thresholds may also be adjusted at runtime +# using the StorageService mbean. +tombstone_warn_threshold: 1000 +tombstone_failure_threshold: 100000 + +# Filtering and secondary index queries at read consistency levels above ONE/LOCAL_ONE use a +# mechanism called replica filtering protection to ensure that results from stale replicas do +# not violate consistency. (See CASSANDRA-8272 and CASSANDRA-15907 for more details.) This +# mechanism materializes replica results by partition on-heap at the coordinator. The more possibly +# stale results returned by the replicas, the more rows materialized during the query. +replica_filtering_protection: + # These thresholds exist to limit the damage severely out-of-date replicas can cause during these + # queries. They limit the number of rows from all replicas individual index and filtering queries + # can materialize on-heap to return correct results at the desired read consistency level. + # + # "cached_replica_rows_warn_threshold" is the per-query threshold at which a warning will be logged. + # "cached_replica_rows_fail_threshold" is the per-query threshold at which the query will fail. + # + # These thresholds may also be adjusted at runtime using the StorageService mbean. + # + # If the failure threshold is breached, it is likely that either the current page/fetch size + # is too large or one or more replicas is severely out-of-sync and in need of repair. + cached_rows_warn_threshold: 2000 + cached_rows_fail_threshold: 32000 + +# Log WARN on any multiple-partition batch size exceeding this value. 5KiB per batch by default. +# Caution should be taken on increasing the size of this threshold as it can lead to node instability. +# Min unit: KiB +batch_size_warn_threshold: 5KiB + +# Fail any multiple-partition batch exceeding this value. 50KiB (10x warn threshold) by default. +# Min unit: KiB +batch_size_fail_threshold: 50KiB + +# Log WARN on any batches not of type LOGGED than span across more partitions than this limit +unlogged_batch_across_partitions_warn_threshold: 10 + +# Log a warning when compacting partitions larger than this value +compaction_large_partition_warning_threshold: 100MiB + +# Log a warning when writing more tombstones than this value to a partition +compaction_tombstone_warning_threshold: 100000 + +# GC Pauses greater than 200 ms will be logged at INFO level +# This threshold can be adjusted to minimize logging if necessary +# Min unit: ms +# gc_log_threshold: 200ms + +# GC Pauses greater than gc_warn_threshold will be logged at WARN level +# Adjust the threshold based on your application throughput requirement. Setting to 0 +# will deactivate the feature. +# Min unit: ms +# gc_warn_threshold: 1000ms + +# Maximum size of any value in SSTables. Safety measure to detect SSTable corruption +# early. Any value size larger than this threshold will result into marking an SSTable +# as corrupted. This should be positive and less than 2GiB. +# Min unit: MiB +# max_value_size: 256MiB + +# ** Impact on keyspace creation ** +# If replication factor is not mentioned as part of keyspace creation, default_keyspace_rf would apply. +# Changing this configuration would only take effect for keyspaces created after the change, but does not impact +# existing keyspaces created prior to the change. +# ** Impact on keyspace alter ** +# When altering a keyspace from NetworkTopologyStrategy to SimpleStrategy, default_keyspace_rf is applied if rf is not +# explicitly mentioned. +# ** Impact on system keyspaces ** +# This would also apply for any system keyspaces that need replication factor. +# A further note about system keyspaces - system_traces and system_distributed keyspaces take RF of 2 or default, +# whichever is higher, and system_auth keyspace takes RF of 1 or default, whichever is higher. +# Suggested value for use in production: 3 +# default_keyspace_rf: 1 + +# Track a metric per keyspace indicating whether replication achieved the ideal consistency +# level for writes without timing out. This is different from the consistency level requested by +# each write which may be lower in order to facilitate availability. +# ideal_consistency_level: EACH_QUORUM + +# Automatically upgrade sstables after upgrade - if there is no ordinary compaction to do, the +# oldest non-upgraded sstable will get upgraded to the latest version +# automatic_sstable_upgrade: false +# Limit the number of concurrent sstable upgrades +# max_concurrent_automatic_sstable_upgrades: 1 + +# Audit logging - Logs every incoming CQL command request, authentication to a node. See the docs +# on audit_logging for full details about the various configuration options. +audit_logging_options: + enabled: false + logger: + - class_name: BinAuditLogger + # audit_logs_dir: + # included_keyspaces: + # excluded_keyspaces: system, system_schema, system_virtual_schema + # included_categories: + # excluded_categories: + # included_users: + # excluded_users: + # roll_cycle: HOURLY + # block: true + # max_queue_weight: 268435456 # 256 MiB + # max_log_size: 17179869184 # 16 GiB + ## archive command is "/path/to/script.sh %path" where %path is replaced with the file being rolled: + # archive_command: + # max_archive_retries: 10 + + +# default options for full query logging - these can be overridden from command line when executing +# nodetool enablefullquerylog +# full_query_logging_options: + # log_dir: + # roll_cycle: HOURLY + # block: true + # max_queue_weight: 268435456 # 256 MiB + # max_log_size: 17179869184 # 16 GiB + ## archive command is "/path/to/script.sh %path" where %path is replaced with the file being rolled: + # archive_command: + ## note that enabling this allows anyone with JMX/nodetool access to run local shell commands as the user running cassandra + # allow_nodetool_archive_command: false + # max_archive_retries: 10 + +# validate tombstones on reads and compaction +# can be either "disabled", "warn" or "exception" +# corrupted_tombstone_strategy: disabled + +# Diagnostic Events # +# If enabled, diagnostic events can be helpful for troubleshooting operational issues. Emitted events contain details +# on internal state and temporal relationships across events, accessible by clients via JMX. +diagnostic_events_enabled: false + +# Use native transport TCP message coalescing. If on upgrade to 4.0 you found your throughput decreasing, and in +# particular you run an old kernel or have very fewer client connections, this option might be worth evaluating. +#native_transport_flush_in_batches_legacy: false + +# Enable tracking of repaired state of data during reads and comparison between replicas +# Mismatches between the repaired sets of replicas can be characterized as either confirmed +# or unconfirmed. In this context, unconfirmed indicates that the presence of pending repair +# sessions, unrepaired partition tombstones, or some other condition means that the disparity +# cannot be considered conclusive. Confirmed mismatches should be a trigger for investigation +# as they may be indicative of corruption or data loss. +# There are separate flags for range vs partition reads as single partition reads are only tracked +# when CL > 1 and a digest mismatch occurs. Currently, range queries don't use digests so if +# enabled for range reads, all range reads will include repaired data tracking. As this adds +# some overhead, operators may wish to disable it whilst still enabling it for partition reads +repaired_data_tracking_for_range_reads_enabled: false +repaired_data_tracking_for_partition_reads_enabled: false +# If false, only confirmed mismatches will be reported. If true, a separate metric for unconfirmed +# mismatches will also be recorded. This is to avoid potential signal:noise issues are unconfirmed +# mismatches are less actionable than confirmed ones. +report_unconfirmed_repaired_data_mismatches: false + +# Having many tables and/or keyspaces negatively affects performance of many operations in the +# cluster. When the number of tables/keyspaces in the cluster exceeds the following thresholds +# a client warning will be sent back to the user when creating a table or keyspace. +# As of cassandra 4.1, these properties are deprecated in favor of keyspaces_warn_threshold and tables_warn_threshold +# table_count_warn_threshold: 150 +# keyspace_count_warn_threshold: 40 + +# configure the read and write consistency levels for modifications to auth tables +# auth_read_consistency_level: LOCAL_QUORUM +# auth_write_consistency_level: EACH_QUORUM + +# Delays on auth resolution can lead to a thundering herd problem on reconnects; this option will enable +# warming of auth caches prior to node completing startup. See CASSANDRA-16958 +# auth_cache_warming_enabled: false + +######################### +# EXPERIMENTAL FEATURES # +######################### + +# Enables materialized view creation on this node. +# Materialized views are considered experimental and are not recommended for production use. +materialized_views_enabled: false + +# Enables SASI index creation on this node. +# SASI indexes are considered experimental and are not recommended for production use. +sasi_indexes_enabled: false + +# Enables creation of transiently replicated keyspaces on this node. +# Transient replication is experimental and is not recommended for production use. +transient_replication_enabled: false + +# Enables the used of 'ALTER ... DROP COMPACT STORAGE' statements on this node. +# 'ALTER ... DROP COMPACT STORAGE' is considered experimental and is not recommended for production use. +drop_compact_storage_enabled: false + +# Whether or not USE is allowed. This is enabled by default to avoid failure on upgrade. +#use_statements_enabled: true + +# When the client triggers a protocol exception or unknown issue (Cassandra bug) we increment +# a client metric showing this; this logic will exclude specific subnets from updating these +# metrics +#client_error_reporting_exclusions: +# subnets: +# - 127.0.0.1 +# - 127.0.0.0/31 + +# Enables read thresholds (warn/fail) across all replicas for reporting back to the client. +# See: CASSANDRA-16850 +# read_thresholds_enabled: false # scheduled to be set true in 4.2 +# When read_thresholds_enabled: true, this tracks the materialized size of a query on the +# coordinator. If coordinator_read_size_warn_threshold is defined, this will emit a warning +# to clients with details on what query triggered this as well as the size of the result set; if +# coordinator_read_size_fail_threshold is defined, this will fail the query after it +# has exceeded this threshold, returning a read error to the user. +# coordinator_read_size_warn_threshold: +# coordinator_read_size_fail_threshold: +# When read_thresholds_enabled: true, this tracks the size of the local read (as defined by +# heap size), and will warn/fail based off these thresholds; undefined disables these checks. +# local_read_size_warn_threshold: +# local_read_size_fail_threshold: +# When read_thresholds_enabled: true, this tracks the expected memory size of the RowIndexEntry +# and will warn/fail based off these thresholds; undefined disables these checks +# row_index_read_size_warn_threshold: +# row_index_read_size_fail_threshold: + +# Guardrail to warn or fail when creating more user keyspaces than threshold. +# The two thresholds default to -1 to disable. +# keyspaces_warn_threshold: -1 +# keyspaces_fail_threshold: -1 +# Guardrail to warn or fail when creating more user tables than threshold. +# The two thresholds default to -1 to disable. +# tables_warn_threshold: -1 +# tables_fail_threshold: -1 +# Guardrail to enable or disable the ability to create uncompressed tables +# uncompressed_tables_enabled: true +# Guardrail to warn or fail when creating/altering a table with more columns per table than threshold. +# The two thresholds default to -1 to disable. +# columns_per_table_warn_threshold: -1 +# columns_per_table_fail_threshold: -1 +# Guardrail to warn or fail when creating more secondary indexes per table than threshold. +# The two thresholds default to -1 to disable. +# secondary_indexes_per_table_warn_threshold: -1 +# secondary_indexes_per_table_fail_threshold: -1 +# Guardrail to enable or disable the creation of secondary indexes +# secondary_indexes_enabled: true +# Guardrail to warn or fail when creating more materialized views per table than threshold. +# The two thresholds default to -1 to disable. +# materialized_views_per_table_warn_threshold: -1 +# materialized_views_per_table_fail_threshold: -1 +# Guardrail to warn about, ignore or reject properties when creating tables. By default all properties are allowed. +# table_properties_warned: [] +# table_properties_ignored: [] +# table_properties_disallowed: [] +# Guardrail to allow/disallow user-provided timestamps. Defaults to true. +# user_timestamps_enabled: true +# Guardrail to allow/disallow GROUP BY functionality. +# group_by_enabled: true +# Guardrail to allow/disallow TRUNCATE and DROP TABLE statements +# drop_truncate_table_enabled: true +# Guardrail to warn or fail when using a page size greater than threshold. +# The two thresholds default to -1 to disable. +# page_size_warn_threshold: -1 +# page_size_fail_threshold: -1 +# Guardrail to allow/disallow list operations that require read before write, i.e. setting list element by index and +# removing list elements by either index or value. Defaults to true. +# read_before_write_list_operations_enabled: true +# Guardrail to warn or fail when querying with an IN restriction selecting more partition keys than threshold. +# The two thresholds default to -1 to disable. +# partition_keys_in_select_warn_threshold: -1 +# partition_keys_in_select_fail_threshold: -1 +# Guardrail to warn or fail when an IN query creates a cartesian product with a size exceeding threshold, +# eg. "a in (1,2,...10) and b in (1,2...10)" results in cartesian product of 100. +# The two thresholds default to -1 to disable. +# in_select_cartesian_product_warn_threshold: -1 +# in_select_cartesian_product_fail_threshold: -1 +# Guardrail to warn about or reject read consistency levels. By default, all consistency levels are allowed. +# read_consistency_levels_warned: [] +# read_consistency_levels_disallowed: [] +# Guardrail to warn about or reject write consistency levels. By default, all consistency levels are allowed. +# write_consistency_levels_warned: [] +# write_consistency_levels_disallowed: [] +# Guardrail to warn or fail when encountering larger size of collection data than threshold. +# At query time this guardrail is applied only to the collection fragment that is being writen, even though in the case +# of non-frozen collections there could be unaccounted parts of the collection on the sstables. This is done this way to +# prevent read-before-write. The guardrail is also checked at sstable write time to detect large non-frozen collections, +# although in that case exceeding the fail threshold will only log an error message, without interrupting the operation. +# The two thresholds default to null to disable. +# Min unit: B +# collection_size_warn_threshold: +# Min unit: B +# collection_size_fail_threshold: +# Guardrail to warn or fail when encountering more elements in collection than threshold. +# At query time this guardrail is applied only to the collection fragment that is being writen, even though in the case +# of non-frozen collections there could be unaccounted parts of the collection on the sstables. This is done this way to +# prevent read-before-write. The guardrail is also checked at sstable write time to detect large non-frozen collections, +# although in that case exceeding the fail threshold will only log an error message, without interrupting the operation. +# The two thresholds default to -1 to disable. +# items_per_collection_warn_threshold: -1 +# items_per_collection_fail_threshold: -1 +# Guardrail to allow/disallow querying with ALLOW FILTERING. Defaults to true. +# allow_filtering_enabled: true +# Guardrail to warn or fail when creating a user-defined-type with more fields in than threshold. +# Default -1 to disable. +# fields_per_udt_warn_threshold: -1 +# fields_per_udt_fail_threshold: -1 +# Guardrail to warn or fail when local data disk usage percentage exceeds threshold. Valid values are in [1, 100]. +# This is only used for the disks storing data directories, so it won't count any separate disks used for storing +# the commitlog, hints nor saved caches. The disk usage is the ratio between the amount of space used by the data +# directories and the addition of that same space and the remaining free space on disk. The main purpose of this +# guardrail is rejecting user writes when the disks are over the defined usage percentage, so the writes done by +# background processes such as compaction and streaming don't fail due to a full disk. The limits should be defined +# accordingly to the expected data growth due to those background processes, so for example a compaction strategy +# doubling the size of the data would require to keep the disk usage under 50%. +# The two thresholds default to -1 to disable. +# data_disk_usage_percentage_warn_threshold: -1 +# data_disk_usage_percentage_fail_threshold: -1 +# Allows defining the max disk size of the data directories when calculating thresholds for +# disk_usage_percentage_warn_threshold and disk_usage_percentage_fail_threshold, so if this is greater than zero they +# become percentages of a fixed size on disk instead of percentages of the physically available disk size. This should +# be useful when we have a large disk and we only want to use a part of it for Cassandra's data directories. +# Valid values are in [1, max available disk size of all data directories]. +# Defaults to null to disable and use the physically available disk size of data directories during calculations. +# Min unit: B +# data_disk_usage_max_disk_size: +# Guardrail to warn or fail when the minimum replication factor is lesser than threshold. +# This would also apply to system keyspaces. +# Suggested value for use in production: 2 or higher +# minimum_replication_factor_warn_threshold: -1 +# minimum_replication_factor_fail_threshold: -1 + +# Startup Checks are executed as part of Cassandra startup process, not all of them +# are configurable (so you can disable them) but these which are enumerated bellow. +# Uncomment the startup checks and configure them appropriately to cover your needs. +# +#startup_checks: +# Verifies correct ownership of attached locations on disk at startup. See CASSANDRA-16879 for more details. +# check_filesystem_ownership: +# enabled: false +# ownership_token: "sometoken" # (overriden by "CassandraOwnershipToken" system property) +# ownership_filename: ".cassandra_fs_ownership" # (overriden by "cassandra.fs_ownership_filename") +# Prevents a node from starting if snitch's data center differs from previous data center. +# check_dc: +# enabled: true # (overriden by cassandra.ignore_dc system property) +# Prevents a node from starting if snitch's rack differs from previous rack. +# check_rack: +# enabled: true # (overriden by cassandra.ignore_rack system property) +# Enable this property to fail startup if the node is down for longer than gc_grace_seconds, to potentially +# prevent data resurrection on tables with deletes. By default, this will run against all keyspaces and tables +# except the ones specified on excluded_keyspaces and excluded_tables. +# check_data_resurrection: +# enabled: false +# file where Cassandra periodically writes the last time it was known to run +# heartbeat_file: /var/lib/cassandra/data/cassandra-heartbeat +# excluded_keyspaces: # comma separated list of keyspaces to exclude from the check +# excluded_tables: # comma separated list of keyspace.table pairs to exclude from the check diff --git a/testfiles/cassandra-rackdc.properties b/testfiles/cassandra-rackdc.properties new file mode 100644 index 0000000..cc472b4 --- /dev/null +++ b/testfiles/cassandra-rackdc.properties @@ -0,0 +1,39 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +# These properties are used with GossipingPropertyFileSnitch and will +# indicate the rack and dc for this node +dc=dc1 +rack=rack1 + +# Add a suffix to a datacenter name. Used by the Ec2Snitch and Ec2MultiRegionSnitch +# to append a string to the EC2 region name. +#dc_suffix= + +# Uncomment the following line to make this snitch prefer the internal ip when possible, as the Ec2MultiRegionSnitch does. +# prefer_local=true + +# Datacenter and rack naming convention used by the Ec2Snitch and Ec2MultiRegionSnitch. +# Options are: +# legacy : datacenter name is the part of the availability zone name preceding the last "-" +# when the zone ends in -1 and includes the number if not -1. Rack is the portion of +# the availability zone name following the last "-". +# Examples: us-west-1a => dc: us-west, rack: 1a; us-west-2b => dc: us-west-2, rack: 2b; +# YOU MUST USE THIS VALUE IF YOU ARE UPGRADING A PRE-4.0 CLUSTER +# standard : Default value. datacenter name is the standard AWS region name, including the number. +# rack name is the region plus the availability zone letter. +# Examples: us-west-1a => dc: us-west-1, rack: us-west-1a; us-west-2b => dc: us-west-2, rack: us-west-2b; +# ec2_naming_scheme=standard From 4eb934d100b541bcd5915f0f96e88be3ceb2ccba Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Mon, 19 Jun 2023 15:49:53 +0300 Subject: [PATCH 02/12] Add cassandra-rackdc.properties writing --- go.mod | 2 +- go.sum | 32 --- pkg/config/builder.go | 59 +++++- pkg/config/builder_test.go | 26 ++- testfiles/cassandra-env.sh | 307 +++++++++++++++++++++++++++++ testfiles/{4.1 => }/cassandra.yaml | 0 testfiles/jvm-server.options | 188 ++++++++++++++++++ 7 files changed, 573 insertions(+), 41 deletions(-) create mode 100644 testfiles/cassandra-env.sh rename testfiles/{4.1 => }/cassandra.yaml (100%) create mode 100644 testfiles/jvm-server.options diff --git a/go.mod b/go.mod index 1d3089a..74028af 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/k8ssandra/k8ssandra-client go 1.20 require ( + github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d github.com/charmbracelet/bubbles v0.16.1 github.com/charmbracelet/bubbletea v0.24.2 github.com/charmbracelet/lipgloss v0.7.1 @@ -30,7 +31,6 @@ require ( github.com/Masterminds/semver/v3 v3.1.1 // indirect github.com/Masterminds/sprig/v3 v3.2.2 // indirect github.com/Masterminds/squirrel v1.5.3 // indirect - github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d // indirect github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535 // indirect github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect diff --git a/go.sum b/go.sum index 8f6db55..d6a4baf 100644 --- a/go.sum +++ b/go.sum @@ -39,10 +39,6 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= -github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= -github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= -github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.0.0 h1:dtDWrepsVPfW9H/4y7dDgFc2MBUSeJhlaDtK13CxFlU= github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= @@ -65,10 +61,7 @@ github.com/Masterminds/squirrel v1.5.3 h1:YPpoceAcxuzIljlr5iWpNKaql7hLeG1KLSrhvd github.com/Masterminds/squirrel v1.5.3/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= github.com/Microsoft/go-winio v0.5.1 h1:aPJp2QD7OOrhO5tQXqQoGSJc+DjDtWTGLOmNyAm6FgY= github.com/Microsoft/hcsshim v0.9.3 h1:k371PzBuRrz2b+ebGuI2nVgVhgsVX60jMfSw80NECxo= -github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d h1:UrqY+r/OJnIp5u0s1SbQ8dVfLCZJsnvazdBP5hS4iRs= github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d h1:O47TZtmKaBkPubAQBONxtC61E7GPOLkGDhJDWChl17s= github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d/go.mod h1:tRDczOw8/ipMRMBrO3kvAWxqQNnVXglAzhIqrXmKRAg= @@ -79,7 +72,6 @@ github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hC github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535 h1:4daAzAu0S6Vi7/lbWECcX0j45yZReDZ56BQsrVBOEEY= github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= @@ -92,8 +84,6 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= -github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= -github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/bshuster-repo/logrus-logstash-hook v1.0.0 h1:e+C0SB5R1pu//O4MQ3f9cFuPGoOVeF2fE4Og9otCc70= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/bugsnag/bugsnag-go v0.0.0-20141110184014-b1d153021fcd h1:rFt+Y/IK1aEZkEHchZRSq9OQbsSzIT/OrI8YFFmRIng= @@ -129,7 +119,6 @@ github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2 github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= github.com/containerd/containerd v1.6.6 h1:xJNPhbrmz8xAMDNoVjHy9YHtWwEQNS+CDkcIRh7t8Y0= github.com/containerd/containerd v1.6.6/go.mod h1:ZoP1geJldzCVY3Tonoz7b1IXk8rIX0Nltt5QE4OMNk0= -github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= @@ -163,8 +152,6 @@ github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDD github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1 h1:ZClxb8laGDf5arXfYcAtECDFgAgHklGI8CxgjHnXKJ4= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= -github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= -github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful/v3 v3.10.2 h1:hIovbnmBTLjHXkqEBUz3HGpXZdM7ZrE9fJIZIqlJLqE= github.com/emicklei/go-restful/v3 v3.10.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -190,7 +177,6 @@ github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/flowstack/go-jsonschema v0.1.1/go.mod h1:yL7fNggx1o8rm9RlgXv7hTBWxdBM0rVwpMwimd3F3N0= -github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= @@ -208,7 +194,6 @@ github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2 github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= 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= @@ -329,8 +314,6 @@ github.com/gosuri/uitable v0.0.4 h1:IG2xLKRvErL3uhY6e1BylFzG+aJiwQviDDTfOKeKTpY= github.com/gosuri/uitable v0.0.4/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= @@ -366,10 +349,8 @@ github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLf github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= -github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= 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/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -379,7 +360,6 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1 github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/k8ssandra/cass-operator v1.15.1-0.20230613083330-58dc7268f372 h1:2tpKA5pSwf8F1br1GzUf2BuvkNZjF5WJnTjkqlPdB3M= github.com/k8ssandra/cass-operator v1.15.1-0.20230613083330-58dc7268f372/go.mod h1:SweDRjqzPDrZsGzoN0b/YzWKk+DCy0+4htELKRoMVI8= github.com/karrick/godirwalk v1.16.1 h1:DynhcF+bztK8gooS0+NDJFrdNZjJ3gzVzC545UNA9iw= @@ -410,7 +390,6 @@ github.com/lib/pq v1.10.6 h1:jbk+ZieJ0D7EVGJYpL9QTz7/YW6UHbmdnZWYyK5cdBs= github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= @@ -491,9 +470,6 @@ github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4AN 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/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo/v2 v2.9.4 h1:xR7vG4IXt5RWx6FfIjyAtsoMAtnc3C/rFXBBd2AjZwE= @@ -546,14 +522,12 @@ github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6po github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rubenv/sql-migrate v1.1.1 h1:haR5Hn8hbW9/SpAICrXoZqXnywS7Q5WijwkQENPeNWY= github.com/rubenv/sql-migrate v1.1.1/go.mod h1:/7TZymwxN8VWumcIxw1jjHEcR1djpdkMHQPT4FWdnbQ= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= @@ -562,7 +536,6 @@ github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= @@ -594,14 +567,12 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xlab/treeprint v1.1.0 h1:G/1DjNkPpfZCFt9CSh6b5/nY4VimlbHF3Rh4obvtzDk= github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -615,7 +586,6 @@ github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50 h1:hlE8//ciYMzt github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f h1:ERexzlUfuTvpE74urLSbIQW0Z/6hF9t8U4NsJLaioAY= github.com/ziutek/mymysql v1.5.4 h1:GB0qdRGsTwQSBVYuVShFBKaXSnSnYYC2d9knnE1LHFs= github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0= -go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= @@ -1014,7 +984,6 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -1030,7 +999,6 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= -gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= helm.sh/helm/v3 v3.9.4 h1:TCI1QhJUeLVOdccfdw+vnSEO3Td6gNqibptB04QtExY= helm.sh/helm/v3 v3.9.4/go.mod h1:3eaWAIqzvlRSD06gR9MMwmp2KBKwlu9av1/1BZpjeWY= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/pkg/config/builder.go b/pkg/config/builder.go index a13536e..7bf8538 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "strconv" + "text/template" "github.com/adutra/goalesce" "gopkg.in/yaml.v3" @@ -52,7 +53,7 @@ func Build(ctx context.Context) error { } // Create rack information - if err := createRackProperties(configInput, nodeInfo, outputConfigFileDir()); err != nil { + if err := createRackProperties(configInput, nodeInfo, defaultConfigFileDir(), outputConfigFileDir()); err != nil { return err } @@ -127,14 +128,58 @@ func outputConfigFileDir() string { return "/configs" } -func createRackProperties(configInput *ConfigInput, nodeInfo *NodeInfo, targetDir string) error { +func createRackProperties(configInput *ConfigInput, nodeInfo *NodeInfo, sourceDir, targetDir string) error { // Write cassandra-rackdc.properties file with Datacenter and Rack information - // Load the current file + // This implementation would preserve any extra keys.. but then again, our seedProvider doesn't support those + /* + rackFile := filepath.Join(sourceDir, "cassandra-rackdc.properties") + props, err := properties.LoadFile(rackFile, properties.UTF8) + if err != nil { + return err + } - // Set dc to DatacenterInfo.Name - // Set rack to NodeInfo.Rack - return nil + props.Set("dc", configInput.DatacenterInfo.Name) + props.Set("rack", nodeInfo.Rack) + + targetFile := filepath.Join(targetDir, "cassandra-rackdc.properties") + f, err := os.OpenFile(targetFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0770) + if err != nil { + return err + } + + defer f.Close() + + if _, err = props.WriteComment(f, "#", properties.UTF8); err != nil { + return err + } + */ + + // This creates the cassandra-rackdc.properites with a template with only the values we currently support + targetFileT := filepath.Join(targetDir, "cassandra-rackdc.properties") + fT, err := os.OpenFile(targetFileT, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0770) + if err != nil { + return err + } + + defer fT.Close() + + rackTemplate, err := template.New("cassandra-rackdc.properties").Parse("dc={{ .DatacenterName }}\nrack={{ .RackName }}\n") + if err != nil { + return err + } + + type RackTemplate struct { + DatacenterName string + RackName string + } + + rt := RackTemplate{ + DatacenterName: configInput.DatacenterInfo.Name, + RackName: nodeInfo.Rack, + } + + return rackTemplate.Execute(fT, rt) } func createCassandraEnv(configInput *ConfigInput, targetDir string) error { @@ -208,5 +253,5 @@ func writeYaml(doc map[string]interface{}, targetFile string) error { return err } - return os.WriteFile(targetFile, b, 0) // TODO Fix Perm + return os.WriteFile(targetFile, b, 0660) } diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index a9e5ed5..d37b639 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -83,7 +83,7 @@ func TestParseNodeInfo(t *testing.T) { func TestCassandraYamlWriting(t *testing.T) { require := require.New(t) - cassYamlDir := filepath.Join(envtest.RootDir(), "testfiles", "4.1") + cassYamlDir := filepath.Join(envtest.RootDir(), "testfiles") tempDir, err := os.MkdirTemp("", "client-test") fmt.Printf("tempDir: %s\n", tempDir) @@ -104,3 +104,27 @@ func TestCassandraYamlWriting(t *testing.T) { // TODO Read back and verify all our changes are there } + +func TestRackProperties(t *testing.T) { + require := require.New(t) + propertiesDir := filepath.Join(envtest.RootDir(), "testfiles") + tempDir, err := os.MkdirTemp("", "client-test") + + fmt.Printf("tempDir: %s\n", tempDir) + require.NoError(err) + + // Create mandatory configs.. + t.Setenv("CONFIG_FILE_DATA", existingConfig) + configInput, err := parseConfigInput() + require.NoError(err) + require.NotNil(configInput) + t.Setenv("POD_IP", "172.27.0.1") + t.Setenv("RACK_NAME", "r1") + nodeInfo, err := parseNodeInfo() + require.NoError(err) + require.NotNil(nodeInfo) + + require.NoError(createRackProperties(configInput, nodeInfo, propertiesDir, tempDir)) + + // TODO Verify file data.. +} diff --git a/testfiles/cassandra-env.sh b/testfiles/cassandra-env.sh new file mode 100644 index 0000000..25ba505 --- /dev/null +++ b/testfiles/cassandra-env.sh @@ -0,0 +1,307 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +calculate_heap_sizes() +{ + case "`uname`" in + Linux) + system_memory_in_mb=`free -m | awk '/:/ {print $2;exit}'` + system_cpu_cores=`egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo` + ;; + FreeBSD) + system_memory_in_bytes=`sysctl hw.physmem | awk '{print $2}'` + system_memory_in_mb=`expr $system_memory_in_bytes / 1024 / 1024` + system_cpu_cores=`sysctl hw.ncpu | awk '{print $2}'` + ;; + SunOS) + system_memory_in_mb=`prtconf | awk '/Memory size:/ {print $3}'` + system_cpu_cores=`psrinfo | wc -l` + ;; + Darwin) + system_memory_in_bytes=`sysctl hw.memsize | awk '{print $2}'` + system_memory_in_mb=`expr $system_memory_in_bytes / 1024 / 1024` + system_cpu_cores=`sysctl hw.ncpu | awk '{print $2}'` + ;; + *) + # assume reasonable defaults for e.g. a modern desktop or + # cheap server + system_memory_in_mb="2048" + system_cpu_cores="2" + ;; + esac + + # some systems like the raspberry pi don't report cores, use at least 1 + if [ "$system_cpu_cores" -lt "1" ] + then + system_cpu_cores="1" + fi + + # set max heap size based on the following + # max(min(1/2 ram, 1024MB), min(1/4 ram, 8GB)) + # calculate 1/2 ram and cap to 1024MB + # calculate 1/4 ram and cap to 8192MB + # pick the max + half_system_memory_in_mb=`expr $system_memory_in_mb / 2` + quarter_system_memory_in_mb=`expr $half_system_memory_in_mb / 2` + if [ "$half_system_memory_in_mb" -gt "1024" ] + then + half_system_memory_in_mb="1024" + fi + if [ "$quarter_system_memory_in_mb" -gt "8192" ] + then + quarter_system_memory_in_mb="8192" + fi + if [ "$half_system_memory_in_mb" -gt "$quarter_system_memory_in_mb" ] + then + max_heap_size_in_mb="$half_system_memory_in_mb" + else + max_heap_size_in_mb="$quarter_system_memory_in_mb" + fi + MAX_HEAP_SIZE="${max_heap_size_in_mb}M" + + # Young gen: min(max_sensible_per_modern_cpu_core * num_cores, 1/4 * heap size) + max_sensible_yg_per_core_in_mb="100" + max_sensible_yg_in_mb=`expr $max_sensible_yg_per_core_in_mb "*" $system_cpu_cores` + + desired_yg_in_mb=`expr $max_heap_size_in_mb / 4` + + if [ "$desired_yg_in_mb" -gt "$max_sensible_yg_in_mb" ] + then + HEAP_NEWSIZE="${max_sensible_yg_in_mb}M" + else + HEAP_NEWSIZE="${desired_yg_in_mb}M" + fi +} + +# Sets the path where logback and GC logs are written. +if [ "x$CASSANDRA_LOG_DIR" = "x" ] ; then + CASSANDRA_LOG_DIR="$CASSANDRA_HOME/logs" +fi + +#GC log path has to be defined here because it needs to access CASSANDRA_HOME +if [ $JAVA_VERSION -ge 11 ] || [ $JAVA_VERSION -ge 17 ] ; then + # See description of https://bugs.openjdk.java.net/browse/JDK-8046148 for details about the syntax + # The following is the equivalent to -XX:+PrintGCDetails -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=10M + echo "$JVM_OPTS" | grep -qe "-[X]log:gc" + if [ "$?" = "1" ] ; then # [X] to prevent ccm from replacing this line + # only add -Xlog:gc if it's not mentioned in jvm-server.options file + mkdir -p ${CASSANDRA_LOG_DIR} + JVM_OPTS="$JVM_OPTS -Xlog:gc=info,heap*=trace,age*=debug,safepoint=info,promotion*=trace:file=${CASSANDRA_LOG_DIR}/gc.log:time,uptime,pid,tid,level:filecount=10,filesize=10485760" + fi +else + # Java 8 + echo "$JVM_OPTS" | grep -qe "-[X]loggc" + if [ "$?" = "1" ] ; then # [X] to prevent ccm from replacing this line + # only add -Xlog:gc if it's not mentioned in jvm-server.options file + mkdir -p ${CASSANDRA_LOG_DIR} + JVM_OPTS="$JVM_OPTS -Xloggc:${CASSANDRA_LOG_DIR}/gc.log" + fi +fi + +# Check what parameters were defined on jvm-server.options file to avoid conflicts +echo $JVM_OPTS | grep -q Xmn +DEFINED_XMN=$? +echo $JVM_OPTS | grep -q Xmx +DEFINED_XMX=$? +echo $JVM_OPTS | grep -q Xms +DEFINED_XMS=$? +echo $JVM_OPTS | grep -q UseConcMarkSweepGC +USING_CMS=$? +echo $JVM_OPTS | grep -q +UseG1GC +USING_G1=$? + +# Override these to set the amount of memory to allocate to the JVM at +# start-up. For production use you may wish to adjust this for your +# environment. MAX_HEAP_SIZE is the total amount of memory dedicated +# to the Java heap. HEAP_NEWSIZE refers to the size of the young +# generation. Both MAX_HEAP_SIZE and HEAP_NEWSIZE should be either set +# or not (if you set one, set the other). +# +# The main trade-off for the young generation is that the larger it +# is, the longer GC pause times will be. The shorter it is, the more +# expensive GC will be (usually). +# +# The example HEAP_NEWSIZE assumes a modern 8-core+ machine for decent pause +# times. If in doubt, and if you do not particularly want to tweak, go with +# 100 MB per physical CPU core. + +#MAX_HEAP_SIZE="4G" +#HEAP_NEWSIZE="800M" + +# Set this to control the amount of arenas per-thread in glibc +#export MALLOC_ARENA_MAX=4 + +# only calculate the size if it's not set manually +if [ "x$MAX_HEAP_SIZE" = "x" ] && [ "x$HEAP_NEWSIZE" = "x" -o $USING_G1 -eq 0 ]; then + calculate_heap_sizes +elif [ "x$MAX_HEAP_SIZE" = "x" ] || [ "x$HEAP_NEWSIZE" = "x" -a $USING_G1 -ne 0 ]; then + echo "please set or unset MAX_HEAP_SIZE and HEAP_NEWSIZE in pairs when using CMS GC (see cassandra-env.sh)" + exit 1 +fi + +if [ "x$MALLOC_ARENA_MAX" = "x" ] ; then + export MALLOC_ARENA_MAX=4 +fi + +# We only set -Xms and -Xmx if they were not defined on jvm-server.options file +# If defined, both Xmx and Xms should be defined together. +if [ $DEFINED_XMX -ne 0 ] && [ $DEFINED_XMS -ne 0 ]; then + JVM_OPTS="$JVM_OPTS -Xms${MAX_HEAP_SIZE}" + JVM_OPTS="$JVM_OPTS -Xmx${MAX_HEAP_SIZE}" +elif [ $DEFINED_XMX -ne 0 ] || [ $DEFINED_XMS -ne 0 ]; then + echo "Please set or unset -Xmx and -Xms flags in pairs on jvm-server.options file." + exit 1 +fi + +# We only set -Xmn flag if it was not defined in jvm-server.options file +# and if the CMS GC is being used +# If defined, both Xmn and Xmx should be defined together. +if [ $DEFINED_XMN -eq 0 ] && [ $DEFINED_XMX -ne 0 ]; then + echo "Please set or unset -Xmx and -Xmn flags in pairs on jvm-server.options file." + exit 1 +elif [ $DEFINED_XMN -ne 0 ] && [ $USING_CMS -eq 0 ]; then + JVM_OPTS="$JVM_OPTS -Xmn${HEAP_NEWSIZE}" +fi + +# We fail to start if -Xmn is used with G1 GC is being used +# See comments for -Xmn in jvm-server.options +if [ $DEFINED_XMN -eq 0 ] && [ $USING_G1 -eq 0 ]; then + echo "It is not recommended to set -Xmn with the G1 garbage collector. See comments for -Xmn in jvm-server.options for details." + exit 1 +fi + +if [ "$JVM_ARCH" = "64-Bit" ] && [ $USING_CMS -eq 0 ]; then + JVM_OPTS="$JVM_OPTS -XX:+UseCondCardMark" +fi + +# provides hints to the JIT compiler +JVM_OPTS="$JVM_OPTS -XX:CompileCommandFile=$CASSANDRA_CONF/hotspot_compiler" + +# add the jamm javaagent +JVM_OPTS="$JVM_OPTS -javaagent:$CASSANDRA_HOME/lib/jamm-0.3.2.jar" + +# set jvm HeapDumpPath with CASSANDRA_HEAPDUMP_DIR +if [ "x$CASSANDRA_HEAPDUMP_DIR" != "x" ]; then + JVM_OPTS="$JVM_OPTS -XX:HeapDumpPath=$CASSANDRA_HEAPDUMP_DIR/cassandra-`date +%s`-pid$$.hprof" +fi + +# stop the jvm on OutOfMemoryError as it can result in some data corruption +# uncomment the preferred option +# ExitOnOutOfMemoryError and CrashOnOutOfMemoryError require a JRE greater or equals to 1.7 update 101 or 1.8 update 92 +# For OnOutOfMemoryError we cannot use the JVM_OPTS variables because bash commands split words +# on white spaces without taking quotes into account +# JVM_OPTS="$JVM_OPTS -XX:+ExitOnOutOfMemoryError" +# JVM_OPTS="$JVM_OPTS -XX:+CrashOnOutOfMemoryError" +JVM_ON_OUT_OF_MEMORY_ERROR_OPT="-XX:OnOutOfMemoryError=kill -9 %p" + +# print an heap histogram on OutOfMemoryError +# JVM_OPTS="$JVM_OPTS -Dcassandra.printHeapHistogramOnOutOfMemoryError=true" + +# jmx: metrics and administration interface +# +# add this if you're having trouble connecting: +# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=" +# +# see +# https://blogs.oracle.com/jmxetc/entry/troubleshooting_connection_problems_in_jconsole +# for more on configuring JMX through firewalls, etc. (Short version: +# get it working with no firewall first.) +# +# Cassandra ships with JMX accessible *only* from localhost. +# To enable remote JMX connections, uncomment lines below +# with authentication and/or ssl enabled. See https://wiki.apache.org/cassandra/JmxSecurity +# +if [ "x$LOCAL_JMX" = "x" ]; then + LOCAL_JMX=yes +fi + +# Specifies the default port over which Cassandra will be available for +# JMX connections. +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +JMX_PORT="7199" + +if [ "$LOCAL_JMX" = "yes" ]; then + JVM_OPTS="$JVM_OPTS -Dcassandra.jmx.local.port=$JMX_PORT" + JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.authenticate=false" +else + JVM_OPTS="$JVM_OPTS -Dcassandra.jmx.remote.port=$JMX_PORT" + # if ssl is enabled the same port cannot be used for both jmx and rmi so either + # pick another value for this property or comment out to use a random port (though see CASSANDRA-7087 for origins) + JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.rmi.port=$JMX_PORT" + + # turn on JMX authentication. See below for further options + JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.authenticate=true" + + # jmx ssl options + #JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.ssl=true" + #JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.ssl.need.client.auth=true" + #JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.ssl.enabled.protocols=" + #JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.ssl.enabled.cipher.suites=" + #JVM_OPTS="$JVM_OPTS -Djavax.net.ssl.keyStore=/path/to/keystore" + #JVM_OPTS="$JVM_OPTS -Djavax.net.ssl.keyStorePassword=" + #JVM_OPTS="$JVM_OPTS -Djavax.net.ssl.trustStore=/path/to/truststore" + #JVM_OPTS="$JVM_OPTS -Djavax.net.ssl.trustStorePassword=" +fi + +# jmx authentication and authorization options. By default, auth is only +# activated for remote connections but they can also be enabled for local only JMX +## Basic file based authn & authz +JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.password.file=/etc/cassandra/jmxremote.password" +#JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.access.file=/etc/cassandra/jmxremote.access" +## Custom auth settings which can be used as alternatives to JMX's out of the box auth utilities. +## JAAS login modules can be used for authentication by uncommenting these two properties. +## Cassandra ships with a LoginModule implementation - org.apache.cassandra.auth.CassandraLoginModule - +## which delegates to the IAuthenticator configured in cassandra.yaml. See the sample JAAS configuration +## file cassandra-jaas.config +#JVM_OPTS="$JVM_OPTS -Dcassandra.jmx.remote.login.config=CassandraLogin" +#JVM_OPTS="$JVM_OPTS -Djava.security.auth.login.config=$CASSANDRA_CONF/cassandra-jaas.config" + +## Cassandra also ships with a helper for delegating JMX authz calls to the configured IAuthorizer, +## uncomment this to use it. Requires one of the two authentication options to be enabled +#JVM_OPTS="$JVM_OPTS -Dcassandra.jmx.authorizer=org.apache.cassandra.auth.jmx.AuthorizationProxy" + +# To use mx4j, an HTML interface for JMX, add mx4j-tools.jar to the lib/ +# directory. +# See http://cassandra.apache.org/doc/latest/operating/metrics.html#jmx +# By default mx4j listens on the broadcast_address, port 8081. Uncomment the following lines +# to control its listen address and port. +#MX4J_ADDRESS="127.0.0.1" +#MX4J_PORT="8081" + +# Cassandra uses SIGAR to capture OS metrics CASSANDRA-7838 +# for SIGAR we have to set the java.library.path +# to the location of the native libraries. +JVM_OPTS="$JVM_OPTS -Djava.library.path=$CASSANDRA_HOME/lib/sigar-bin" + +if [ "x$MX4J_ADDRESS" != "x" ]; then + if [[ "$MX4J_ADDRESS" == \-Dmx4jaddress* ]]; then + # Backward compatible with the older style #13578 + JVM_OPTS="$JVM_OPTS $MX4J_ADDRESS" + else + JVM_OPTS="$JVM_OPTS -Dmx4jaddress=$MX4J_ADDRESS" + fi +fi +if [ "x$MX4J_PORT" != "x" ]; then + if [[ "$MX4J_PORT" == \-Dmx4jport* ]]; then + # Backward compatible with the older style #13578 + JVM_OPTS="$JVM_OPTS $MX4J_PORT" + else + JVM_OPTS="$JVM_OPTS -Dmx4jport=$MX4J_PORT" + fi +fi + +JVM_OPTS="$JVM_OPTS $JVM_EXTRA_OPTS" + diff --git a/testfiles/4.1/cassandra.yaml b/testfiles/cassandra.yaml similarity index 100% rename from testfiles/4.1/cassandra.yaml rename to testfiles/cassandra.yaml diff --git a/testfiles/jvm-server.options b/testfiles/jvm-server.options new file mode 100644 index 0000000..028fffa --- /dev/null +++ b/testfiles/jvm-server.options @@ -0,0 +1,188 @@ +########################################################################### +# jvm-server.options # +# # +# - all flags defined here will be used by cassandra to startup the JVM # +# - one flag should be specified per line # +# - lines that do not start with '-' will be ignored # +# - only static flags are accepted (no variables or parameters) # +# - dynamic flags will be appended to these on cassandra-env # +# # +# See jvm8-server.options and jvm11-server.options for Java version # +# specific options. # +########################################################################### + +###################### +# STARTUP PARAMETERS # +###################### + +# Uncomment any of the following properties to enable specific startup parameters + +# In a multi-instance deployment, multiple Cassandra instances will independently assume that all +# CPU processors are available to it. This setting allows you to specify a smaller set of processors +# and perhaps have affinity. +#-Dcassandra.available_processors=number_of_processors + +# The directory location of the cassandra.yaml file. +#-Dcassandra.config=directory + +# Sets the initial partitioner token for a node the first time the node is started. +#-Dcassandra.initial_token=token + +# Set to false to start Cassandra on a node but not have the node join the cluster. +#-Dcassandra.join_ring=true|false + +# Set to false to clear all gossip state for the node on restart. Use when you have changed node +# information in cassandra.yaml (such as listen_address). +#-Dcassandra.load_ring_state=true|false + +# Enable pluggable metrics reporter. See Pluggable metrics reporting in Cassandra 2.0.2. +#-Dcassandra.metricsReporterConfigFile=file + +# Set the port on which the CQL native transport listens for clients. (Default: 9042) +#-Dcassandra.native_transport_port=port + +# Overrides the partitioner. (Default: org.apache.cassandra.dht.Murmur3Partitioner) +#-Dcassandra.partitioner=partitioner + +# To replace a node that has died, restart a new node in its place specifying the address of the +# dead node. The new node must not have any data in its data directory, that is, it must be in the +# same state as before bootstrapping. +#-Dcassandra.replace_address=listen_address or broadcast_address of dead node + +# Allow restoring specific tables from an archived commit log. +#-Dcassandra.replayList=table + +# Allows overriding of the default RING_DELAY (30000ms), which is the amount of time a node waits +# before joining the ring. +#-Dcassandra.ring_delay_ms=ms + +# Set the SSL port for encrypted communication. (Default: 7001) +#-Dcassandra.ssl_storage_port=port + +# Set the port for inter-node communication. (Default: 7000) +#-Dcassandra.storage_port=port + +# Set the default location for the trigger JARs. (Default: conf/triggers) +#-Dcassandra.triggers_dir=directory + +# For testing new compaction and compression strategies. It allows you to experiment with different +# strategies and benchmark write performance differences without affecting the production workload. +#-Dcassandra.write_survey=true + +# To disable configuration via JMX of auth caches (such as those for credentials, permissions and +# roles). This will mean those config options can only be set (persistently) in cassandra.yaml +# and will require a restart for new values to take effect. +#-Dcassandra.disable_auth_caches_remote_configuration=true + +# To disable dynamic calculation of the page size used when indexing an entire partition (during +# initial index build/rebuild). If set to true, the page size will be fixed to the default of +# 10000 rows per page. +#-Dcassandra.force_default_indexing_page_size=true + +# Imposes an upper bound on hint lifetime below the normal min gc_grace_seconds +#-Dcassandra.maxHintTTL=max_hint_ttl_in_seconds + +######################## +# GENERAL JVM SETTINGS # +######################## + +# enable assertions. highly suggested for correct application functionality. +-ea + +# disable assertions for net.openhft.** because it runs out of memory by design +# if enabled and run for more than just brief testing +-da:net.openhft... + +# enable thread priorities, primarily so we can give periodic tasks +# a lower priority to avoid interfering with client workload +-XX:+UseThreadPriorities + +# Enable heap-dump if there's an OOM +-XX:+HeapDumpOnOutOfMemoryError + +# Per-thread stack size. +-Xss256k + +# Make sure all memory is faulted and zeroed on startup. +# This helps prevent soft faults in containers and makes +# transparent hugepage allocation more effective. +-XX:+AlwaysPreTouch + +# Enable thread-local allocation blocks and allow the JVM to automatically +# resize them at runtime. +-XX:+UseTLAB +-XX:+ResizeTLAB +-XX:+UseNUMA + +# http://www.evanjones.ca/jvm-mmap-pause.html +-XX:+PerfDisableSharedMem + +# Prefer binding to IPv4 network intefaces (when net.ipv6.bindv6only=1). See +# http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6342561 (short version: +# comment out this entry to enable IPv6 support). +-Djava.net.preferIPv4Stack=true + +### Debug options + +# uncomment to enable flight recorder +#-XX:+UnlockCommercialFeatures +#-XX:+FlightRecorder + +# uncomment to have Cassandra JVM listen for remote debuggers/profilers on port 1414 +#-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1414 + +# uncomment to have Cassandra JVM log internal method compilation (developers only) +#-XX:+UnlockDiagnosticVMOptions +#-XX:+LogCompilation + +################# +# HEAP SETTINGS # +################# + +# Heap size is automatically calculated by cassandra-env based on this +# formula: max(min(1/2 ram, 1024MB), min(1/4 ram, 8GB)) +# That is: +# - calculate 1/2 ram and cap to 1024MB +# - calculate 1/4 ram and cap to 8192MB +# - pick the max +# +# For production use you may wish to adjust this for your environment. +# If that's the case, uncomment the -Xmx and Xms options below to override the +# automatic calculation of JVM heap memory. +# +# It is recommended to set min (-Xms) and max (-Xmx) heap sizes to +# the same value to avoid stop-the-world GC pauses during resize, and +# so that we can lock the heap in memory on startup to prevent any +# of it from being swapped out. +#-Xms4G +#-Xmx4G + +# Young generation size is automatically calculated by cassandra-env +# based on this formula: min(100 * num_cores, 1/4 * heap size) +# +# The main trade-off for the young generation is that the larger it +# is, the longer GC pause times will be. The shorter it is, the more +# expensive GC will be (usually). +# +# It is not recommended to set the young generation size if using the +# G1 GC, since that will override the target pause-time goal. +# More info: http://www.oracle.com/technetwork/articles/java/g1gc-1984535.html +# +# The example below assumes a modern 8-core+ machine for decent +# times. If in doubt, and if you do not particularly want to tweak, go +# 100 MB per physical CPU core. +#-Xmn800M + +################################### +# EXPIRATION DATE OVERFLOW POLICY # +################################### + +# Defines how to handle INSERT requests with TTL exceeding the maximum supported expiration date: +# * REJECT: this is the default policy and will reject any requests with expiration date timestamp +# after 2106-02-07T06:28:13+00:00 or 2038-01-19T03:14:06+00:00 depending on compatibility mode (<="nc" sstable formats) +# * CAP: any insert with TTL expiring after 2106-02-07T06:28:13+00:00 or 2038-01-19T03:14:06+00:00, +# depending on compatibility mode (<="nc" sstable formats), will expire on 2106-02-07T06:28:13+00:00 +# or 2038-01-19T03:14:06+00:00 and the client will receive a warning. +# * CAP_NOWARN: same as previous, except that the client warning will not be emitted. +# +#-Dcassandra.expiration_date_overflow_policy=REJECT From 20167d1b6eb86d3c5a0f342c943b19ca421d5ae4 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Mon, 19 Jun 2023 20:49:42 +0300 Subject: [PATCH 03/12] Read original configs from /cassandra-base-config --- Makefile | 3 ++- pkg/config/builder.go | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 488486f..9ad91fd 100644 --- a/Makefile +++ b/Makefile @@ -56,11 +56,12 @@ build: test ## Build kubectl-k8ssandra .PHONY: docker-build docker-build: ## Build k8ssandra-client docker image - docker buildx build --build-arg VERSION=${VERSION} -t ${IMG_LATEST} . --load -f cmd/kubectl-k8ssandra/Dockerfile + docker buildx build --build-arg VERSION=${VERSION} -t ${IMG_LATEST} -t ${IMG} . --load -f cmd/kubectl-k8ssandra/Dockerfile .PHONY: kind-load kind-load: ## Load k8ssandra-client:latest to kind kind load docker-image ${IMG_LATEST} + kind load docker-image ${IMG} ##@ Tools / Dependencies diff --git a/pkg/config/builder.go b/pkg/config/builder.go index 7bf8538..8162596 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -120,12 +120,13 @@ func parseNodeInfo() (*NodeInfo, error) { // findConfigFiles returns the path of config files in the cass-management-api (for Cassandra 4.1.x and up) func defaultConfigFileDir() string { // $CASSANDRA_CONF could modify this, but we override it in the mgmt-api - return "/opt/cassandra/conf" + return "/cassandra-base-config" + // return "/opt/cassandra/conf" } func outputConfigFileDir() string { // docker-entrypoint.sh will copy the files from here, so we need all the outputs to target this - return "/configs" + return "/config" } func createRackProperties(configInput *ConfigInput, nodeInfo *NodeInfo, sourceDir, targetDir string) error { From 4c350aedeba69ab4fdb981626e79a42a2998e962 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Tue, 20 Jun 2023 15:09:18 +0300 Subject: [PATCH 04/12] Add simplified jvm-server.options writer.. --- cmd/kubectl-k8ssandra/config/builder.go | 4 + pkg/config/builder.go | 96 ++++++++++++++++++++++- pkg/config/builder_test.go | 33 +++++++- pkg/config/metadata/jvm_server_options.go | 94 ++++++++++++++++++++++ pkg/config/types.go | 3 +- 5 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 pkg/config/metadata/jvm_server_options.go diff --git a/cmd/kubectl-k8ssandra/config/builder.go b/cmd/kubectl-k8ssandra/config/builder.go index 1add535..58842f9 100644 --- a/cmd/kubectl-k8ssandra/config/builder.go +++ b/cmd/kubectl-k8ssandra/config/builder.go @@ -52,12 +52,16 @@ func NewBuilderCmd(streams genericclioptions.IOStreams) *cobra.Command { } fl := cmd.Flags() + // TODO Add flags to control the input and the output (some of the inputs are from env variables) o.configFlags.AddFlags(fl) return cmd } // Complete parses the arguments and necessary flags to options func (c *builderOptions) Complete(cmd *cobra.Command, args []string) error { + // TODO Instead of pkg doing the Getenv parameters, we should probably do them here + // since it's related to the command line interface and shell. Makes it easier to + // refactor later to more sane input return nil } diff --git a/pkg/config/builder.go b/pkg/config/builder.go index 8162596..c8af764 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -1,15 +1,19 @@ package config import ( + "bufio" "context" "encoding/json" + "fmt" "net" "os" "path/filepath" "strconv" + "strings" "text/template" "github.com/adutra/goalesce" + "github.com/k8ssandra/k8ssandra-client/pkg/config/metadata" "gopkg.in/yaml.v3" ) @@ -63,7 +67,7 @@ func Build(ctx context.Context) error { } // Create jvm*-server.options - if err := createJVMOptions(configInput, outputConfigFileDir()); err != nil { + if err := createJVMOptions(configInput, defaultConfigFileDir(), outputConfigFileDir()); err != nil { return err } @@ -189,10 +193,98 @@ func createCassandraEnv(configInput *ConfigInput, targetDir string) error { return nil } -func createJVMOptions(configInput *ConfigInput, targetDir string) error { +func createJVMOptions(configInput *ConfigInput, sourceDir, targetDir string) error { + // Read the current jvm-server-options as []string, do linear search to replace the values with the inputs we get + optionsPath := filepath.Join(sourceDir, "jvm-server.options") + currentOptions, err := readJvmServerOptions(optionsPath) + if err != nil { + return err + } + + targetOptions := make([]string, 0, len(currentOptions)+len(configInput.ServerOptions)) + + if len(configInput.ServerOptions) > 0 { + // Parse the jvm-server-options + + if addOpts, found := configInput.ServerOptions["additional-jvm-opts"]; found { + // These should be appended.. + for _, v := range addOpts.([]interface{}) { + targetOptions = append(targetOptions, v.(string)) + } + } + + s := metadata.ServerOptions() + for k, v := range configInput.ServerOptions { + if k == "additional-jvm-opts" { + continue + } + + if outputVal, found := s[k]; found { + if match, _ := metadata.PrefixParser(outputVal); match { + targetOptions = append(targetOptions, fmt.Sprintf("%s%s", outputVal, v)) + } else { + targetOptions = append(targetOptions, fmt.Sprintf("%s=%s", outputVal, v)) + } + } + } + + } + + // Add current options, if they're not there.. +curOptions: + for _, v := range currentOptions { + for _, vT := range targetOptions { + // TODO This is not handling Xss etc right.. fix + if v == vT { + continue curOptions + } + } + targetOptions = append(targetOptions, v) + } + + targetFileT := filepath.Join(targetDir, "jvm-server.options") + fT, err := os.OpenFile(targetFileT, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0770) + if err != nil { + return err + } + + for _, v := range targetOptions { + _, err := fmt.Fprintf(fT, "%s\n", v) + if err != nil { + return err + } + } + + defer fT.Close() + return nil } +func readJvmServerOptions(path string) ([]string, error) { + options := make([]string, 0) + f, err := os.Open(path) + if err != nil { + return nil, err + } + + defer f.Close() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) // Avoid dual allocation from token -> string + + if !strings.HasPrefix(line, "#") && len(line) > 0 { + options = append(options, line) + } + } + + if err := scanner.Err(); err != nil { + return nil, err + } + + return options, nil +} + // cassandra.yaml related functions func createCassandraYaml(configInput *ConfigInput, nodeInfo *NodeInfo, sourceDir, targetDir string) error { diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index d37b639..e5d672c 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -12,7 +12,9 @@ import ( var existingConfig = ` { - "cassandra-env-sh": { + "jvm-server-options": { + "initial_heap_size": "512m", + "max_heap_size": "512m", "additional-jvm-opts": [ "-Dcassandra.system_distributed_replication=test-dc:1", "-Dcom.sun.management.jmxremote.authenticate=true" @@ -128,3 +130,32 @@ func TestRackProperties(t *testing.T) { // TODO Verify file data.. } + +func TestServerOptionsReading(t *testing.T) { + require := require.New(t) + propertiesDir := filepath.Join(envtest.RootDir(), "testfiles") + inputFile := filepath.Join(propertiesDir, "jvm-server.options") + s, err := readJvmServerOptions(inputFile) + require.NoError(err) + + for _, v := range s { + fmt.Printf("%s\n", v) + } +} + +func TestServerOptionsOutput(t *testing.T) { + require := require.New(t) + optionsDir := filepath.Join(envtest.RootDir(), "testfiles") + tempDir, err := os.MkdirTemp("", "client-test") + + fmt.Printf("tempDir: %s\n", tempDir) + require.NoError(err) + + // Create mandatory configs.. + t.Setenv("CONFIG_FILE_DATA", existingConfig) + configInput, err := parseConfigInput() + require.NoError(err) + require.NotNil(configInput) + + require.NoError(createJVMOptions(configInput, optionsDir, tempDir)) +} diff --git a/pkg/config/metadata/jvm_server_options.go b/pkg/config/metadata/jvm_server_options.go new file mode 100644 index 0000000..cfdb7fd --- /dev/null +++ b/pkg/config/metadata/jvm_server_options.go @@ -0,0 +1,94 @@ +// Code is generated with scripts/parse.py. DO NOT EDIT. Sadly, the script is lost in time.. +package metadata + +import( + "regexp" +) + +var jvm_server_options = map[string]Metadata{ + "-XX:+UnlockDiagnosticVMOptions": {Key: "unlock-diagnostic-vm-options", BuilderType: "boolean", DefaultValueString: "true"}, + "-Dcassandra.available_processors": {Key: "cassandra_available_processors", BuilderType: "int"}, + "-Dcassandra.config": {Key: "cassandra_config_directory", BuilderType: "string"}, + "-Dcassandra.initial_token": {Key: "cassandra_initial_token", BuilderType: "string"}, + "-Dcassandra.join_ring": {Key: "cassandra_join_ring", BuilderType: "boolean", DefaultValueString: "true"}, + "-Dcassandra.load_ring_state": {Key: "cassandra_load_ring_state", BuilderType: "boolean", DefaultValueString: "true"}, + "-Dcassandra.metricsReporterConfigFile": {Key: "cassandra_metrics_reporter_config_file", BuilderType: "string"}, + "-Dcassandra.replace_address": {Key: "cassandra_replace_address", BuilderType: "string"}, + "-Ddse.consistent_replace": {Key: "dse_consistent_replace", BuilderType: "string"}, + "-Ddse.consistent_replace.parallelism": {Key: "dse_consistent_replace_parallelism", BuilderType: "string"}, + "-Ddse.consistent_replace.retries": {Key: "dse_consistent_replace_retries", BuilderType: "string"}, + "-Ddse.consistent_replace.whitelist": {Key: "dse_consistent_replace_whitelist", BuilderType: "string"}, + "-Dcassandra.replayList": {Key: "cassandra_replay_list", BuilderType: "string"}, + "-Dcassandra.ring_delay_ms": {Key: "cassandra_ring_delay_ms", BuilderType: "int"}, + "-Dcassandra.triggers_dir": {Key: "cassandra_triggers_dir", BuilderType: "string"}, + "-Dcassandra.write_survey": {Key: "cassandra_write_survey", BuilderType: "boolean", DefaultValueString: "false"}, + "-Dcassandra.disable_auth_caches_remote_configuration": {Key: "cassandra_disable_auth_caches_remote_configuration", BuilderType: "boolean", DefaultValueString: "false"}, + "-Dcassandra.force_default_indexing_page_size": {Key: "cassandra_force_default_indexing_page_size", BuilderType: "boolean", DefaultValueString: "false"}, + "-Dcassandra.maxHintTTL": {Key: "cassandra_max_hint_ttl", BuilderType: "string"}, + "-XX:+UseThreadPriorities": {Key: "use_thread_priorities", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+HeapDumpOnOutOfMemoryError": {Key: "heap_dump_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "true"}, + "-Xss": {Key: "per_thread_stack_size", BuilderType: "string", DefaultValueString: "256k"}, + "-XX:StringTableSize": {Key: "string_table_size", BuilderType: "string", DefaultValueString: "1000003"}, + "-XX:+AlwaysPreTouch": {Key: "always_pre_touch", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+UseTLAB": {Key: "use_tlb", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+ResizeTLAB": {Key: "resize_tlb", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+UseNUMA": {Key: "use_numa", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+PerfDisableSharedMem": {Key: "perf_disable_shared_mem", BuilderType: "boolean", DefaultValueString: "true"}, + "-Djava.net.preferIPv4Stack": {Key: "java_net_prefer_ipv4_stack", BuilderType: "boolean", DefaultValueString: "true"}, + "-Dsun.nio.PageAlignDirectMemory": {Key: "page-align-direct-memory", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:-RestrictContended": {Key: "restrict-contended", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:GuaranteedSafepointInterval": {Key: "guaranteed-safepoint-interval", BuilderType: "string", DefaultValueString: "300000"}, + "-XX:-UseBiasedLocking": {Key: "use-biased-locking", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+DebugNonSafepoints": {Key: "debug-non-safepoints", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+PreserveFramePointer": {Key: "preserve-frame-pointer", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:+UnlockCommercialFeatures": {Key: "unlock_commercial_features", BuilderType: "boolean", DefaultValueString: "false"}, + "-XX:+FlightRecorder": {Key: "flight_recorder", BuilderType: "boolean", DefaultValueString: "false"}, + "-XX:+LogCompilation": {Key: "log_compilation", BuilderType: "boolean", DefaultValueString: "false"}, + "-Xms": {Key: "initial_heap_size", BuilderType: "string"}, + "-Xmx": {Key: "max_heap_size", BuilderType: "string"}, + "-Djdk.nio.maxCachedBufferSize": {Key: "jdk_nio_maxcachedbuffersize", BuilderType: "int", DefaultValueString: "1048576"}, + "-Dcassandra.expiration_date_overflow_policy": {Key: "cassandra_expiration_date_overflow_policy", BuilderType: "string"}, + "-Dio.netty.eventLoop.maxPendingTasks": {Key: "io_netty_eventloop_maxpendingtasks", BuilderType: "int", DefaultValueString: "65536"}, + "-XX:+CrashOnOutOfMemoryError": {Key: "crash_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "false"}, + "-XX:MaxDirectMemorySize": {Key: "max_direct_memory", BuilderType: "string"}, + "-Dcassandra.printHeapHistogramOnOutOfMemoryError": {Key: "print_heap_histogram_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "false"}, + "-XX:+ExitOnOutOfMemoryError": {Key: "exit_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "false"}, +} + +const ( + jvm_server_optionsPrefixExp = "^-Xss|^-Xms|^-Xmx" +) + +var ( + prefixMatcher = regexp.MustCompile(jvm_server_optionsPrefixExp) +) + +func ServerOptions() map[string]string { + // Inverses the above map until we can regenerate something nicer.. + m := make(map[string]string, len(jvm_server_options)) + for k, v := range jvm_server_options { + m[v.Key] = k + } + return m +} + +func PrefixParser(input string) (bool, string) { + // prefixMatcher := regexp.MustCompile(jvm_server_optionsPrefixExp) + subParts := prefixMatcher.FindStringSubmatchIndex(input) + if len(subParts) > 0 { + mapKey := input[subParts[0]:subParts[1]] + + return true, mapKey + } + + return false, "" +} + +type Metadata struct { + // omitEmpty bool // static_constant vs constant + Key string + BuilderType string // list, boolean, string, int => yaml rendering + DefaultValueString string + // DefaultValueInt int + // DefaultValueBool bool +} diff --git a/pkg/config/types.go b/pkg/config/types.go index 4f26151..a40226f 100644 --- a/pkg/config/types.go +++ b/pkg/config/types.go @@ -30,8 +30,9 @@ type ConfigInput struct { ClusterInfo ClusterInfo `json:"cluster-info"` DatacenterInfo DatacenterInfo `json:"datacenter-info"` CassYaml map[string]interface{} `json:"cassandra-yaml,omitempty"` + ServerOptions map[string]interface{} `json:"jvm-server-options,omitempty"` - // jvm-options parts.. + // At some point, parse the remaining unknown keys when we decide what to do with them.. } type ClusterInfo struct { From d7ca89cbc7892af79f6c84584e8979eb66f9b65f Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Mon, 26 Jun 2023 14:40:10 +0300 Subject: [PATCH 05/12] Add cassandra-env.sh processing --- pkg/config/builder.go | 49 ++++++++++++++++++++++++++++++++++---- pkg/config/builder_test.go | 24 +++++++++++++++++++ pkg/config/types.go | 7 ++++++ 3 files changed, 76 insertions(+), 4 deletions(-) diff --git a/pkg/config/builder.go b/pkg/config/builder.go index c8af764..4df8111 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -62,7 +62,7 @@ func Build(ctx context.Context) error { } // Create cassandra-env.sh - if err := createCassandraEnv(configInput, outputConfigFileDir()); err != nil { + if err := createCassandraEnv(configInput, defaultConfigFileDir(), outputConfigFileDir()); err != nil { return err } @@ -76,6 +76,9 @@ func Build(ctx context.Context) error { return err } + // TODO Do we need to do something with rest of the conf-files? + // At least we want jvm11-server.options also. What about logbacks? + return nil } @@ -187,9 +190,47 @@ func createRackProperties(configInput *ConfigInput, nodeInfo *NodeInfo, sourceDi return rackTemplate.Execute(fT, rt) } -func createCassandraEnv(configInput *ConfigInput, targetDir string) error { - // Modify cassandra-env.sh if it's in the jvm-options / jvm-server-options / additional-jvm-options? - // This probably needs a template that is used to ensure backwards compatibility +func createCassandraEnv(configInput *ConfigInput, sourceDir, targetDir string) error { + envPath := filepath.Join(sourceDir, "cassandra-env.sh") + f, err := os.ReadFile(envPath) + if err != nil { + return err + } + + targetFileT := filepath.Join(targetDir, "cassandra-env.sh") + fT, err := os.OpenFile(targetFileT, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0770) + if err != nil { + return err + } + + defer fT.Close() + + if configInput.CassandraEnv.MallocArenaMax > 0 { + if _, err := fmt.Fprintf(fT, "export MALLOC_ARENA_MAX=%d\n", configInput.CassandraEnv.MallocArenaMax); err != nil { + return err + } + } + + if configInput.CassandraEnv.HeapDumpDir != "" { + if _, err := fmt.Fprintf(fT, "export CASSANDRA_HEAPDUMP_DIR=%s\n", configInput.CassandraEnv.HeapDumpDir); err != nil { + return err + } + } + + if _, err = fT.Write(f); err != nil { + return err + } + + if _, err := fmt.Fprintf(fT, "\n"); err != nil { + return err + } + + for _, opt := range configInput.CassandraEnv.AdditionalOpts { + if _, err := fmt.Fprintf(fT, "JVM_OPTS=\"$JVM_OPTS %s\"\n", opt); err != nil { + return err + } + } + return nil } diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index e5d672c..3bc6f7a 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -12,6 +12,13 @@ import ( var existingConfig = ` { + "cassandra-env-sh": { + "malloc-arena-max": 8, + "additional-jvm-opts": [ + "-Dcassandra.system_distributed_replication=test-dc:1", + "-Dcom.sun.management.jmxremote.authenticate=true" + ] + }, "jvm-server-options": { "initial_heap_size": "512m", "max_heap_size": "512m", @@ -159,3 +166,20 @@ func TestServerOptionsOutput(t *testing.T) { require.NoError(createJVMOptions(configInput, optionsDir, tempDir)) } + +func TestCassandraEnv(t *testing.T) { + require := require.New(t) + envDir := filepath.Join(envtest.RootDir(), "testfiles") + tempDir, err := os.MkdirTemp("", "client-test") + + fmt.Printf("tempDir: %s\n", tempDir) + require.NoError(err) + + // Create mandatory configs.. + t.Setenv("CONFIG_FILE_DATA", existingConfig) + configInput, err := parseConfigInput() + require.NoError(err) + require.NotNil(configInput) + + require.NoError(createCassandraEnv(configInput, envDir, tempDir)) +} diff --git a/pkg/config/types.go b/pkg/config/types.go index a40226f..1e1b3a3 100644 --- a/pkg/config/types.go +++ b/pkg/config/types.go @@ -31,10 +31,17 @@ type ConfigInput struct { DatacenterInfo DatacenterInfo `json:"datacenter-info"` CassYaml map[string]interface{} `json:"cassandra-yaml,omitempty"` ServerOptions map[string]interface{} `json:"jvm-server-options,omitempty"` + CassandraEnv CassandraEnvOptions `json:"cassandra-env-sh,omitempty"` // At some point, parse the remaining unknown keys when we decide what to do with them.. } +type CassandraEnvOptions struct { + MallocArenaMax int `json:"malloc-arena-max,omitempty"` + HeapDumpDir string `json:"heap-dump-dir,omitempty"` + AdditionalOpts []string `json:"additional-jvm-opts,omitempty"` +} + type ClusterInfo struct { Name string `json:"name"` Seeds string `json:"seeds"` // comma separated list of seeds From e9418f5ca93ae7350e386eac477380e289d1779f Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Mon, 26 Jun 2023 15:19:16 +0300 Subject: [PATCH 06/12] Add support for jvm11-server.options and jvm17-server.options --- pkg/config/builder.go | 35 +++++- pkg/config/metadata/jvm_server_options.go | 17 ++- pkg/config/types.go | 12 +- testfiles/jvm11-server.options | 115 +++++++++++++++++++ testfiles/jvm17-server.options | 134 ++++++++++++++++++++++ 5 files changed, 301 insertions(+), 12 deletions(-) create mode 100644 testfiles/jvm11-server.options create mode 100644 testfiles/jvm17-server.options diff --git a/pkg/config/builder.go b/pkg/config/builder.go index 4df8111..23558f1 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -234,20 +234,35 @@ func createCassandraEnv(configInput *ConfigInput, sourceDir, targetDir string) e return nil } +// createJVMOptions writes all the jvm*-server.options func createJVMOptions(configInput *ConfigInput, sourceDir, targetDir string) error { + if err := createServerJVMOptions(configInput.ServerOptions11, "jvm-server.options", sourceDir, targetDir); err != nil { + return err + } + if err := createServerJVMOptions(configInput.ServerOptions11, "jvm11-server.options", sourceDir, targetDir); err != nil { + return err + } + if err := createServerJVMOptions(configInput.ServerOptions11, "jvm17-server.options", sourceDir, targetDir); err != nil { + return err + } + + return nil +} + +func createServerJVMOptions(options map[string]interface{}, filename, sourceDir, targetDir string) error { // Read the current jvm-server-options as []string, do linear search to replace the values with the inputs we get - optionsPath := filepath.Join(sourceDir, "jvm-server.options") + optionsPath := filepath.Join(sourceDir, filename) currentOptions, err := readJvmServerOptions(optionsPath) if err != nil { return err } - targetOptions := make([]string, 0, len(currentOptions)+len(configInput.ServerOptions)) + targetOptions := make([]string, 0, len(currentOptions)+len(options)) - if len(configInput.ServerOptions) > 0 { + if len(options) > 0 { // Parse the jvm-server-options - if addOpts, found := configInput.ServerOptions["additional-jvm-opts"]; found { + if addOpts, found := options["additional-jvm-opts"]; found { // These should be appended.. for _, v := range addOpts.([]interface{}) { targetOptions = append(targetOptions, v.(string)) @@ -255,7 +270,7 @@ func createJVMOptions(configInput *ConfigInput, sourceDir, targetDir string) err } s := metadata.ServerOptions() - for k, v := range configInput.ServerOptions { + for k, v := range options { if k == "additional-jvm-opts" { continue } @@ -283,7 +298,7 @@ curOptions: targetOptions = append(targetOptions, v) } - targetFileT := filepath.Join(targetDir, "jvm-server.options") + targetFileT := filepath.Join(targetDir, filename) fT, err := os.OpenFile(targetFileT, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0770) if err != nil { return err @@ -303,6 +318,14 @@ curOptions: func readJvmServerOptions(path string) ([]string, error) { options := make([]string, 0) + + if _, err := os.Stat(path); err != nil { + if os.IsNotExist(err) { + return make([]string, 0), nil + } + return nil, err + } + f, err := os.Open(path) if err != nil { return nil, err diff --git a/pkg/config/metadata/jvm_server_options.go b/pkg/config/metadata/jvm_server_options.go index cfdb7fd..a4f5012 100644 --- a/pkg/config/metadata/jvm_server_options.go +++ b/pkg/config/metadata/jvm_server_options.go @@ -1,7 +1,7 @@ // Code is generated with scripts/parse.py. DO NOT EDIT. Sadly, the script is lost in time.. package metadata -import( +import ( "regexp" ) @@ -55,6 +55,16 @@ var jvm_server_options = map[string]Metadata{ "-XX:+ExitOnOutOfMemoryError": {Key: "exit_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "false"}, } +var jvm11_server_options = map[string]Metadata{ + "-Djdk.attach.allowAttachSelf": {Key: "jdk_attach_allow_attach_self", BuilderType: "boolean", DefaultValueString: "true"}, + "-Dio.netty.tryReflectionSetAccessible": {Key: "io_netty_try_reflection_set_accessible", BuilderType: "boolean", DefaultValueString: "true"}, + "-XX:G1RSetUpdatingPauseTimePercent": {Key: "g1r_set_updating_pause_time_percent", BuilderType: "int", DefaultValueString: "5"}, + "-XX:MaxGCPauseMillis": {Key: "max_gc_pause_millis", BuilderType: "int", DefaultValueString: "500"}, + "-XX:InitiatingHeapOccupancyPercent": {Key: "initiating_heap_occupancy_percent", BuilderType: "int"}, + "-XX:ParallelGCThreads": {Key: "parallel_gc_threads", BuilderType: "int"}, + "-XX:ConcGCThreads": {Key: "conc_gc_threads", BuilderType: "int"}, +} + const ( jvm_server_optionsPrefixExp = "^-Xss|^-Xms|^-Xmx" ) @@ -69,6 +79,11 @@ func ServerOptions() map[string]string { for k, v := range jvm_server_options { m[v.Key] = k } + + for k, v := range jvm11_server_options { + m[v.Key] = k + } + return m } diff --git a/pkg/config/types.go b/pkg/config/types.go index 1e1b3a3..503eaf2 100644 --- a/pkg/config/types.go +++ b/pkg/config/types.go @@ -27,11 +27,13 @@ import "net" // From cass-operator JSON input type ConfigInput struct { - ClusterInfo ClusterInfo `json:"cluster-info"` - DatacenterInfo DatacenterInfo `json:"datacenter-info"` - CassYaml map[string]interface{} `json:"cassandra-yaml,omitempty"` - ServerOptions map[string]interface{} `json:"jvm-server-options,omitempty"` - CassandraEnv CassandraEnvOptions `json:"cassandra-env-sh,omitempty"` + ClusterInfo ClusterInfo `json:"cluster-info"` + DatacenterInfo DatacenterInfo `json:"datacenter-info"` + CassYaml map[string]interface{} `json:"cassandra-yaml,omitempty"` + ServerOptions map[string]interface{} `json:"jvm-server-options,omitempty"` + ServerOptions11 map[string]interface{} `json:"jvm11-server-options,omitempty"` + ServerOptions17 map[string]interface{} `json:"jvm17-server-options,omitempty"` + CassandraEnv CassandraEnvOptions `json:"cassandra-env-sh,omitempty"` // At some point, parse the remaining unknown keys when we decide what to do with them.. } diff --git a/testfiles/jvm11-server.options b/testfiles/jvm11-server.options new file mode 100644 index 0000000..5fd1f26 --- /dev/null +++ b/testfiles/jvm11-server.options @@ -0,0 +1,115 @@ +########################################################################### +# jvm11-server.options # +# # +# See jvm-server.options. This file is specific for Java 11 and newer. # +########################################################################### + + +######################## +# GENERAL JVM SETTINGS # +######################## + +# Disable biased locking as it does not benefit Cassandra. +-XX:-UseBiasedLocking + + +################# +# GC SETTINGS # +################# + + + +### CMS Settings +##-XX:+UseConcMarkSweepGC +##-XX:+CMSParallelRemarkEnabled +##-XX:SurvivorRatio=8 +##-XX:MaxTenuringThreshold=1 +##-XX:CMSInitiatingOccupancyFraction=75 +##-XX:+UseCMSInitiatingOccupancyOnly +##-XX:CMSWaitDuration=10000 +##-XX:+CMSParallelInitialMarkEnabled +##-XX:+CMSEdenChunksRecordAlways +## some JVMs will fill up their heap when accessed via JMX, see CASSANDRA-6541 +##-XX:+CMSClassUnloadingEnabled + + + +### G1 Settings +## Use the Hotspot garbage-first collector. +-XX:+UseG1GC +-XX:+ParallelRefProcEnabled +-XX:MaxTenuringThreshold=1 +-XX:G1HeapRegionSize=16m + +# +## Have the JVM do less remembered set work during STW, instead +## preferring concurrent GC. Reduces p99.9 latency. +-XX:G1RSetUpdatingPauseTimePercent=5 +# +## Main G1GC tunable: lowering the pause target will lower throughput and vise versa. +## 200ms is the JVM default and lowest viable setting +## 1000ms increases throughput. Keep it smaller than the timeouts in cassandra.yaml. +-XX:MaxGCPauseMillis=300 + +## Optional G1 Settings +# Save CPU time on large (>= 16GB) heaps by delaying region scanning +# until the heap is 70% full. The default in Hotspot 8u40 is 40%. +-XX:InitiatingHeapOccupancyPercent=70 + +# For systems with > 8 cores, the default ParallelGCThreads is 5/8 the number of logical cores. +# Otherwise equal to the number of cores when 8 or less. +# Machines with > 10 cores should try setting these to <= full cores. +#-XX:ParallelGCThreads=16 +# By default, ConcGCThreads is 1/4 of ParallelGCThreads. +# Setting both to the same value can reduce STW durations. +#-XX:ConcGCThreads=16 + + +### JPMS + +-Djdk.attach.allowAttachSelf=true +--add-exports java.base/jdk.internal.misc=ALL-UNNAMED +--add-exports java.base/jdk.internal.ref=ALL-UNNAMED +--add-exports java.base/jdk.internal.util=ALL-UNNAMED +--add-exports java.base/sun.nio.ch=ALL-UNNAMED +--add-exports java.management.rmi/com.sun.jmx.remote.internal.rmi=ALL-UNNAMED +--add-exports java.rmi/sun.rmi.registry=ALL-UNNAMED +--add-exports java.rmi/sun.rmi.server=ALL-UNNAMED +--add-exports java.sql/java.sql=ALL-UNNAMED + +--add-opens java.base/java.lang.module=ALL-UNNAMED +--add-opens java.base/jdk.internal.loader=ALL-UNNAMED +--add-opens java.base/jdk.internal.ref=ALL-UNNAMED +--add-opens java.base/jdk.internal.reflect=ALL-UNNAMED +--add-opens java.base/jdk.internal.math=ALL-UNNAMED +--add-opens java.base/jdk.internal.module=ALL-UNNAMED +--add-opens java.base/jdk.internal.util.jar=ALL-UNNAMED +--add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED + + +### GC logging options -- uncomment to enable + +# Java 11 (and newer) GC logging options: +# See description of https://bugs.openjdk.java.net/browse/JDK-8046148 for details about the syntax +# The following is the equivalent to -XX:+PrintGCDetails -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=10M +#-Xlog:gc=info,heap*=trace,age*=debug,safepoint=info,promotion*=trace:file=/var/log/cassandra/gc.log:time,uptime,pid,tid,level:filecount=10,filesize=10485760 + +# Notes for Java 8 migration: +# +# -XX:+PrintGCDetails maps to -Xlog:gc*:... - i.e. add a '*' after "gc" +# -XX:+PrintGCDateStamps maps to decorator 'time' +# +# -XX:+PrintHeapAtGC maps to 'heap' with level 'trace' +# -XX:+PrintTenuringDistribution maps to 'age' with level 'debug' +# -XX:+PrintGCApplicationStoppedTime maps to 'safepoint' with level 'info' +# -XX:+PrintPromotionFailure maps to 'promotion' with level 'trace' +# -XX:PrintFLSStatistics=1 maps to 'freelist' with level 'trace' + +### Netty Options + +# On Java >= 9 Netty requires the io.netty.tryReflectionSetAccessible system property to be set to true to enable +# creation of direct buffers using Unsafe. Without it, this falls back to ByteBuffer.allocateDirect which has +# inferior performance and risks exceeding MaxDirectMemory +-Dio.netty.tryReflectionSetAccessible=true + +# The newline in the end of file is intentional diff --git a/testfiles/jvm17-server.options b/testfiles/jvm17-server.options new file mode 100644 index 0000000..98a70a2 --- /dev/null +++ b/testfiles/jvm17-server.options @@ -0,0 +1,134 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +########################################################################### +# jvm17-server.options # +# # +# See jvm-server.options. This file is specific for Java 17 and newer. # +########################################################################### + +################# +# GC SETTINGS # +################# + + + +### G1 Settings +## Use the Hotspot garbage-first collector. +-XX:+UseG1GC +-XX:+ParallelRefProcEnabled +-XX:MaxTenuringThreshold=1 +-XX:G1HeapRegionSize=16m + +# +## Have the JVM do less remembered set work during STW, instead +## preferring concurrent GC. Reduces p99.9 latency. +-XX:G1RSetUpdatingPauseTimePercent=5 +# +## Main G1GC tunable: lowering the pause target will lower throughput and vise versa. +## 200ms is the JVM default and lowest viable setting +## 1000ms increases throughput. Keep it smaller than the timeouts in cassandra.yaml. +-XX:MaxGCPauseMillis=300 + +## Optional G1 Settings +# Save CPU time on large (>= 16GB) heaps by delaying region scanning +# until the heap is 70% full. The default in Hotspot 8u40 is 40%. +-XX:InitiatingHeapOccupancyPercent=70 + +# For systems with > 8 cores, the default ParallelGCThreads is 5/8 the number of logical cores. +# Otherwise equal to the number of cores when 8 or less. +# Machines with > 10 cores should try setting these to <= full cores. +#-XX:ParallelGCThreads=16 +# By default, ConcGCThreads is 1/4 of ParallelGCThreads. +# Setting both to the same value can reduce STW durations. +#-XX:ConcGCThreads=16 + + +### JPMS + +-Djdk.attach.allowAttachSelf=true +--add-exports java.base/jdk.internal.misc=ALL-UNNAMED +--add-exports java.base/jdk.internal.ref=ALL-UNNAMED +# https://chronicle.software/chronicle-support-java-17/ +--add-exports java.base/sun.nio.ch=ALL-UNNAMED +--add-exports java.management.rmi/com.sun.jmx.remote.internal.rmi=ALL-UNNAMED +--add-exports java.rmi/sun.rmi.registry=ALL-UNNAMED +--add-exports java.rmi/sun.rmi.server=ALL-UNNAMED +--add-exports java.sql/java.sql=ALL-UNNAMED + +#chronicle, AuditLog https://chronicle.software/chronicle-support-java-17/ +--add-exports java.base/java.lang.ref=ALL-UNNAMED +--add-exports java.base/jdk.internal.util=ALL-UNNAMED +--add-exports jdk.unsupported/sun.misc=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + +--add-opens java.base/java.lang.module=ALL-UNNAMED +--add-opens java.base/jdk.internal.loader=ALL-UNNAMED +--add-opens java.base/jdk.internal.ref=ALL-UNNAMED +--add-opens java.base/jdk.internal.reflect=ALL-UNNAMED +--add-opens java.base/jdk.internal.math=ALL-UNNAMED +--add-opens java.base/jdk.internal.module=ALL-UNNAMED +--add-opens java.base/jdk.internal.util.jar=ALL-UNNAMED +--add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED + +#to be addressed in CASSANDRA-17850 +--add-opens java.base/sun.nio.ch=ALL-UNNAMED +# https://chronicle.software/chronicle-support-java-17/ +--add-opens java.base/java.io=ALL-UNNAMED +--add-opens java.base/java.nio=ALL-UNNAMED +#to be addressed during jamm maintenance +--add-opens java.base/java.util.concurrent=ALL-UNNAMED +--add-opens java.base/java.util=ALL-UNNAMED +--add-opens java.base/java.util.concurrent.atomic=ALL-UNNAMED +# https://chronicle.software/chronicle-support-java-17/ explains also --add-opens java.base/java.util=ALL-UNNAMED, further to jamm +# many cqlsh tests fail if we do not open the below one - jamm and at org.apache.cassandra.net.Verb.getModifiersField(Verb.java:388) +# in-jvm tests +--add-opens java.base/java.lang=ALL-UNNAMED +#jamm +--add-opens java.base/java.math=ALL-UNNAMED +#in-jvm tests? plus # https://chronicle.software/chronicle-support-java-17/ +--add-opens java.base/java.lang.reflect=ALL-UNNAMED +#jamm post CASSANDRA-17199 +--add-opens java.base/java.net=ALL-UNNAMED + +### GC logging options -- uncomment to enable + +# Java 11 (and newer) GC logging options: +# See description of https://bugs.openjdk.java.net/browse/JDK-8046148 for details about the syntax +# The following is the equivalent to -XX:+PrintGCDetails -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=10M +#-Xlog:gc=info,heap*=trace,age*=debug,safepoint=info,promotion*=trace:file=/var/log/cassandra/gc.log:time,uptime,pid,tid,level:filecount=10,filesize=10485760 + +# Notes for Java 8 migration: +# +# -XX:+PrintGCDetails maps to -Xlog:gc*:... - i.e. add a '*' after "gc" +# -XX:+PrintGCDateStamps maps to decorator 'time' +# +# -XX:+PrintHeapAtGC maps to 'heap' with level 'trace' +# -XX:+PrintTenuringDistribution maps to 'age' with level 'debug' +# -XX:+PrintGCApplicationStoppedTime maps to 'safepoint' with level 'info' +# -XX:+PrintPromotionFailure maps to 'promotion' with level 'trace' +# -XX:PrintFLSStatistics=1 maps to 'freelist' with level 'trace' + +### Netty Options + +# On Java >= 9 Netty requires the io.netty.tryReflectionSetAccessible system property to be set to true to enable +# creation of direct buffers using Unsafe. Without it, this falls back to ByteBuffer.allocateDirect which has +# inferior performance and risks exceeding MaxDirectMemory +-Dio.netty.tryReflectionSetAccessible=true + +# The newline in the end of file is intentional From 9e1b73dfd7c09b2f49647fb2d83a01885e669c80 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Thu, 20 Jul 2023 18:49:28 +0300 Subject: [PATCH 07/12] Add better jvm*-server.options parsing. Detect duplicate keys, remove default GC settings (and push our own defaults if no other garbage_collector is not requested). --- go.mod | 1 + go.sum | 38 ++++++++ pkg/config/builder.go | 113 +++++++++++++++++++--- pkg/config/builder_test.go | 7 ++ pkg/config/metadata/jvm_server_options.go | 109 --------------------- pkg/config/types.go | 25 +++++ 6 files changed, 170 insertions(+), 123 deletions(-) delete mode 100644 pkg/config/metadata/jvm_server_options.go diff --git a/go.mod b/go.mod index 74028af..64ac800 100644 --- a/go.mod +++ b/go.mod @@ -35,6 +35,7 @@ require ( github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/beorn7/perks v1.0.1 // indirect + github.com/burmanm/definitions-parser v0.0.0-20230720114634-62c738b72e61 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chai2010/gettext-go v1.0.2 // indirect github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect diff --git a/go.sum b/go.sum index d6a4baf..920b70c 100644 --- a/go.sum +++ b/go.sum @@ -39,6 +39,10 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= +github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= +github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.0.0 h1:dtDWrepsVPfW9H/4y7dDgFc2MBUSeJhlaDtK13CxFlU= github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= @@ -61,7 +65,10 @@ github.com/Masterminds/squirrel v1.5.3 h1:YPpoceAcxuzIljlr5iWpNKaql7hLeG1KLSrhvd github.com/Masterminds/squirrel v1.5.3/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= github.com/Microsoft/go-winio v0.5.1 h1:aPJp2QD7OOrhO5tQXqQoGSJc+DjDtWTGLOmNyAm6FgY= github.com/Microsoft/hcsshim v0.9.3 h1:k371PzBuRrz2b+ebGuI2nVgVhgsVX60jMfSw80NECxo= +github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d h1:UrqY+r/OJnIp5u0s1SbQ8dVfLCZJsnvazdBP5hS4iRs= github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d h1:O47TZtmKaBkPubAQBONxtC61E7GPOLkGDhJDWChl17s= github.com/adutra/goalesce v0.0.0-20221124153206-5643f911003d/go.mod h1:tRDczOw8/ipMRMBrO3kvAWxqQNnVXglAzhIqrXmKRAg= @@ -72,6 +79,7 @@ github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hC github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535 h1:4daAzAu0S6Vi7/lbWECcX0j45yZReDZ56BQsrVBOEEY= github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= @@ -84,11 +92,19 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= +github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/bshuster-repo/logrus-logstash-hook v1.0.0 h1:e+C0SB5R1pu//O4MQ3f9cFuPGoOVeF2fE4Og9otCc70= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/bugsnag/bugsnag-go v0.0.0-20141110184014-b1d153021fcd h1:rFt+Y/IK1aEZkEHchZRSq9OQbsSzIT/OrI8YFFmRIng= github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b h1:otBG+dV+YK+Soembjv71DPz3uX/V/6MMlSyD9JBQ6kQ= github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0 h1:nvj0OLI3YqYXer/kZD8Ri1aaunCxIEsOst1BVJswV0o= +github.com/burmanm/definitions-parser v0.0.0-20230719133937-3df9f3deff6f h1:nqjRvPLE7PFK5CJeTEhtPlYivKcU9BhVePsR3SJd6Wo= +github.com/burmanm/definitions-parser v0.0.0-20230719133937-3df9f3deff6f/go.mod h1:pJnSicezmEGVRxj0BdymVxthDZK6TGMrNFjbwSbrFJQ= +github.com/burmanm/definitions-parser v0.0.0-20230720112505-8eaad361b445 h1:6clngNU52A+avSE+VU1i0IOR5aHjw4bbMVaLK0yj/U8= +github.com/burmanm/definitions-parser v0.0.0-20230720112505-8eaad361b445/go.mod h1:pJnSicezmEGVRxj0BdymVxthDZK6TGMrNFjbwSbrFJQ= +github.com/burmanm/definitions-parser v0.0.0-20230720114634-62c738b72e61 h1:JgGOw1bU6nCB3wlORn+1stQOGXlyig2djSvCk5rjoNg= +github.com/burmanm/definitions-parser v0.0.0-20230720114634-62c738b72e61/go.mod h1:pJnSicezmEGVRxj0BdymVxthDZK6TGMrNFjbwSbrFJQ= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -119,6 +135,7 @@ github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2 github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= github.com/containerd/containerd v1.6.6 h1:xJNPhbrmz8xAMDNoVjHy9YHtWwEQNS+CDkcIRh7t8Y0= github.com/containerd/containerd v1.6.6/go.mod h1:ZoP1geJldzCVY3Tonoz7b1IXk8rIX0Nltt5QE4OMNk0= +github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= @@ -152,6 +169,8 @@ github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDD github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1 h1:ZClxb8laGDf5arXfYcAtECDFgAgHklGI8CxgjHnXKJ4= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= +github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= +github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful/v3 v3.10.2 h1:hIovbnmBTLjHXkqEBUz3HGpXZdM7ZrE9fJIZIqlJLqE= github.com/emicklei/go-restful/v3 v3.10.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -177,6 +196,7 @@ github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/flowstack/go-jsonschema v0.1.1/go.mod h1:yL7fNggx1o8rm9RlgXv7hTBWxdBM0rVwpMwimd3F3N0= +github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= @@ -194,6 +214,7 @@ github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2 github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= 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= @@ -314,6 +335,8 @@ github.com/gosuri/uitable v0.0.4 h1:IG2xLKRvErL3uhY6e1BylFzG+aJiwQviDDTfOKeKTpY= github.com/gosuri/uitable v0.0.4/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= @@ -349,8 +372,10 @@ github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLf github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= +github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= 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/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -360,6 +385,7 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1 github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/k8ssandra/cass-operator v1.15.1-0.20230613083330-58dc7268f372 h1:2tpKA5pSwf8F1br1GzUf2BuvkNZjF5WJnTjkqlPdB3M= github.com/k8ssandra/cass-operator v1.15.1-0.20230613083330-58dc7268f372/go.mod h1:SweDRjqzPDrZsGzoN0b/YzWKk+DCy0+4htELKRoMVI8= github.com/karrick/godirwalk v1.16.1 h1:DynhcF+bztK8gooS0+NDJFrdNZjJ3gzVzC545UNA9iw= @@ -390,6 +416,7 @@ github.com/lib/pq v1.10.6 h1:jbk+ZieJ0D7EVGJYpL9QTz7/YW6UHbmdnZWYyK5cdBs= github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= +github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= @@ -470,6 +497,9 @@ github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4AN 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/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo/v2 v2.9.4 h1:xR7vG4IXt5RWx6FfIjyAtsoMAtnc3C/rFXBBd2AjZwE= @@ -522,12 +552,14 @@ github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6po github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rubenv/sql-migrate v1.1.1 h1:haR5Hn8hbW9/SpAICrXoZqXnywS7Q5WijwkQENPeNWY= github.com/rubenv/sql-migrate v1.1.1/go.mod h1:/7TZymwxN8VWumcIxw1jjHEcR1djpdkMHQPT4FWdnbQ= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= +github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= @@ -536,6 +568,7 @@ github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= @@ -567,12 +600,14 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xlab/treeprint v1.1.0 h1:G/1DjNkPpfZCFt9CSh6b5/nY4VimlbHF3Rh4obvtzDk= github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -586,6 +621,7 @@ github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50 h1:hlE8//ciYMzt github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f h1:ERexzlUfuTvpE74urLSbIQW0Z/6hF9t8U4NsJLaioAY= github.com/ziutek/mymysql v1.5.4 h1:GB0qdRGsTwQSBVYuVShFBKaXSnSnYYC2d9knnE1LHFs= github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0= +go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= @@ -984,6 +1020,7 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -999,6 +1036,7 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= +gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= helm.sh/helm/v3 v3.9.4 h1:TCI1QhJUeLVOdccfdw+vnSEO3Td6gNqibptB04QtExY= helm.sh/helm/v3 v3.9.4/go.mod h1:3eaWAIqzvlRSD06gR9MMwmp2KBKwlu9av1/1BZpjeWY= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/pkg/config/builder.go b/pkg/config/builder.go index 23558f1..d58860d 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -8,12 +8,14 @@ import ( "net" "os" "path/filepath" + "regexp" "strconv" "strings" "text/template" "github.com/adutra/goalesce" - "github.com/k8ssandra/k8ssandra-client/pkg/config/metadata" + metadata "github.com/burmanm/definitions-parser/pkg/types" + gentypes "github.com/burmanm/definitions-parser/pkg/types/generated" "gopkg.in/yaml.v3" ) @@ -44,6 +46,10 @@ import ( // TODO Could we also refactor the POD_IP / HOST_IP processing? Why can't the decision happen in cass-operator? */ +var ( + prefixRegexp = regexp.MustCompile(gentypes.JvmServerOptionsPrefixExp) +) + func Build(ctx context.Context) error { // Parse input from cass-operator configInput, err := parseConfigInput() @@ -76,9 +82,6 @@ func Build(ctx context.Context) error { return err } - // TODO Do we need to do something with rest of the conf-files? - // At least we want jvm11-server.options also. What about logbacks? - return nil } @@ -236,19 +239,31 @@ func createCassandraEnv(configInput *ConfigInput, sourceDir, targetDir string) e // createJVMOptions writes all the jvm*-server.options func createJVMOptions(configInput *ConfigInput, sourceDir, targetDir string) error { - if err := createServerJVMOptions(configInput.ServerOptions11, "jvm-server.options", sourceDir, targetDir); err != nil { + if err := createServerJVMOptions(configInput.ServerOptions, "jvm-server.options", sourceDir, targetDir); err != nil { return err } if err := createServerJVMOptions(configInput.ServerOptions11, "jvm11-server.options", sourceDir, targetDir); err != nil { return err } - if err := createServerJVMOptions(configInput.ServerOptions11, "jvm17-server.options", sourceDir, targetDir); err != nil { + if err := createServerJVMOptions(configInput.ServerOptions17, "jvm17-server.options", sourceDir, targetDir); err != nil { return err } return nil } +func optionsFilenameToMap(filename string) map[string]metadata.Metadata { + switch filename { + case "jvm-server.options": + return gentypes.JvmServerOptionsPrefix + case "jvm11-server.options": + return gentypes.Jvm11ServerOptionsPrefix + default: + // JVM17 and newer do not have alias tables in the EDNs + return make(map[string]metadata.Metadata, 0) + } +} + func createServerJVMOptions(options map[string]interface{}, filename, sourceDir, targetDir string) error { // Read the current jvm-server-options as []string, do linear search to replace the values with the inputs we get optionsPath := filepath.Join(sourceDir, filename) @@ -261,7 +276,6 @@ func createServerJVMOptions(options map[string]interface{}, filename, sourceDir, if len(options) > 0 { // Parse the jvm-server-options - if addOpts, found := options["additional-jvm-opts"]; found { // These should be appended.. for _, v := range addOpts.([]interface{}) { @@ -269,28 +283,57 @@ func createServerJVMOptions(options map[string]interface{}, filename, sourceDir, } } - s := metadata.ServerOptions() + s := optionsFilenameToMap(filename) for k, v := range options { - if k == "additional-jvm-opts" { + if k == "additional-jvm-opts" || k == "garbage_collector" { continue } if outputVal, found := s[k]; found { - if match, _ := metadata.PrefixParser(outputVal); match { - targetOptions = append(targetOptions, fmt.Sprintf("%s%s", outputVal, v)) - } else { - targetOptions = append(targetOptions, fmt.Sprintf("%s=%s", outputVal, v)) + if outputVal.ValueType == metadata.TemplateValue { + // We need another process here.. + continue } + targetOptions = append(targetOptions, outputVal.Output(v.(string))) } } + } + + if options == nil { + options = make(map[string]interface{}) + } + + if filename == "jvm11-server.options" { + if _, found := options["garbage_collector"]; !found { + // This is only applicable to JVM11 options.. + options["garbage_collector"] = "G1GC" + } + if gcOpts, found := options["garbage_collector"]; found { + // Get the GC options + currentOptions = append(currentOptions, getGCOptions(gcOpts.(string))...) + } } // Add current options, if they're not there.. curOptions: for _, v := range currentOptions { + curValueLoc := strings.Index(v, "=") + for _, vT := range targetOptions { - // TODO This is not handling Xss etc right.. fix + if suppressed, prefix := prefixMatcher(v); suppressed { + if strings.HasPrefix(vT, prefix) { + continue curOptions + } + } + + // Different value should not mean we can't compare + targetValueLoc := strings.Index(vT, "=") + if targetValueLoc > 0 && curValueLoc > 0 { + vT = vT[:targetValueLoc] + v = v[:curValueLoc] + } + if v == vT { continue curOptions } @@ -316,6 +359,31 @@ curOptions: return nil } +func getGCOptions(gcName string) []string { + switch gcName { + case "G1GC": + return defaultG1Settings + case "CMS": + return defaultCMSSettings + case "Shenandoah": + return []string{"-XX:+UseShenandoahGC"} + case "ZGC": + return []string{"-XX:+UseZGC"} + default: + // User needs to define all the settings + return []string{} + } +} + +func prefixMatcher(value string) (bool, string) { + // r := regexp.MustCompile(gentypes.JvmServerOptionsPrefixExp) + parts := prefixRegexp.FindStringSubmatch(value) + if parts != nil { + return true, parts[0] + } + return false, "" +} + func readJvmServerOptions(path string) ([]string, error) { options := make([]string, 0) @@ -333,11 +401,28 @@ func readJvmServerOptions(path string) ([]string, error) { defer f.Close() + runningSegment := false + currentSegment := "" + scanner := bufio.NewScanner(f) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) // Avoid dual allocation from token -> string + // Try to detect GC settings + if strings.HasPrefix(line, "### ") { + segmentName, _ := strings.CutPrefix(line, "### ") + if !runningSegment { + currentSegment = segmentName + runningSegment = true + } else { + currentSegment = segmentName + } + } + if !strings.HasPrefix(line, "#") && len(line) > 0 { + if runningSegment && (strings.HasPrefix(currentSegment, "G1") || strings.HasPrefix(currentSegment, "CMS")) { + continue + } options = append(options, line) } } diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index 3bc6f7a..62f2a71 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -22,11 +22,18 @@ var existingConfig = ` "jvm-server-options": { "initial_heap_size": "512m", "max_heap_size": "512m", + "per_thread_stack_size": "384k", "additional-jvm-opts": [ "-Dcassandra.system_distributed_replication=test-dc:1", "-Dcom.sun.management.jmxremote.authenticate=true" ] }, + "jvm11-server-options": { + "g1r_set_updating_pause_time_percent": "6", + "additional-jvm-opts": [ + "-XX:MaxGCPauseMillis=350" + ] + }, "cassandra-yaml": { "authenticator": "PasswordAuthenticator", "authorizer": "CassandraAuthorizer", diff --git a/pkg/config/metadata/jvm_server_options.go b/pkg/config/metadata/jvm_server_options.go deleted file mode 100644 index a4f5012..0000000 --- a/pkg/config/metadata/jvm_server_options.go +++ /dev/null @@ -1,109 +0,0 @@ -// Code is generated with scripts/parse.py. DO NOT EDIT. Sadly, the script is lost in time.. -package metadata - -import ( - "regexp" -) - -var jvm_server_options = map[string]Metadata{ - "-XX:+UnlockDiagnosticVMOptions": {Key: "unlock-diagnostic-vm-options", BuilderType: "boolean", DefaultValueString: "true"}, - "-Dcassandra.available_processors": {Key: "cassandra_available_processors", BuilderType: "int"}, - "-Dcassandra.config": {Key: "cassandra_config_directory", BuilderType: "string"}, - "-Dcassandra.initial_token": {Key: "cassandra_initial_token", BuilderType: "string"}, - "-Dcassandra.join_ring": {Key: "cassandra_join_ring", BuilderType: "boolean", DefaultValueString: "true"}, - "-Dcassandra.load_ring_state": {Key: "cassandra_load_ring_state", BuilderType: "boolean", DefaultValueString: "true"}, - "-Dcassandra.metricsReporterConfigFile": {Key: "cassandra_metrics_reporter_config_file", BuilderType: "string"}, - "-Dcassandra.replace_address": {Key: "cassandra_replace_address", BuilderType: "string"}, - "-Ddse.consistent_replace": {Key: "dse_consistent_replace", BuilderType: "string"}, - "-Ddse.consistent_replace.parallelism": {Key: "dse_consistent_replace_parallelism", BuilderType: "string"}, - "-Ddse.consistent_replace.retries": {Key: "dse_consistent_replace_retries", BuilderType: "string"}, - "-Ddse.consistent_replace.whitelist": {Key: "dse_consistent_replace_whitelist", BuilderType: "string"}, - "-Dcassandra.replayList": {Key: "cassandra_replay_list", BuilderType: "string"}, - "-Dcassandra.ring_delay_ms": {Key: "cassandra_ring_delay_ms", BuilderType: "int"}, - "-Dcassandra.triggers_dir": {Key: "cassandra_triggers_dir", BuilderType: "string"}, - "-Dcassandra.write_survey": {Key: "cassandra_write_survey", BuilderType: "boolean", DefaultValueString: "false"}, - "-Dcassandra.disable_auth_caches_remote_configuration": {Key: "cassandra_disable_auth_caches_remote_configuration", BuilderType: "boolean", DefaultValueString: "false"}, - "-Dcassandra.force_default_indexing_page_size": {Key: "cassandra_force_default_indexing_page_size", BuilderType: "boolean", DefaultValueString: "false"}, - "-Dcassandra.maxHintTTL": {Key: "cassandra_max_hint_ttl", BuilderType: "string"}, - "-XX:+UseThreadPriorities": {Key: "use_thread_priorities", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+HeapDumpOnOutOfMemoryError": {Key: "heap_dump_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "true"}, - "-Xss": {Key: "per_thread_stack_size", BuilderType: "string", DefaultValueString: "256k"}, - "-XX:StringTableSize": {Key: "string_table_size", BuilderType: "string", DefaultValueString: "1000003"}, - "-XX:+AlwaysPreTouch": {Key: "always_pre_touch", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+UseTLAB": {Key: "use_tlb", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+ResizeTLAB": {Key: "resize_tlb", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+UseNUMA": {Key: "use_numa", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+PerfDisableSharedMem": {Key: "perf_disable_shared_mem", BuilderType: "boolean", DefaultValueString: "true"}, - "-Djava.net.preferIPv4Stack": {Key: "java_net_prefer_ipv4_stack", BuilderType: "boolean", DefaultValueString: "true"}, - "-Dsun.nio.PageAlignDirectMemory": {Key: "page-align-direct-memory", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:-RestrictContended": {Key: "restrict-contended", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:GuaranteedSafepointInterval": {Key: "guaranteed-safepoint-interval", BuilderType: "string", DefaultValueString: "300000"}, - "-XX:-UseBiasedLocking": {Key: "use-biased-locking", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+DebugNonSafepoints": {Key: "debug-non-safepoints", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+PreserveFramePointer": {Key: "preserve-frame-pointer", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:+UnlockCommercialFeatures": {Key: "unlock_commercial_features", BuilderType: "boolean", DefaultValueString: "false"}, - "-XX:+FlightRecorder": {Key: "flight_recorder", BuilderType: "boolean", DefaultValueString: "false"}, - "-XX:+LogCompilation": {Key: "log_compilation", BuilderType: "boolean", DefaultValueString: "false"}, - "-Xms": {Key: "initial_heap_size", BuilderType: "string"}, - "-Xmx": {Key: "max_heap_size", BuilderType: "string"}, - "-Djdk.nio.maxCachedBufferSize": {Key: "jdk_nio_maxcachedbuffersize", BuilderType: "int", DefaultValueString: "1048576"}, - "-Dcassandra.expiration_date_overflow_policy": {Key: "cassandra_expiration_date_overflow_policy", BuilderType: "string"}, - "-Dio.netty.eventLoop.maxPendingTasks": {Key: "io_netty_eventloop_maxpendingtasks", BuilderType: "int", DefaultValueString: "65536"}, - "-XX:+CrashOnOutOfMemoryError": {Key: "crash_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "false"}, - "-XX:MaxDirectMemorySize": {Key: "max_direct_memory", BuilderType: "string"}, - "-Dcassandra.printHeapHistogramOnOutOfMemoryError": {Key: "print_heap_histogram_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "false"}, - "-XX:+ExitOnOutOfMemoryError": {Key: "exit_on_out_of_memory_error", BuilderType: "boolean", DefaultValueString: "false"}, -} - -var jvm11_server_options = map[string]Metadata{ - "-Djdk.attach.allowAttachSelf": {Key: "jdk_attach_allow_attach_self", BuilderType: "boolean", DefaultValueString: "true"}, - "-Dio.netty.tryReflectionSetAccessible": {Key: "io_netty_try_reflection_set_accessible", BuilderType: "boolean", DefaultValueString: "true"}, - "-XX:G1RSetUpdatingPauseTimePercent": {Key: "g1r_set_updating_pause_time_percent", BuilderType: "int", DefaultValueString: "5"}, - "-XX:MaxGCPauseMillis": {Key: "max_gc_pause_millis", BuilderType: "int", DefaultValueString: "500"}, - "-XX:InitiatingHeapOccupancyPercent": {Key: "initiating_heap_occupancy_percent", BuilderType: "int"}, - "-XX:ParallelGCThreads": {Key: "parallel_gc_threads", BuilderType: "int"}, - "-XX:ConcGCThreads": {Key: "conc_gc_threads", BuilderType: "int"}, -} - -const ( - jvm_server_optionsPrefixExp = "^-Xss|^-Xms|^-Xmx" -) - -var ( - prefixMatcher = regexp.MustCompile(jvm_server_optionsPrefixExp) -) - -func ServerOptions() map[string]string { - // Inverses the above map until we can regenerate something nicer.. - m := make(map[string]string, len(jvm_server_options)) - for k, v := range jvm_server_options { - m[v.Key] = k - } - - for k, v := range jvm11_server_options { - m[v.Key] = k - } - - return m -} - -func PrefixParser(input string) (bool, string) { - // prefixMatcher := regexp.MustCompile(jvm_server_optionsPrefixExp) - subParts := prefixMatcher.FindStringSubmatchIndex(input) - if len(subParts) > 0 { - mapKey := input[subParts[0]:subParts[1]] - - return true, mapKey - } - - return false, "" -} - -type Metadata struct { - // omitEmpty bool // static_constant vs constant - Key string - BuilderType string // list, boolean, string, int => yaml rendering - DefaultValueString string - // DefaultValueInt int - // DefaultValueBool bool -} diff --git a/pkg/config/types.go b/pkg/config/types.go index 503eaf2..528d97b 100644 --- a/pkg/config/types.go +++ b/pkg/config/types.go @@ -65,3 +65,28 @@ type NodeInfo struct { Rack string IP net.IP } + +var ( + defaultG1Settings = []string{ + "-XX:+UseG1GC", + "-XX:+ParallelRefProcEnabled", + "-XX:MaxTenuringThreshold=1", + "-XX:G1HeapRegionSize=16m", + "-XX:G1RSetUpdatingPauseTimePercent=5", + "-XX:MaxGCPauseMillis=300", + "-XX:InitiatingHeapOccupancyPercent=70", + } + + defaultCMSSettings = []string{ + "-XX:+UseConcMarkSweepGC", + "-XX:+CMSParallelRemarkEnabled", + "-XX:SurvivorRatio=8", + "-XX:MaxTenuringThreshold=1", + "-XX:CMSInitiatingOccupancyFraction=75", + "-XX:+UseCMSInitiatingOccupancyOnly", + "-XX:CMSWaitDuration=10000", + "-XX:+CMSParallelInitialMarkEnabled", + "-XX:+CMSEdenChunksRecordAlways", + "-XX:+CMSClassUnloadingEnabled", + } +) From abc331464ff456e7bd6d215eec732820db6e787c Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Fri, 21 Jul 2023 14:36:49 +0300 Subject: [PATCH 08/12] Add automated tests for all subsections of processing, fix server-options missing some cases of rendering text after equal sign --- pkg/config/builder.go | 9 +- pkg/config/builder_test.go | 167 ++++++++++++++++++++++++++++++++----- 2 files changed, 153 insertions(+), 23 deletions(-) diff --git a/pkg/config/builder.go b/pkg/config/builder.go index d58860d..9a23ba4 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -327,14 +327,17 @@ curOptions: } } + vc := v + vTc := vT + // Different value should not mean we can't compare targetValueLoc := strings.Index(vT, "=") if targetValueLoc > 0 && curValueLoc > 0 { - vT = vT[:targetValueLoc] - v = v[:curValueLoc] + vTc = vTc[:targetValueLoc] + vc = vc[:curValueLoc] } - if v == vT { + if vc == vTc { continue curOptions } } diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index 62f2a71..5fd7f76 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -1,13 +1,14 @@ package config import ( - "fmt" + "bufio" "os" "path/filepath" "testing" "github.com/k8ssandra/k8ssandra-client/internal/envtest" "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" ) var existingConfig = ` @@ -47,7 +48,7 @@ var existingConfig = ` }, "datacenter-info": { "graph-enabled": 0, - "name": "dc1", + "name": "datacenter1", "solr-enabled": 0, "spark-enabled": 0 } @@ -101,8 +102,8 @@ func TestCassandraYamlWriting(t *testing.T) { require := require.New(t) cassYamlDir := filepath.Join(envtest.RootDir(), "testfiles") tempDir, err := os.MkdirTemp("", "client-test") + defer os.RemoveAll(tempDir) - fmt.Printf("tempDir: %s\n", tempDir) require.NoError(err) // Create mandatory configs.. @@ -118,15 +119,48 @@ func TestCassandraYamlWriting(t *testing.T) { require.NoError(createCassandraYaml(configInput, nodeInfo, cassYamlDir, tempDir)) - // TODO Read back and verify all our changes are there + yamlOrigPath := filepath.Join(cassYamlDir, "cassandra.yaml") + yamlPath := filepath.Join(tempDir, "cassandra.yaml") + + yamlOrigFile, err := os.ReadFile(yamlOrigPath) + require.NoError(err) + + yamlFile, err := os.ReadFile(yamlPath) + require.NoError(err) + + // Unmarshal, Marshal to remove all comments (and some fields if necessary) + cassandraYaml := make(map[string]interface{}) + require.NoError(yaml.Unmarshal(yamlFile, cassandraYaml)) + + cassandraOrigYaml := make(map[string]interface{}) + require.NoError(yaml.Unmarshal(yamlOrigFile, cassandraOrigYaml)) + + // Verify all the original keys are there (nothing was removed) + for k := range cassandraOrigYaml { + require.Contains(cassandraYaml, k) + } + + // Verify our k8ssandra overrides are set + seedProviders := cassandraYaml["seed_provider"].([]interface{}) + seedProvider := seedProviders[0].(map[string]interface{}) + require.Equal("org.apache.cassandra.locator.K8SeedProvider", seedProvider["class_name"]) + + listenIP := nodeInfo.IP.String() + require.Equal(listenIP, cassandraYaml["listen_address"]) + + // Verify our changed properties are there + require.Equal("PasswordAuthenticator", cassandraYaml["authenticator"]) + require.Equal("CassandraAuthorizer", cassandraYaml["authorizer"]) + require.Equal("CassandraRoleManager", cassandraYaml["role_manager"]) + require.Equal(256, cassandraYaml["num_tokens"]) + require.Equal(false, cassandraYaml["start_rpc"]) } func TestRackProperties(t *testing.T) { require := require.New(t) propertiesDir := filepath.Join(envtest.RootDir(), "testfiles") tempDir, err := os.MkdirTemp("", "client-test") - - fmt.Printf("tempDir: %s\n", tempDir) + defer os.RemoveAll(tempDir) require.NoError(err) // Create mandatory configs.. @@ -142,19 +176,11 @@ func TestRackProperties(t *testing.T) { require.NoError(createRackProperties(configInput, nodeInfo, propertiesDir, tempDir)) - // TODO Verify file data.. -} - -func TestServerOptionsReading(t *testing.T) { - require := require.New(t) - propertiesDir := filepath.Join(envtest.RootDir(), "testfiles") - inputFile := filepath.Join(propertiesDir, "jvm-server.options") - s, err := readJvmServerOptions(inputFile) + lines, err := readFileToLines(tempDir, "cassandra-rackdc.properties") require.NoError(err) - - for _, v := range s { - fmt.Printf("%s\n", v) - } + require.Equal(2, len(lines)) + require.Contains(lines, "dc=datacenter1") + require.Contains(lines, "rack=r1") } func TestServerOptionsOutput(t *testing.T) { @@ -162,7 +188,7 @@ func TestServerOptionsOutput(t *testing.T) { optionsDir := filepath.Join(envtest.RootDir(), "testfiles") tempDir, err := os.MkdirTemp("", "client-test") - fmt.Printf("tempDir: %s\n", tempDir) + defer os.RemoveAll(tempDir) require.NoError(err) // Create mandatory configs.. @@ -172,14 +198,83 @@ func TestServerOptionsOutput(t *testing.T) { require.NotNil(configInput) require.NoError(createJVMOptions(configInput, optionsDir, tempDir)) + + inputFile := filepath.Join(tempDir, "jvm-server.options") + inputFile11 := filepath.Join(tempDir, "jvm11-server.options") + + s, err := readJvmServerOptions(inputFile) + require.NoError(err) + + require.Contains(s, "-Xss384k") + require.NotContains(s, "-Xss256k") + + require.Contains(s, "-Xmx512m") + require.Contains(s, "-Xms512m") + require.Contains(s, "-Dcassandra.system_distributed_replication=test-dc:1") + require.Contains(s, "-Dcom.sun.management.jmxremote.authenticate=true") + + s11, err := readJvmServerOptions(inputFile11) + require.NoError(err) + + require.Contains(s11, "-XX:MaxGCPauseMillis=350") + require.NotContains(s11, "-XX:MaxGCPauseMillis=300") + require.Contains(s11, "-XX:G1RSetUpdatingPauseTimePercent=6") + require.NotContains(s11, "-XX:G1RSetUpdatingPauseTimePercent=5") + + for _, v := range defaultG1Settings { + if v == "-XX:G1RSetUpdatingPauseTimePercent=5" || v == "-XX:MaxGCPauseMillis=300" { + // Our config replaces these default values with new values, so they should not be here + require.NotContains(s11, v) + continue + } + require.Contains(s11, v) + } + + // Test empty also and check we get the default G1 settings + ci := &ConfigInput{} + tempDir2, err := os.MkdirTemp("", "client-test") + require.NoError(err) + defer os.RemoveAll(tempDir2) + require.NoError(createJVMOptions(ci, optionsDir, tempDir2)) + + inputFile11 = filepath.Join(tempDir2, "jvm11-server.options") + + s11, err = readJvmServerOptions(inputFile11) + require.NoError(err) + + for _, v := range defaultG1Settings { + require.Contains(s11, v) + } + + // Test CMS option also + ci = &ConfigInput{ + ServerOptions11: map[string]interface{}{ + "garbage_collector": "CMS", + }, + } + + tempDir3, err := os.MkdirTemp("", "client-test") + require.NoError(err) + defer os.RemoveAll(tempDir3) + require.NoError(createJVMOptions(ci, optionsDir, tempDir3)) + + inputFile11 = filepath.Join(tempDir3, "jvm11-server.options") + + s11, err = readJvmServerOptions(inputFile11) + require.NoError(err) + + for _, v := range defaultCMSSettings { + require.Contains(s11, v) + } + } func TestCassandraEnv(t *testing.T) { require := require.New(t) envDir := filepath.Join(envtest.RootDir(), "testfiles") tempDir, err := os.MkdirTemp("", "client-test") + defer os.RemoveAll(tempDir) - fmt.Printf("tempDir: %s\n", tempDir) require.NoError(err) // Create mandatory configs.. @@ -189,4 +284,36 @@ func TestCassandraEnv(t *testing.T) { require.NotNil(configInput) require.NoError(createCassandraEnv(configInput, envDir, tempDir)) + + // Verify output + lines, err := readFileToLines(tempDir, "cassandra-env.sh") + require.NoError(err) + + require.Contains(lines, "export MALLOC_ARENA_MAX=8") + require.Contains(lines, "JVM_OPTS=\"$JVM_OPTS -Dcassandra.system_distributed_replication=test-dc:1\"") + require.Contains(lines, "JVM_OPTS=\"$JVM_OPTS -Dcom.sun.management.jmxremote.authenticate=true\"") +} + +// readFileToLines is a small test helper, reads file to []string (per line). This version does not filter anything, not even whitespace. +func readFileToLines(dir, filename string) ([]string, error) { + outputFile := filepath.Join(dir, filename) + lines := make([]string, 0, 1) + + f, err := os.Open(outputFile) + if err != nil { + return nil, err + } + + defer f.Close() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + if err := scanner.Err(); err != nil { + return nil, err + } + + return lines, nil } From e8b164a243c9b3c65a01e41853efa0105a76b276 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Fri, 21 Jul 2023 14:53:35 +0300 Subject: [PATCH 09/12] Add the ability to override config input and output directories, add builder test to verify all files were written --- cmd/kubectl-k8ssandra/config/builder.go | 9 ++- pkg/config/builder.go | 77 +++++++++++-------------- pkg/config/builder_test.go | 42 +++++++++++++- 3 files changed, 81 insertions(+), 47 deletions(-) diff --git a/cmd/kubectl-k8ssandra/config/builder.go b/cmd/kubectl-k8ssandra/config/builder.go index 58842f9..8b4695c 100644 --- a/cmd/kubectl-k8ssandra/config/builder.go +++ b/cmd/kubectl-k8ssandra/config/builder.go @@ -19,6 +19,9 @@ var ( type builderOptions struct { configFlags *genericclioptions.ConfigFlags genericclioptions.IOStreams + + inputDir string + outputDir string } func newBuilderOptions(streams genericclioptions.IOStreams) *builderOptions { @@ -52,7 +55,8 @@ func NewBuilderCmd(streams genericclioptions.IOStreams) *cobra.Command { } fl := cmd.Flags() - // TODO Add flags to control the input and the output (some of the inputs are from env variables) + fl.StringVar(&o.inputDir, "input", "", "read config files from this directory instead of default") + fl.StringVar(&o.outputDir, "output", "", "write config files to this directory instead of default") o.configFlags.AddFlags(fl) return cmd } @@ -74,5 +78,6 @@ func (c *builderOptions) Validate() error { func (c *builderOptions) Run() error { ctx := context.Background() - return config.Build(ctx) + builder := config.NewBuilder(c.inputDir, c.outputDir) + return builder.Build(ctx) } diff --git a/pkg/config/builder.go b/pkg/config/builder.go index 9a23ba4..0f3b319 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -19,38 +19,41 @@ import ( "gopkg.in/yaml.v3" ) -/* - - Need to find the original Cassandra / DSE configuration (the path) in our images - - Merge given input with what we have there as a default - - - Merge certain keys to different files (only cassandra-yaml -> yamls) - - Rack information, cluster information etc - - Was there some other information we might want here? - - Merge JSON & YAML? -*/ - -/* - For NodeInfo struct, these are set by the cass-operator. - // TODO We did add some more also, add support for them? - // TODO Also, RACK_NAME and others could be moved to a JSON key which cass-operator could create.. - // TODO Do we need PRODUCT_VERSION for anything anymore? - - {:pod-ip (System/getenv "POD_IP") - :config-file-data (System/getenv "CONFIG_FILE_DATA") - :product-version (System/getenv "PRODUCT_VERSION") - :rack-name (System/getenv "RACK_NAME") - :product-name (or (System/getenv "PRODUCT_NAME") "dse") - :use-host-ip-for-broadcast (or (System/getenv "USE_HOST_IP_FOR_BROADCAST") "false") - :host-ip (System/getenv "HOST_IP") - - // TODO Could we also refactor the POD_IP / HOST_IP processing? Why can't the decision happen in cass-operator? -*/ +const ( + // $CASSANDRA_CONF could modify this, but we override it in the mgmt-api + defaultInputDir = "/cassandra-base-config" + + // docker-entrypoint.sh will copy the files from here, so we need all the outputs to target this + defaultOutputDir = "/config" +) + +type Builder struct { + configInputDir string + configOutputDir string +} + +func NewBuilder(overrideConfigInput, overrideConfigOutput string) *Builder { + b := &Builder{ + configInputDir: defaultInputDir, + configOutputDir: defaultOutputDir, + } + + if overrideConfigInput != "" { + b.configInputDir = overrideConfigInput + } + + if overrideConfigOutput != "" { + b.configOutputDir = overrideConfigOutput + } + + return b +} var ( prefixRegexp = regexp.MustCompile(gentypes.JvmServerOptionsPrefixExp) ) -func Build(ctx context.Context) error { +func (b *Builder) Build(ctx context.Context) error { // Parse input from cass-operator configInput, err := parseConfigInput() if err != nil { @@ -63,22 +66,22 @@ func Build(ctx context.Context) error { } // Create rack information - if err := createRackProperties(configInput, nodeInfo, defaultConfigFileDir(), outputConfigFileDir()); err != nil { + if err := createRackProperties(configInput, nodeInfo, b.configInputDir, b.configOutputDir); err != nil { return err } // Create cassandra-env.sh - if err := createCassandraEnv(configInput, defaultConfigFileDir(), outputConfigFileDir()); err != nil { + if err := createCassandraEnv(configInput, b.configInputDir, b.configOutputDir); err != nil { return err } // Create jvm*-server.options - if err := createJVMOptions(configInput, defaultConfigFileDir(), outputConfigFileDir()); err != nil { + if err := createJVMOptions(configInput, b.configInputDir, b.configOutputDir); err != nil { return err } // Create cassandra.yaml - if err := createCassandraYaml(configInput, nodeInfo, defaultConfigFileDir(), outputConfigFileDir()); err != nil { + if err := createCassandraYaml(configInput, nodeInfo, b.configInputDir, b.configOutputDir); err != nil { return err } @@ -127,18 +130,6 @@ func parseNodeInfo() (*NodeInfo, error) { return n, nil } -// findConfigFiles returns the path of config files in the cass-management-api (for Cassandra 4.1.x and up) -func defaultConfigFileDir() string { - // $CASSANDRA_CONF could modify this, but we override it in the mgmt-api - return "/cassandra-base-config" - // return "/opt/cassandra/conf" -} - -func outputConfigFileDir() string { - // docker-entrypoint.sh will copy the files from here, so we need all the outputs to target this - return "/config" -} - func createRackProperties(configInput *ConfigInput, nodeInfo *NodeInfo, sourceDir, targetDir string) error { // Write cassandra-rackdc.properties file with Datacenter and Rack information diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index 5fd7f76..630ef33 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -2,6 +2,7 @@ package config import ( "bufio" + "context" "os" "path/filepath" "testing" @@ -55,6 +56,13 @@ var existingConfig = ` } ` +func TestBuilderDefaults(t *testing.T) { + require := require.New(t) + builder := NewBuilder("", "") + require.Equal(defaultInputDir, builder.configInputDir) + require.Equal(defaultOutputDir, builder.configOutputDir) +} + func TestConfigInfoParsing(t *testing.T) { require := require.New(t) t.Setenv("CONFIG_FILE_DATA", existingConfig) @@ -98,14 +106,44 @@ func TestParseNodeInfo(t *testing.T) { require.Equal("10.0.0.1", nodeInfo.IP.String()) } -func TestCassandraYamlWriting(t *testing.T) { +func TestBuild(t *testing.T) { require := require.New(t) - cassYamlDir := filepath.Join(envtest.RootDir(), "testfiles") + t.Setenv("CONFIG_FILE_DATA", existingConfig) + inputDir := filepath.Join(envtest.RootDir(), "testfiles") tempDir, err := os.MkdirTemp("", "client-test") + require.NoError(err) defer os.RemoveAll(tempDir) + b := NewBuilder(inputDir, tempDir) + require.NoError(b.Build(context.TODO())) + + // Verify that all target files are there.. + entries, err := os.ReadDir(tempDir) + require.NoError(err) + + fileNames := make([]string, 0, len(entries)) + for _, v := range entries { + fileNames = append(fileNames, v.Name()) + f, err := v.Info() + require.NoError(err) + require.True(f.Size() > 0) + } + + require.Contains(fileNames, "cassandra-env.sh") + require.Contains(fileNames, "cassandra-rackdc.properties") + require.Contains(fileNames, "cassandra.yaml") + require.Contains(fileNames, "jvm-server.options") + require.Contains(fileNames, "jvm11-server.options") +} + +func TestCassandraYamlWriting(t *testing.T) { + require := require.New(t) + cassYamlDir := filepath.Join(envtest.RootDir(), "testfiles") + tempDir, err := os.MkdirTemp("", "client-test") require.NoError(err) + defer os.RemoveAll(tempDir) + // Create mandatory configs.. t.Setenv("CONFIG_FILE_DATA", existingConfig) configInput, err := parseConfigInput() From cfda014995778fc42fb36911e5d49ae5e1738b77 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Fri, 21 Jul 2023 16:25:26 +0300 Subject: [PATCH 10/12] Fix test --- pkg/config/builder_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index 630ef33..6c48bb6 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -74,7 +74,7 @@ func TestConfigInfoParsing(t *testing.T) { require.NotNil(configInput.DatacenterInfo) require.Equal("test", configInput.ClusterInfo.Name) - require.Equal("dc1", configInput.DatacenterInfo.Name) + require.Equal("datacenter1", configInput.DatacenterInfo.Name) } func TestParseNodeInfo(t *testing.T) { From 581b89df60a0d0695abfaee7fe87af363b0c9946 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Tue, 25 Jul 2023 16:10:31 +0300 Subject: [PATCH 11/12] Fix numeric evaluation to keep the original format --- pkg/config/builder.go | 9 ++-- pkg/config/builder_test.go | 90 +++++++++++++++++++++++++++++--------- 2 files changed, 75 insertions(+), 24 deletions(-) diff --git a/pkg/config/builder.go b/pkg/config/builder.go index 0f3b319..7deab68 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -93,7 +93,10 @@ func (b *Builder) Build(ctx context.Context) error { func parseConfigInput() (*ConfigInput, error) { configInputStr := os.Getenv("CONFIG_FILE_DATA") configInput := &ConfigInput{} - if err := json.Unmarshal([]byte(configInputStr), configInput); err != nil { + + d := json.NewDecoder(strings.NewReader(configInputStr)) + d.UseNumber() // This decodes the numbers as strings + if err := d.Decode(configInput); err != nil { return nil, err } @@ -285,7 +288,7 @@ func createServerJVMOptions(options map[string]interface{}, filename, sourceDir, // We need another process here.. continue } - targetOptions = append(targetOptions, outputVal.Output(v.(string))) + targetOptions = append(targetOptions, outputVal.Output(fmt.Sprintf("%v", v))) } } } @@ -302,7 +305,7 @@ func createServerJVMOptions(options map[string]interface{}, filename, sourceDir, if gcOpts, found := options["garbage_collector"]; found { // Get the GC options - currentOptions = append(currentOptions, getGCOptions(gcOpts.(string))...) + currentOptions = append(currentOptions, getGCOptions(fmt.Sprintf("%v", gcOpts))...) } } diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index 6c48bb6..cad721c 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -15,43 +15,68 @@ import ( var existingConfig = ` { "cassandra-env-sh": { - "malloc-arena-max": 8, - "additional-jvm-opts": [ + "malloc-arena-max": 8, + "additional-jvm-opts": [ "-Dcassandra.system_distributed_replication=test-dc:1", "-Dcom.sun.management.jmxremote.authenticate=true" - ] + ] }, "jvm-server-options": { - "initial_heap_size": "512m", - "max_heap_size": "512m", - "per_thread_stack_size": "384k", - "additional-jvm-opts": [ + "initial_heap_size": "512m", + "max_heap_size": "512m", + "per_thread_stack_size": "384k", + "additional-jvm-opts": [ "-Dcassandra.system_distributed_replication=test-dc:1", "-Dcom.sun.management.jmxremote.authenticate=true" - ] + ] }, "jvm11-server-options": { "g1r_set_updating_pause_time_percent": "6", "additional-jvm-opts": [ - "-XX:MaxGCPauseMillis=350" + "-XX:MaxGCPauseMillis=350" ] }, "cassandra-yaml": { - "authenticator": "PasswordAuthenticator", - "authorizer": "CassandraAuthorizer", - "num_tokens": 256, - "role_manager": "CassandraRoleManager", - "start_rpc": false + "authenticator": "PasswordAuthenticator", + "authorizer": "CassandraAuthorizer", + "num_tokens": 256, + "role_manager": "CassandraRoleManager", + "start_rpc": false }, "cluster-info": { - "name": "test", - "seeds": "test-seed-service,test-dc-additional-seed-service" + "name": "test", + "seeds": "test-seed-service,test-dc-additional-seed-service" }, "datacenter-info": { - "graph-enabled": 0, - "name": "datacenter1", - "solr-enabled": 0, - "spark-enabled": 0 + "graph-enabled": 0, + "name": "datacenter1", + "solr-enabled": 0, + "spark-enabled": 0 + } +} +` + +var numericConfig = ` +{ + "jvm-server-options": { + "max_heap_size": 524288000 + }, + "cassandra-yaml": { + "authenticator": "PasswordAuthenticator", + "authorizer": "CassandraAuthorizer", + "num_tokens": 256, + "role_manager": "CassandraRoleManager", + "start_rpc": false + }, + "cluster-info": { + "name": "test", + "seeds": "test-seed-service,test-dc-additional-seed-service" + }, + "datacenter-info": { + "graph-enabled": 0, + "name": "dc2", + "solr-enabled": 0, + "spark-enabled": 0 } } ` @@ -190,7 +215,7 @@ func TestCassandraYamlWriting(t *testing.T) { require.Equal("PasswordAuthenticator", cassandraYaml["authenticator"]) require.Equal("CassandraAuthorizer", cassandraYaml["authorizer"]) require.Equal("CassandraRoleManager", cassandraYaml["role_manager"]) - require.Equal(256, cassandraYaml["num_tokens"]) + require.Equal("256", cassandraYaml["num_tokens"]) require.Equal(false, cassandraYaml["start_rpc"]) } @@ -332,6 +357,29 @@ func TestCassandraEnv(t *testing.T) { require.Contains(lines, "JVM_OPTS=\"$JVM_OPTS -Dcom.sun.management.jmxremote.authenticate=true\"") } +func TestReadOptionsWithNumeric(t *testing.T) { + // JSON Unmarshalling does not Unmarshal everything to type string, instead they can be int/floats/bool etc + require := require.New(t) + + optionsDir := filepath.Join(envtest.RootDir(), "testfiles") + tempDir, err := os.MkdirTemp("", "client-test") + + defer os.RemoveAll(tempDir) + require.NoError(err) + + t.Setenv("CONFIG_FILE_DATA", numericConfig) + configInput, err := parseConfigInput() + require.NoError(err) + require.NotNil(configInput) + + require.NoError(createJVMOptions(configInput, optionsDir, tempDir)) + + lines, err := readFileToLines(tempDir, "jvm-server.options") + require.NoError(err) + + require.Contains(lines, "-Xmx524288000") +} + // readFileToLines is a small test helper, reads file to []string (per line). This version does not filter anything, not even whitespace. func readFileToLines(dir, filename string) ([]string, error) { outputFile := filepath.Join(dir, filename) From fd4404516069d86eee0e0895c5c5bbb19dcae5e7 Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Wed, 26 Jul 2023 12:01:04 +0300 Subject: [PATCH 12/12] Remove commented out code, add JVM major version check for GC options --- pkg/config/builder.go | 36 +++++++----------------------------- pkg/config/builder_test.go | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 29 deletions(-) diff --git a/pkg/config/builder.go b/pkg/config/builder.go index 7deab68..9dcc321 100644 --- a/pkg/config/builder.go +++ b/pkg/config/builder.go @@ -134,32 +134,6 @@ func parseNodeInfo() (*NodeInfo, error) { } func createRackProperties(configInput *ConfigInput, nodeInfo *NodeInfo, sourceDir, targetDir string) error { - // Write cassandra-rackdc.properties file with Datacenter and Rack information - - // This implementation would preserve any extra keys.. but then again, our seedProvider doesn't support those - /* - rackFile := filepath.Join(sourceDir, "cassandra-rackdc.properties") - props, err := properties.LoadFile(rackFile, properties.UTF8) - if err != nil { - return err - } - - props.Set("dc", configInput.DatacenterInfo.Name) - props.Set("rack", nodeInfo.Rack) - - targetFile := filepath.Join(targetDir, "cassandra-rackdc.properties") - f, err := os.OpenFile(targetFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0770) - if err != nil { - return err - } - - defer f.Close() - - if _, err = props.WriteComment(f, "#", properties.UTF8); err != nil { - return err - } - */ - // This creates the cassandra-rackdc.properites with a template with only the values we currently support targetFileT := filepath.Join(targetDir, "cassandra-rackdc.properties") fT, err := os.OpenFile(targetFileT, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0770) @@ -305,7 +279,7 @@ func createServerJVMOptions(options map[string]interface{}, filename, sourceDir, if gcOpts, found := options["garbage_collector"]; found { // Get the GC options - currentOptions = append(currentOptions, getGCOptions(fmt.Sprintf("%v", gcOpts))...) + currentOptions = append(currentOptions, getGCOptions(fmt.Sprintf("%v", gcOpts), 11)...) } } @@ -356,7 +330,7 @@ curOptions: return nil } -func getGCOptions(gcName string) []string { +func getGCOptions(gcName string, jvmMajor int) []string { switch gcName { case "G1GC": return defaultG1Settings @@ -365,7 +339,11 @@ func getGCOptions(gcName string) []string { case "Shenandoah": return []string{"-XX:+UseShenandoahGC"} case "ZGC": - return []string{"-XX:+UseZGC"} + zgcOpts := []string{"-XX:+UseZGC"} + if jvmMajor < 17 { + zgcOpts = append(zgcOpts, "-XX:+UnlockExperimentalVMOptions") + } + return zgcOpts default: // User needs to define all the settings return []string{} diff --git a/pkg/config/builder_test.go b/pkg/config/builder_test.go index cad721c..8d5aaff 100644 --- a/pkg/config/builder_test.go +++ b/pkg/config/builder_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/k8ssandra/k8ssandra-client/internal/envtest" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) @@ -329,7 +330,21 @@ func TestServerOptionsOutput(t *testing.T) { for _, v := range defaultCMSSettings { require.Contains(s11, v) } +} + +func TestGCOptions(t *testing.T) { + assert := assert.New(t) + assert.Equal(defaultG1Settings, getGCOptions("G1GC", 11)) + assert.Equal(defaultG1Settings, getGCOptions("G1GC", 17)) + + assert.Equal(defaultCMSSettings, getGCOptions("CMS", 11)) + assert.Equal(defaultCMSSettings, getGCOptions("CMS", 17)) + + assert.Equal([]string{"-XX:+UseShenandoahGC"}, getGCOptions("Shenandoah", 11)) + assert.Equal([]string{"-XX:+UseShenandoahGC"}, getGCOptions("Shenandoah", 17)) + assert.Equal([]string{"-XX:+UseZGC", "-XX:+UnlockExperimentalVMOptions"}, getGCOptions("ZGC", 11)) + assert.Equal([]string{"-XX:+UseZGC"}, getGCOptions("ZGC", 17)) } func TestCassandraEnv(t *testing.T) {