8000 feat(library): split pkg/chop config machinery from the kube client wiring by sks · Pull Request #2161 · Altinity/clickhouse-operator · GitHub
[go: up one dir, main page]

Skip to content
< 8000 link rel="preload" as="image" href="https://github.githubassets.com/assets/universe-9af583553ea01049.webp"/>
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 55 additions & 7 deletions pkg/chop/chop.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ import (
"fmt"
"os"

"context"

kube "k8s.io/client-go/kubernetes"

log "github.com/altinity/clickhouse-operator/pkg/announcer"
api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1"
"github.com/altinity/clickhouse-operator/pkg/apis/deployment"
chopclientset "github.com/altinity/clickhouse-operator/pkg/client/clientset/versioned"
chopconfig "github.com/altinity/clickhouse-operator/pkg/chop/config"
"github.com/altinity/clickhouse-operator/pkg/client/clientset/versioned"
"github.com/altinity/clickhouse-operator/pkg/controller"
)

// CHOp defines ClickHouse Operator
Expand All @@ -36,7 +40,7 @@ type CHOp struct {
// Date specified date when operator was built
Date string
// ConfigManager specifies configuration manager in charge of operator's configuration
ConfigManager *ConfigManager
ConfigManager *chopconfig.ConfigManager
}

// newCHOp creates new CHOp
Expand All @@ -45,14 +49,58 @@ func newCHOp(
commit string,
date string,
kubeClient *kube.Clientset,
chopClient *chopclientset.Clientset,
chopClient *versioned.Clientset,
initConfigFilePath string,
) *CHOp {
return &CHOp{
Version: version,
Commit: commit,
Date: date,
ConfigManager: newConfigManager(kubeClient, chopClient, initConfigFilePath),
Version: version,
Commit: commit,
Date: date,
ConfigManager: chopconfig.NewManager(
crConfigListerFrom(chopClient),
secretGetterFrom(kubeClient),
lastKubeConfigInsecure,
initConfigFilePath,
),
}
}

// crConfigListerFrom adapts the operator's custom-resource clientset to
// the config package's CRConfigLister seam — the only place the CR
// listing touches the k8s wire.
func crConfigListerFrom(chopClient *versioned.Clientset) chopconfig.CRConfigLister {
if chopClient == nil {
return nil
}
return func(namespace string) ([]*api.OperatorConfig, map[string]string, error) {
list, err := chopClient.ClickhouseV1().ClickHouseOperatorConfigurations(namespace).List(context.TODO(), controller.NewListOptions())
if err != nil {
return nil, nil, err
}
configs := make([]*api.OperatorConfig, 0, len(list.Items))
versions := make(map[string]string, len(list.Items))
for i := range list.Items {
cr := &list.Items[i]
cr.Spec.Runtime.ConfigCRName = cr.Name
configs = append(configs, &cr.Spec)
versions[cr.Namespace+"/"+cr.Name] = cr.ResourceVersion
}
return configs, versions, nil
}
}

// secretGetterFrom adapts the operator's kube clientset to the config
// package's secretDataGetter seam.
func secretGetterFrom(kubeClient *kube.Clientset) func(namespace, name string) (map[string][]byte, error) {
if kubeClient == nil {
return nil
}
return func(namespace, name string) (map[string][]byte, error) {
secret, err := kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(), name, controller.NewGetOptions())
if err != nil {
return nil, err
}
return secret.Data, nil
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright 2019 Altinity Ltd and/or its affiliates. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package chop

import (
"crypto/rand"
"encoding/hex"
"fmt"
"os"
"path/filepath"

log "github.com/altinity/clickhouse-operator/pkg/announcer"
api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1"
)

// ipcTokenBytes is the random-byte length of the operator↔exporter shared
// bearer token. 32 bytes = 256 bits → 64 hex characters in the file.
// Comfortably above the brute-force-resistance threshold; not so large that
// it stresses /etc tmpfs.
const ipcTokenBytes = 32

// ProvisionIPCToken generates a fresh random token and writes it to the
// configured TokenPath when chopconf has IPC Mode=Secure. Plain mode is a
// no-op so existing deployments are unaffected.
//
// provisionIPCToken is the test-accessible inner implementation. Splitting
// the IPC-config read from the file-write logic lets unit tests drive the
// behavior with a synthetic *api.OperatorConfigSecurityIPC rather
// than spinning up a full chop subsystem.
//
// Idempotent across restarts: if the path already holds a non-empty token,
// the existing value is reused (avoids invalidating the token if the operator
// container restarts while the exporter container keeps holding the old
// value).
// ProvisionIPCToken is the exported inner implementation (pkg/chop's
// wrapper reads the global config and hands the IPC section here).
func ProvisionIPCToken(ipc *api.OperatorConfigSecurityIPC) error {
if (ipc == nil) || (ipc.GetMode() != api.IPCModeSecure) {
return nil
}

path := ipc.GetTokenPath()
if path == "" {
path = api.IPCDefaultTokenPath
}

// Reuse non-empty existing token across operator-container restarts.
if data, err := os.ReadFile(path); (err == nil) && (len(data) > 0) {
log.V(1).Info("IPC: reusing existing token at %s", path)
return nil
}

if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return fmt.Errorf("IPC: cannot create token dir %s: %w", filepath.Dir(path), err)
}

raw := make([]byte, ipcTokenBytes)
if _, err := rand.Read(raw); err != nil {
return fmt.Errorf("IPC: crypto/rand failure generating token: %w", err)
}
encoded := hex.EncodeToString(raw)

if err := os.WriteFile(path, []byte(encoded), 0o400); err != nil {
return fmt.Errorf("IPC: cannot write token to %s: %w", path, err)
}
log.Info("IPC: Secure mode — provisioned token at %s (%d bytes)", path, len(encoded))
return nil
}
12 changes: 6 additions & 6 deletions pkg/chop/ipc_token_test.go → pkg/chop/config/ipc_token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,22 @@ func TestProvisionIPCTokenPlainModeIsNoop(t *testing.T) {
dir := t.TempDir()
tokenPath := filepath.Join(dir, "token")

require.NoError(t, provisionIPCToken(ipcCfg(api.IPCModePlain, tokenPath)))
require.NoError(t, ProvisionIPCToken(ipcCfg(api.IPCModePlain, tokenPath)))

_, err := os.Stat(tokenPath)
require.True(t, os.IsNotExist(err), "Plain mode must not write any token file")
}

func TestProvisionIPCTokenNilIPCIsNoop(t *testing.T) {
require.NoError(t, provisionIPCToken(nil))
require.NoError(t, ProvisionIPCToken(nil))
}

func TestProvisionIPCTokenSecureModeWritesToken(t *testing.T) {
dir := t.TempDir()
// Path under a subdirectory that doesn't exist yet — exercises MkdirAll.
tokenPath := filepath.Join(dir, "subdir", "token")

require.NoError(t, provisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath)))
require.NoError(t, ProvisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath)))

data, err := os.ReadFile(tokenPath)
require.NoError(t, err)
Expand All @@ -71,7 +71,7 @@ func TestProvisionIPCTokenReuseExisting(t *testing.T) {
tokenPath := filepath.Join(dir, "token")
require.NoError(t, os.WriteFile(tokenPath, []byte("preexisting-token-value"), 0o400))

require.NoError(t, provisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath)))
require.NoError(t, ProvisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath)))

data, err := os.ReadFile(tokenPath)
require.NoError(t, err)
Expand All @@ -86,12 +86,12 @@ func TestProvisionIPCTokenTwoCallsSameToken(t *testing.T) {
tokenPath := filepath.Join(dir, "token")
cfg := ipcCfg(api.IPCModeSecure, tokenPath)

require.NoError(t, provisionIPCToken(cfg))
require.NoError(t, ProvisionIPCToken(cfg))
first, err := os.ReadFile(tokenPath)
require.NoError(t, err)
require.NotEmpty(t, first)

require.NoError(t, provisionIPCToken(cfg))
require.NoError(t, ProvisionIPCToken(cfg))
second, err := os.ReadFile(tokenPath)
require.NoError(t, err)
require.Equal(t, first, second, "second call must reuse the existing token")
Expand Down
Loading
Loading
0