|
| 1 | +// Copyright 2025 Stefan Prodan. |
| 2 | +// SPDX-License-Identifier: AGPL-3.0 |
| 3 | + |
| 4 | +package toolbox |
| 5 | + |
| 6 | +import ( |
| 7 | + "bytes" |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + ssautil "github.com/fluxcd/pkg/ssa/utils" |
| 14 | + "github.com/google/go-containerregistry/pkg/authn" |
| 15 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 16 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 17 | + "k8s.io/client-go/rest" |
| 18 | + "sigs.k8s.io/yaml" |
| 19 | + |
| 20 | + fluxcdv1 "github.com/controlplaneio-fluxcd/flux-operator/api/v1" |
| 21 | + "github.com/controlplaneio-fluxcd/flux-operator/cmd/mcp/auth" |
| 22 | + "github.com/controlplaneio-fluxcd/flux-operator/internal/install" |
| 23 | +) |
| 24 | + |
| 25 | +const ( |
| 26 | + // ToolInstallFluxInstance is the name of the install_flux_instance tool. |
| 27 | + ToolInstallFluxInstance = "install_flux_instance" |
| 28 | +) |
| 29 | + |
| 30 | +func init() { |
| 31 | + systemTools[ToolInstallFluxInstance] = systemTool{ |
| 32 | + readOnly: false, |
| 33 | + inCluster: true, |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// installFluxInstanceInput defines the input parameters for installing Flux instance. |
| 38 | +type installFluxInstanceInput struct { |
| 39 | + InstanceURL string `json:"instance_url" jsonschema:"The URL pointing to the Flux Instance manifest file."` |
| 40 | + Timeout string `json:"timeout,omitempty" jsonschema:"The installation timeout. Default is 5m."` |
| 41 | +} |
| 42 | + |
| 43 | +// HandleInstallFluxInstance is the handler function for the install_flux_instance tool. |
| 44 | +func (m *Manager) HandleInstallFluxInstance(ctx context.Context, request *mcp.CallToolRequest, input installFluxInstanceInput) (*mcp.CallToolResult, any, error) { |
| 45 | + if err := auth.CheckScopes(ctx, getScopeNames(ToolInstallFluxInstance, m.readOnly)); err != nil { |
| 46 | + return NewToolResultError(err.Error()) |
| 47 | + } |
| 48 | + now := time.Now() |
| 49 | + if input.InstanceURL == "" { |
| 50 | + return NewToolResultError("The instance URL cannot be empty") |
| 51 | + } |
| 52 | + |
| 53 | + timeoutStr := input.Timeout |
| 54 | + if timeoutStr == "" { |
| 55 | + timeoutStr = "5m" |
| 56 | + } |
| 57 | + timeout, err := time.ParseDuration(timeoutStr) |
| 58 | + if err != nil { |
| 59 | + return NewToolResultError("The timeout is not a valid duration") |
| 60 | + } |
| 61 | + if timeout < 5*time.Minute { |
| 62 | + timeout = 5 * time.Minute |
| 63 | + } |
| 64 | + waitTimeout := timeout - 30*time.Second |
| 65 | + |
| 66 | + // TODO: stream logs back to the MCP client while the installation is in progress. |
| 67 | + installLog := strings.Builder{} |
| 68 | + |
| 69 | + ctx, cancel := context.WithTimeout(ctx, timeout) |
| 70 | + defer cancel() |
| 71 | + |
| 72 | + // Step 1: Download the Flux instance manifest and operator manifests |
| 73 | + |
| 74 | + instance, err := m.fetchInstanceManifest(ctx, input.InstanceURL) |
| 75 | + if err != nil { |
| 76 | + return NewToolResultErrorFromErr("failed to fetch instance manifest", err) |
| 77 | + } |
| 78 | + |
| 79 | + operatorObjects, err := m.fetchOperatorManifest(ctx, instance) |
| 80 | + if err != nil { |
| 81 | + return NewToolResultErrorFromErr("failed to fetch operator manifest", err) |
| 82 | + } |
| 83 | + installLog.WriteString(fmt.Sprintf("Artifact download completed in %s\n", time.Since(now).Round(time.Second))) |
| 84 | + |
| 85 | + // Step 2: Create Kubernetes client with impersonation if needed |
| 86 | + |
| 87 | + cfg, err := m.flags.ToRESTConfig() |
| 88 | + if err != nil { |
| 89 | + return NewToolResultErrorFromErr("loading kubeconfig failed", err) |
| 90 | + } |
| 91 | + |
| 92 | + if sess := auth.FromContext(ctx); sess != nil { |
| 93 | + cfg.Impersonate = rest.ImpersonationConfig{ |
| 94 | + UserName: sess.UserName, |
| 95 | + Groups: sess.Groups, |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + installer, err := install.NewInstaller(ctx, cfg) |
| 100 | + if err != nil { |
| 101 | + return NewToolResultErrorFromErr("failed to create installer", err) |
| 102 | + } |
| 103 | + |
| 104 | + // Step 3: Install or upgrade the Flux Operator |
| 105 | + |
| 106 | + isInstalled, err := installer.IsInstalled(ctx) |
| 107 | + if err != nil { |
| 108 | + return NewToolResultErrorFromErr("failed prerequisites", err) |
| 109 | + } |
| 110 | + if !isInstalled { |
| 111 | + installLog.WriteString("Installing Flux Operator...\n") |
| 112 | + } else { |
| 113 | + installLog.WriteString("Upgrading Flux Operator...\n") |
| 114 | + } |
| 115 | + multitenant := instance.Spec.Cluster != nil && instance.Spec.Cluster.Multitenant |
| 116 | + cs, err := installer.ApplyOperator(ctx, operatorObjects, multitenant) |
| 117 | + if err != nil { |
| 118 | + return NewToolResultErrorFromErr("failed to install the operator", err) |
| 119 | + } |
| 120 | + installLog.WriteString(cs.String()) |
| 121 | + installLog.WriteString("\n") |
| 122 | + if err := installer.WaitFor(ctx, cs, waitTimeout); err != nil { |
| 123 | + return NewToolResultErrorFromErr("failed to wait for the operator", err) |
| 124 | + } |
| 125 | + installLog.WriteString("Flux Operator is ready.\n") |
| 126 | + |
| 127 | + // Step 4: Install or upgrade the Flux instance |
| 128 | + |
| 129 | + installLog.WriteString("Installing Flux Instance...\n") |
| 130 | + cs, err = installer.ApplyInstance(ctx, instance) |
| 131 | + if err != nil { |
| 132 | + return NewToolResultErrorFromErr("failed to install instance", err) |
| 133 | + } |
| 134 | + installLog.WriteString(cs.String()) |
| 135 | + installLog.WriteString("\n") |
| 136 | + if err := installer.WaitFor(ctx, cs, waitTimeout-30*time.Second); err != nil { |
| 137 | + return NewToolResultErrorFromErr("failed to wait for the instance", err) |
| 138 | + } |
| 139 | + |
| 140 | + // Step 5: Configure automatic updates |
| 141 | + |
| 142 | + installLog.WriteString("Configuring automatic updates...\n") |
| 143 | + cs, err = installer.ApplyAutoUpdate(ctx, multitenant) |
| 144 | + if err != nil { |
| 145 | + return NewToolResultErrorFromErr("failed to configure automatic updates", err) |
| 146 | + } |
| 147 | + installLog.WriteString(cs.String()) |
| 148 | + installLog.WriteString("\n") |
| 149 | + if err := installer.WaitFor(ctx, cs, waitTimeout-time.Minute); err != nil { |
| 150 | + return NewToolResultErrorFromErr("failed to wait for automatic updates", err) |
| 151 | + } |
| 152 | + installLog.WriteString(fmt.Sprintf("Installation completed in %s\n", time.Since(now).Round(time.Second))) |
| 153 | + |
| 154 | + return NewToolResultText(installLog.String()) |
| 155 | +} |
| 156 | + |
| 157 | +// fetchInstanceManifest downloads and parses the FluxInstance manifest from the given URL. |
| 158 | +func (m *Manager) fetchInstanceManifest(ctx context.Context, instanceURL string) (*fluxcdv1.FluxInstance, error) { |
| 159 | + instance := &fluxcdv1.FluxInstance{} |
| 160 | + data, err := install.DownloadManifestFromURL(ctx, instanceURL, authn.DefaultKeychain) |
| 161 | + if err != nil { |
| 162 | + return nil, err |
| 163 | + } |
| 164 | + |
| 165 | + if err := yaml.Unmarshal(data, instance); err != nil { |
| 166 | + return nil, fmt.Errorf("failed to parse Flux instance: %w", err) |
| 167 | + } |
| 168 | + |
| 169 | + // Set namespace to flux-system |
| 170 | + instance.Namespace = install.DefaultNamespace |
| 171 | + |
| 172 | + return instance, nil |
| 173 | +} |
| 174 | + |
| 175 | +// fetchOperatorManifest downloads and parses the Flux Operator manifest from the distribution artifact. |
| 176 | +func (m *Manager) fetchOperatorManifest(ctx context.Context, instance *fluxcdv1.FluxInstance) ([]*unstructured.Unstructured, error) { |
| 177 | + artifactURL := install.DefaultArtifactURL |
| 178 | + if instance.Spec.Distribution.Artifact != "" { |
| 179 | + artifactURL = instance.Spec.Distribution.Artifact |
| 180 | + } |
| 181 | + |
| 182 | + data, err := install.DownloadFileFromArtifact( |
| 183 | + ctx, |
| 184 | + artifactURL, |
| 185 | + "flux-operator/install.yaml", |
| 186 | + authn.DefaultKeychain, |
| 187 | + ) |
| 188 | + if err != nil { |
| 189 | + return nil, fmt.Errorf("failed to pull distribution artifact: %w", err) |
| 190 | + } |
| 191 | + |
| 192 | + objects, err := ssautil.ReadObjects(bytes.NewReader(data)) |
| 193 | + if err != nil { |
| 194 | + return nil, fmt.Errorf("unable to parse flux-operator/install.yaml: %w", err) |
| 195 | + } |
| 196 | + |
| 197 | + if len(objects) == 0 { |
| 198 | + return nil, fmt.Errorf("no Kubernetes objects found in flux-operator/install.yaml") |
| 199 | + } |
| 200 | + |
| 201 | + return objects, nil |
| 202 | +} |
0 commit comments