diff --git a/README.md b/README.md index 0706896..50c2137 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ nr cluster register \ `--org-id` is required (or set `NR_ORGANIZATION_ID`). It only sends `X-Organization-ID`. A missing or unauthorized token still fails; a token from another organization cannot register into this one. -The CLI uses the organization hypervisor driver (`proxmox`, `virtfusion`, or `solusvm`). Pass `--hypervisor-driver` only to confirm it; a mismatch is rejected. +The CLI uses the organization hypervisor driver (`proxmox`, `virtfusion`, or `solusvm`). Pass `--hypervisor-driver` only to confirm it; a mismatch is rejected. `pterodactyl` is not a hypervisor driver. After the agent is registered, `nr cluster install-pterodactyl` installs the game server operator beside it. `--agent-ip` must be an address assigned to a local interface on the VM (`ip -4 addr`). k3s uses it as `--node-ip`; a placeholder such as `1.1.1.1` fails preflight. diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 4e93985..865ce5a 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -99,6 +99,10 @@ TLS verification is off. No flag or env var is required. TLS verification is off. No flag or env var is required. +### Pterodactyl (`nr cluster install-pterodactyl`) + +This is not a `--hypervisor-driver` value. Register the hypervisor agent first, then install the game server operator. The command asks for the panel URL, both keys, and the panel user id, and shows the keys as you type. Export `PTERODACTYL_APPLICATION_KEY` and `PTERODACTYL_CLIENT_KEY` to the keys themselves to skip those prompts. The keys are stored in a Secret on the agent and are not sent to NodeRings. + ## State Registration checkpoints live under `~/.nr/`. Do not copy these directories between machines. diff --git a/internal/cli/agent.go b/internal/cli/agent.go index c4cda17..7c66605 100644 --- a/internal/cli/agent.go +++ b/internal/cli/agent.go @@ -329,6 +329,7 @@ func runAgentCreate(cmd *cobra.Command, args []string) error { hypervisorDriverRaw, cmd.Flags().Changed("hypervisor-driver"), orgDriver, + !cmd.Flags().Changed("hypervisor-driver"), ) if err != nil { return err diff --git a/internal/cli/cluster.go b/internal/cli/cluster.go index 7374f05..3ce9bf9 100644 --- a/internal/cli/cluster.go +++ b/internal/cli/cluster.go @@ -73,7 +73,13 @@ func init() { clusterRegisterCmd.Flags().Bool("reinstall-operator", false, "Re-run hypervisor operator Helm install even if that phase already succeeded (use with --resume). Reuses cluster Secrets unless hypervisor credentials are provided.") clusterRegisterCmd.Flags().String("operator-chart", "", "Local path or OCI ref for the hypervisor operator chart (default: Harbor OCI or sibling checkout)") clusterRegisterCmd.Flags().String("operator-chart-version", "", "Helm chart version when using OCI (default: "+config.DefaultProxmoxOperatorChartVersion+")") - clusterRegisterCmd.Flags().String("hypervisor-driver", "", "Required until the first agent in this organization is registered. After that, omit it or pass the same driver (proxmox, virtfusion, or solusvm).") + clusterRegisterCmd.Flags().String("hypervisor-driver", "", "Hypervisor for this agent: proxmox, virtfusion, or solusvm. Omit it with --pterodactyl to install game servers only. One hypervisor per organization.") + clusterRegisterCmd.Flags().Bool("pterodactyl", false, "Install the game server operator. Does not set a hypervisor. Combine with --hypervisor-driver to install both. Panel URL, keys, and user id are prompted unless set with flags or PTERODACTYL_* env.") + clusterRegisterCmd.Flags().String("panel-url", "", "Panel origin with no /admin, used with --pterodactyl (prompted, or PTERODACTYL_PANEL_URL)") + clusterRegisterCmd.Flags().String("application-key-file", "", "File containing the ptla_ application key (prompted, or PTERODACTYL_APPLICATION_KEY / PTERODACTYL_APPLICATION_KEY_FILE)") + clusterRegisterCmd.Flags().String("client-key-file", "", "File containing the ptlc_ client key (prompted, or PTERODACTYL_CLIENT_KEY / PTERODACTYL_CLIENT_KEY_FILE)") + clusterRegisterCmd.Flags().String("panel-user-id", "", "Panel user id that owns NodeRings servers (prompted, or PTERODACTYL_PANEL_USER_ID)") + clusterRegisterCmd.Flags().String("pterodactyl-chart", "", "Local chart path or OCI reference for the Pterodactyl operator") clusterRegisterCmd.Flags().String("proxmox-instances-file", "", "YAML file with proxmox.instances list (or PROXMOX_INSTANCES_FILE)") clusterRegisterCmd.Flags().String("virtfusion-instances-file", "", "YAML file with virtfusion.instances list (or VIRTFUSION_INSTANCES_FILE)") clusterRegisterCmd.Flags().String("solusvm-instances-file", "", "YAML file with solusvm.instances list (or SOLUSVM_INSTANCES_FILE)") @@ -148,10 +154,12 @@ func runClusterRegister(cmd *cobra.Command, args []string) error { } orgDriver := fetchOrganizationHypervisorDriver(ctx, apiClient) + installPterodactyl, _ := cmd.Flags().GetBool("pterodactyl") hypervisorDriver, err := resolveHypervisorDriver( hypervisorDriverRaw, cmd.Flags().Changed("hypervisor-driver"), orgDriver, + installPterodactyl && !cmd.Flags().Changed("hypervisor-driver"), ) if err != nil { return err @@ -169,6 +177,8 @@ func runClusterRegister(cmd *cobra.Command, args []string) error { operatorChartPath: operatorChartPath, operatorChartVersion: operatorChartVersion, hypervisorDriver: hypervisorDriver, + installPterodactyl: installPterodactyl, + command: cmd, proxmoxInstancesFile: proxmoxInstancesFile, virtfusionInstancesFile: virtfusionInstancesFile, solusvmInstancesFile: solusvmInstancesFile, @@ -189,6 +199,15 @@ func runClusterRegister(cmd *cobra.Command, args []string) error { if err := validateRegisterHypervisorOpts(registerOpts); err != nil { return err } + if installPterodactyl { + if yes { + if _, err := loadPterodactylInstall(cmd, "pterodactyl-chart", true); err != nil { + return err + } + } else if err := preflightPterodactylInstall(cmd); err != nil { + return err + } + } if err := applyDevRegisterProfile(cfg, devMode); err != nil { return err @@ -273,7 +292,7 @@ func runClusterRegister(cmd *cobra.Command, args []string) error { // Handle resume if resume { - return handleResume(ctx, stateManager, apiClient, log, configDir, skipPrechecks, dryRun, offline, cfg, registerOpts) + return handleResume(cmd, ctx, stateManager, apiClient, log, configDir, skipPrechecks, dryRun, offline, cfg, registerOpts) } // Handle dry-run @@ -284,11 +303,14 @@ func runClusterRegister(cmd *cobra.Command, args []string) error { if namespaces := collectOffloadNamespaces(registerOpts); len(namespaces) > 0 { log.Infof("Would offload namespaces: %v", namespaces) } - if registerOpts.skipOperatorInstall { - log.Infof("Would skip %s install", operatorHelmName(registerOpts.hypervisorDriver)) + if registerOpts.hypervisorDriver == "" || registerOpts.skipOperatorInstall { + log.Info("Would skip the hypervisor operator") } else { log.Infof("Would install %s / vnc-gateway", operatorHelmName(registerOpts.hypervisorDriver)) } + if registerOpts.installPterodactyl { + log.Info("Would install the Pterodactyl operator") + } log.Info("Would verify provider health (subsections scoped to register flags)") return nil } @@ -530,10 +552,13 @@ func runClusterRegister(cmd *cobra.Command, args []string) error { return err } - // Step 9: Install hypervisor operator + vnc-gateway + // Step 9: Install hypervisor operator + vnc-gateway, then the game server operator when requested. if err := runOperatorInstallPhase(ctx, apiClient, log, stateManager, agentID, registerOpts); err != nil { return err } + if err := ensurePterodactylRelease(cmd, registerOpts, agentID); err != nil { + return err + } // Step 10: Verify provider cluster health (subsections honor register flags) if err := runPostRegisterVerify(ctx, apiClient, log, agentID, registerOpts); err != nil { @@ -769,7 +794,7 @@ func createAgent(ctx context.Context, apiClient *api.Client, name, agentIP, gate func persistAgentHypervisorDriver(ctx context.Context, apiClient *api.Client, agentID, hypervisorDriver string) error { apiDriver := hypervisorDriverToAPI(hypervisorDriver) if apiDriver == nil { - return fmt.Errorf("hypervisor driver is required to register an agent") + return nil } genClient := apiClient.GetGeneratedClient() resp, err := apiClient.DoWithAutoRefresh(ctx, 3, func() (*http.Response, error) { @@ -836,7 +861,7 @@ func preparePlatformVersions( } // handleResume resumes a failed installation -func handleResume(ctx context.Context, stateManager *state.Manager, apiClient *api.Client, log *logger.Logger, configDir string, skipPrechecks, dryRun, offline bool, cfg *config.Config, registerOpts clusterRegisterOpts) error { +func handleResume(cmd *cobra.Command, ctx context.Context, stateManager *state.Manager, apiClient *api.Client, log *logger.Logger, configDir string, skipPrechecks, dryRun, offline bool, cfg *config.Config, registerOpts clusterRegisterOpts) error { installState := stateManager.GetState() if installState.AgentID == "" { @@ -888,6 +913,9 @@ func handleResume(ctx context.Context, stateManager *state.Manager, apiClient *a if installState.Phase == state.PhaseComplete && !operatorInstallPending { log.Info("Installation already complete; verifying provider health...") + if err := ensurePterodactylRelease(cmd, registerOpts, installState.AgentID); err != nil { + return err + } if err := runPostRegisterVerify(ctx, apiClient, log, installState.AgentID, registerOpts); err != nil { return err } @@ -933,6 +961,9 @@ func handleResume(ctx context.Context, stateManager *state.Manager, apiClient *a return resumeFromOperatorInstall(ctx, stateManager, apiClient, log, registerOpts) case state.PhaseOperatorInstall: log.Info("Operator install already completed; verifying before marking complete...") + if err := ensurePterodactylRelease(cmd, registerOpts, installState.AgentID); err != nil { + return err + } if err := runPostRegisterVerify(ctx, apiClient, log, installState.AgentID, registerOpts); err != nil { return err } @@ -1223,6 +1254,9 @@ func resumeFromOperatorInstall(ctx context.Context, stateManager *state.Manager, if err := runOperatorInstallPhase(ctx, apiClient, log, stateManager, stateManager.GetAgentID(), registerOpts); err != nil { return err } + if err := ensurePterodactylRelease(registerOpts.command, registerOpts, stateManager.GetAgentID()); err != nil { + return err + } if err := runPostRegisterVerify(ctx, apiClient, log, stateManager.GetAgentID(), registerOpts); err != nil { return err } diff --git a/internal/cli/cluster_hypervisor.go b/internal/cli/cluster_hypervisor.go new file mode 100644 index 0000000..8503276 --- /dev/null +++ b/internal/cli/cluster_hypervisor.go @@ -0,0 +1,151 @@ +package cli + +import ( + "context" + "fmt" + "os" + "os/exec" + "strings" + + "github.com/spf13/cobra" + + "github.com/noderings/cli/internal/config" + "github.com/noderings/cli/internal/logger" + "github.com/noderings/cli/internal/state" +) + +func init() { + cmd := &cobra.Command{ + Use: "install-hypervisor", + Short: "Install one hypervisor operator", + Long: `Install proxmox, virtfusion, or solusvm on the current cluster. + +Run it on a new agent, or after game servers are already installed. +An agent has one hypervisor. A second choice is rejected. +Pass --agent-id to store that driver on an agent registered with --pterodactyl only.`, + RunE: runInstallHypervisor, + } + cmd.Flags().String("hypervisor-driver", "", "proxmox, virtfusion, or solusvm (required)") + cmd.Flags().String("agent-id", "", "Agent UUID. Stores the driver when this agent had no hypervisor yet.") + cmd.Flags().BoolP("yes", "y", false, "Non-interactive: read hypervisor credentials from the environment or an instances file") + cmd.Flags().String("operator-chart", "", "Local path or OCI ref for the hypervisor operator chart") + cmd.Flags().String("operator-chart-version", "", "Helm chart version when using OCI") + cmd.Flags().String("proxmox-instances-file", "", "YAML file with proxmox.instances list (or PROXMOX_INSTANCES_FILE)") + cmd.Flags().String("virtfusion-instances-file", "", "YAML file with virtfusion.instances list (or VIRTFUSION_INSTANCES_FILE)") + cmd.Flags().String("solusvm-instances-file", "", "YAML file with solusvm.instances list (or SOLUSVM_INSTANCES_FILE)") + cmd.Flags().String("vnc-gateway-namespace", "", "VNC gateway namespace (default: vnc-gateway)") + clusterCmd.AddCommand(cmd) +} + +func runInstallHypervisor(cmd *cobra.Command, _ []string) error { + if !cmd.Flags().Changed("hypervisor-driver") { + return UsageErrorf("--hypervisor-driver is required (proxmox, virtfusion, or solusvm)") + } + raw, _ := cmd.Flags().GetString("hypervisor-driver") + driver, err := parseHypervisorDriver(raw) + if err != nil { + return err + } + if strings.TrimSpace(raw) == "" { + return UsageErrorf("--hypervisor-driver is required (proxmox, virtfusion, or solusvm)") + } + + present, err := installedHypervisorNamespaces() + if err != nil { + return err + } + if err := conflictingHypervisorNamespace(present, driver); err != nil { + return err + } + + agentID, _ := cmd.Flags().GetString("agent-id") + agentID = strings.TrimSpace(agentID) + yes, _ := cmd.Flags().GetBool("yes") + chart, _ := cmd.Flags().GetString("operator-chart") + chartVersion, _ := cmd.Flags().GetString("operator-chart-version") + pveFile, _ := cmd.Flags().GetString("proxmox-instances-file") + vfFile, _ := cmd.Flags().GetString("virtfusion-instances-file") + svmFile, _ := cmd.Flags().GetString("solusvm-instances-file") + vncNS, _ := cmd.Flags().GetString("vnc-gateway-namespace") + + opts := clusterRegisterOpts{ + yes: yes, + hypervisorDriver: driver, + operatorChartPath: chart, + operatorChartVersion: chartVersion, + proxmoxInstancesFile: pveFile, + virtfusionInstancesFile: vfFile, + solusvmInstancesFile: svmFile, + vncGatewayNamespace: vncNS, + } + if err := validateRegisterHypervisorOpts(opts); err != nil { + return err + } + + ctx := context.Background() + log, err := logger.NewLogger("info", "") + if err != nil { + return err + } + if agentID != "" || strings.TrimSpace(os.Getenv("MIMIR_BEARER_TOKEN")) == "" { + apiClient, apiErr := getAuthenticatedAPIClient(cmd) + if apiErr != nil { + return fmt.Errorf("log in, or set MIMIR_BEARER_TOKEN, before installing the hypervisor operator: %w", apiErr) + } + if agentID != "" { + orgDriver := fetchOrganizationHypervisorDriver(ctx, apiClient) + bound, bindErr := resolveHypervisorDriver(driver, true, orgDriver, false) + if bindErr != nil { + return bindErr + } + if err := persistAgentHypervisorDriver(ctx, apiClient, agentID, bound); err != nil { + return err + } + log.Infof("Stored hypervisor driver %s on agent %s", bound, agentID) + } + stateManager := state.NewManager(config.GetConfigDir(), agentID) + return runOperatorInstallPhase(ctx, apiClient, log, stateManager, agentID, opts) + } + + stateManager := state.NewManager(config.GetConfigDir(), "install-hypervisor") + return runOperatorInstallPhase(ctx, nil, log, stateManager, "", opts) +} + +func hypervisorNamespace(driver string) string { + switch driver { + case config.HypervisorDriverVirtFusion: + return config.DefaultVirtFusionOperatorHelmNamespace + case config.HypervisorDriverSolusVM: + return config.DefaultSolusVMOperatorHelmNamespace + default: + return config.DefaultProxmoxOperatorHelmNamespace + } +} + +func conflictingHypervisorNamespace(present []string, requested string) error { + want := hypervisorNamespace(requested) + for _, ns := range present { + ns = strings.TrimSpace(ns) + if ns == "" || ns == want { + continue + } + return UsageErrorf("this cluster already has the %s hypervisor. An agent has one of proxmox, virtfusion, or solusvm", ns) + } + return nil +} + +func installedHypervisorNamespaces() ([]string, error) { + known := []string{ + config.DefaultProxmoxOperatorHelmNamespace, + config.DefaultVirtFusionOperatorHelmNamespace, + config.DefaultSolusVMOperatorHelmNamespace, + } + var found []string + for _, ns := range known { + check := exec.Command("kubectl", "get", "ns", ns) + if err := check.Run(); err == nil { + found = append(found, ns) + } + } + return found, nil +} diff --git a/internal/cli/cluster_inbound_peering.go b/internal/cli/cluster_inbound_peering.go index 2781e22..41d92cc 100644 --- a/internal/cli/cluster_inbound_peering.go +++ b/internal/cli/cluster_inbound_peering.go @@ -42,6 +42,15 @@ func runInboundPeeringPhase( log.Warnf("Failed to save state: %v", err) } + // The mothership virtual-kubelet starts as soon as this kubeconfig is uploaded. + // CRDs and Liqo roles have to exist on this cluster before that. + log.Info("Ensuring game catalog reflection on this cluster...") + if err := liqoManager.PrepareGameCatalogReflection(ctx); err != nil { + stateManager.SetError(state.PhaseInboundPeering, err.Error(), true) + _ = stateManager.Save() + return fmt.Errorf("prepare game catalog reflection: %w", err) + } + detectedRemoteClusterID, detectErr := liqoManager.GetPeeredClusterID(ctx) neoClusterID, err := resolveRemoteClusterID(log, opts, detectedRemoteClusterID, detectErr) if err != nil { diff --git a/internal/cli/cluster_operator_install.go b/internal/cli/cluster_operator_install.go index c09ff81..a21b0fe 100644 --- a/internal/cli/cluster_operator_install.go +++ b/internal/cli/cluster_operator_install.go @@ -26,6 +26,14 @@ func runOperatorInstallPhase( agentID string, opts clusterRegisterOpts, ) error { + if strings.TrimSpace(opts.hypervisorDriver) == "" { + log.Info("No hypervisor selected; skipping the hypervisor operator") + stateManager.AddCheckpoint(state.PhaseOperatorInstall, state.CheckpointStatusSuccess, "no hypervisor") + if err := stateManager.Save(); err != nil { + log.Warnf("Failed to save state: %v", err) + } + return nil + } if opts.skipOperatorInstall { log.Infof("Skipping %s install (--skip-operator-install)", operatorHelmName(opts.hypervisorDriver)) return nil diff --git a/internal/cli/cluster_pterodactyl.go b/internal/cli/cluster_pterodactyl.go new file mode 100644 index 0000000..2741aa8 --- /dev/null +++ b/internal/cli/cluster_pterodactyl.go @@ -0,0 +1,446 @@ +package cli + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "os" + "os/exec" + "strconv" + "strings" + + "github.com/google/uuid" + "github.com/spf13/cobra" + + "github.com/noderings/cli/internal/config" + nrinstall "github.com/noderings/cli/internal/install" + "github.com/noderings/cli/internal/logger" +) + +// errPterodactylCredentialsRequired is returned when panel settings are still +// missing and the command cannot prompt (--yes, or stdin is not a terminal). +var errPterodactylCredentialsRequired = errors.New("pterodactyl credentials required: set PTERODACTYL_PANEL_URL, PTERODACTYL_APPLICATION_KEY or PTERODACTYL_APPLICATION_KEY_FILE, PTERODACTYL_CLIENT_KEY or PTERODACTYL_CLIENT_KEY_FILE, and PTERODACTYL_PANEL_USER_ID, pass the matching flags, or run interactively (without --yes)") + +func init() { + cmd := &cobra.Command{ + Use: "install-pterodactyl", + Short: "Install the Pterodactyl operator", + Long: `Install the game server operator on the current cluster. + +Use it on its own, before a hypervisor, or after nr cluster register --hypervisor-driver. +It does not set --hypervisor-driver. The panel URL, application key, client key, and panel user id are prompted unless you set them with flags or PTERODACTYL_* environment variables. Keys stay in a Secret on the agent. They are not sent to NodeRings.`, + RunE: runInstallPterodactyl, + } + cmd.Flags().String("panel-url", "", "Panel origin with no /admin (prompted, or PTERODACTYL_PANEL_URL)") + cmd.Flags().String("application-key-file", "", "File containing the ptla_ application key (prompted, or PTERODACTYL_APPLICATION_KEY / PTERODACTYL_APPLICATION_KEY_FILE)") + cmd.Flags().String("client-key-file", "", "File containing the ptlc_ client key (prompted, or PTERODACTYL_CLIENT_KEY / PTERODACTYL_CLIENT_KEY_FILE)") + cmd.Flags().String("panel-user-id", "", "Panel user id that owns NodeRings servers (prompted, or PTERODACTYL_PANEL_USER_ID)") + cmd.Flags().String("operator-chart", "", "Local chart path or OCI reference") + cmd.Flags().String("agent-id", "", "Agent UUID stamped on Pterodactyl metrics") + clusterCmd.AddCommand(cmd) +} + +type pterodactylInstall struct { + PanelURL string + ApplicationKey string + ClientKey string + PanelUserID string + Chart string + Namespace string + SecretName string + AgentID string + MimirEndpoint string + MimirTLS bool + MimirSecretName string +} + +func loadPterodactylInstall(cmd *cobra.Command, chartFlag string, nonInteractive bool) (pterodactylInstall, error) { + panelURL, _ := cmd.Flags().GetString("panel-url") + userID, _ := cmd.Flags().GetString("panel-user-id") + chart, _ := cmd.Flags().GetString(chartFlag) + panelURL = strings.TrimSpace(panelURL) + if panelURL == "" { + panelURL = strings.TrimSpace(os.Getenv("PTERODACTYL_PANEL_URL")) + } + userID = strings.TrimSpace(userID) + if userID == "" { + userID = strings.TrimSpace(os.Getenv("PTERODACTYL_PANEL_USER_ID")) + } + appKey, err := pterodactylKey(cmd, "application-key-file", "PTERODACTYL_APPLICATION_KEY_FILE", "PTERODACTYL_APPLICATION_KEY") + if err != nil { + return pterodactylInstall{}, err + } + clientKey, err := pterodactylKey(cmd, "client-key-file", "PTERODACTYL_CLIENT_KEY_FILE", "PTERODACTYL_CLIENT_KEY") + if err != nil { + return pterodactylInstall{}, err + } + if panelURL != "" { + if err := validatePanelURL(panelURL); err != nil { + return pterodactylInstall{}, err + } + } + if userID != "" { + if _, err := parsePanelUserID(userID); err != nil { + return pterodactylInstall{}, err + } + } + if panelURL == "" || appKey == "" || clientKey == "" || userID == "" { + if nonInteractive || !isStdinTerminal() { + return pterodactylInstall{}, errPterodactylCredentialsRequired + } + beginCredentialPrompt("Configure Pterodactyl panel access for the operator") + if panelURL == "" { + panelURL, err = promptString("Pterodactyl panel URL (e.g. https://panel.example.com, no /admin)", "") + if err != nil { + return pterodactylInstall{}, err + } + } + if appKey == "" { + appKey, err = promptVisibleToken("Pterodactyl application API key (ptla_)") + if err != nil { + return pterodactylInstall{}, err + } + } + if clientKey == "" { + clientKey, err = promptVisibleToken("Pterodactyl client API key (ptlc_)") + if err != nil { + return pterodactylInstall{}, err + } + } + if userID == "" { + userID, err = promptString("Pterodactyl panel user ID (numeric, from the Users list)", "") + if err != nil { + return pterodactylInstall{}, err + } + } + } + if err := validatePanelURL(panelURL); err != nil { + return pterodactylInstall{}, err + } + panelUserID, err := parsePanelUserID(userID) + if err != nil { + return pterodactylInstall{}, err + } + if strings.TrimSpace(appKey) == "" || strings.TrimSpace(clientKey) == "" { + return pterodactylInstall{}, errPterodactylCredentialsRequired + } + chart = strings.TrimSpace(chart) + if chart == "" { + chart = strings.TrimSpace(os.Getenv("PTERODACTYL_OPERATOR_CHART")) + } + if chart == "" { + chart = config.DefaultPterodactylOperatorChartOCI + } + return pterodactylInstall{ + PanelURL: strings.TrimRight(panelURL, "/"), + ApplicationKey: strings.TrimSpace(appKey), + ClientKey: strings.TrimSpace(clientKey), + PanelUserID: strconv.Itoa(panelUserID), + Chart: chart, + Namespace: config.DefaultPterodactylOperatorHelmNamespace, + SecretName: "operator-pterodactyl-operator-panel-credentials", + }, nil +} + +// preflightPterodactylInstall rejects a bad URL, user id, or key file before +// register spends time on the cluster. Missing values are filled later, the +// same way Proxmox credentials are. +func preflightPterodactylInstall(cmd *cobra.Command) error { + _, err := loadPterodactylInstall(cmd, "pterodactyl-chart", true) + if errors.Is(err, errPterodactylCredentialsRequired) { + return nil + } + return err +} + +func pterodactylKey(cmd *cobra.Command, flagName, fileEnv, valueEnv string) (string, error) { + path, _ := cmd.Flags().GetString(flagName) + path = strings.TrimSpace(path) + if path == "" { + path = strings.TrimSpace(os.Getenv(fileEnv)) + } + if path != "" { + return readKeyFile(path) + } + return strings.TrimSpace(os.Getenv(valueEnv)), nil +} + +func validatePanelURL(panelURL string) error { + panelURL = strings.TrimRight(strings.TrimSpace(panelURL), "/") + parsed, err := url.Parse(panelURL) + if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.Path != "" || parsed.RawQuery != "" || parsed.Fragment != "" || parsed.User != nil || strings.ContainsAny(panelURL, " ,\t\r\n") { + return UsageErrorf("--panel-url must be an http(s) origin with no /admin and no path") + } + return nil +} + +func parsePanelUserID(userID string) (int, error) { + panelUserID, err := strconv.Atoi(strings.TrimSpace(userID)) + if err != nil || panelUserID <= 0 { + return 0, UsageErrorf("--panel-user-id must be a positive integer") + } + return panelUserID, nil +} + +func readKeyFile(path string) (string, error) { + if strings.TrimSpace(path) == "" { + return "", UsageErrorf("application and client key files are required") + } + raw, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("read key file: %w", err) + } + key := strings.TrimSpace(string(raw)) + if key == "" { + return "", UsageErrorf("key file is empty") + } + return key, nil +} + +func runInstallPterodactyl(cmd *cobra.Command, _ []string) error { + install, err := loadPterodactylInstall(cmd, "operator-chart", false) + if err != nil { + return err + } + agentID, _ := cmd.Flags().GetString("agent-id") + install.AgentID = strings.TrimSpace(agentID) + return applyPterodactylRelease(cmd, install) +} + +func ensurePterodactylRelease(cmd *cobra.Command, opts clusterRegisterOpts, agentID string) error { + if !opts.installPterodactyl { + return nil + } + install, err := loadPterodactylInstall(cmd, "pterodactyl-chart", opts.yes) + if err != nil { + return err + } + install.AgentID = strings.TrimSpace(agentID) + if install.AgentID == "" { + install.AgentID = strings.TrimSpace(opts.agentID) + } + return applyPterodactylRelease(cmd, install) +} + +func applyPterodactylRelease(cmd *cobra.Command, install pterodactylInstall) error { + ctx := cmd.Context() + if ctx == nil { + ctx = context.Background() + } + // Same as the Proxmox installer: helm lives in ~/.nr/bin, and the kubeconfig + // is the readable k3s copy (lab or production agent) or KUBECONFIG / ~/.kube/config. + if _, err := nrinstall.EnsureCLIBinDir(); err != nil { + return fmt.Errorf("helm bin dir: %w", err) + } + kubeconfig := nrinstall.EnsureReadableKubeconfig(ctx, "", nil) + if strings.TrimSpace(kubeconfig) == "" { + return fmt.Errorf("could not find a readable kubeconfig (tried KUBECONFIG, ~/.nr/k3s.kubeconfig, ~/.kube/config, and /etc/rancher/k3s/k3s.yaml)") + } + if err := applyPanelSecret(ctx, install, kubeconfig); err != nil { + return err + } + if err := configurePterodactylMetrics(ctx, cmd, &install, kubeconfig); err != nil { + return err + } + // CRDs are installed on their own before peering so the virtual-kubelet can + // watch them. The operator subchart must not try to adopt or delete them. + if err := nrinstall.EnsureHypervisorCRDs(ctx, kubeconfig, nil); err != nil { + return err + } + if err := nrinstall.AnnotateOperatorCRDsKeep(ctx, kubeconfig, nil); err != nil { + return err + } + helmArgs := pterodactylHelmArgs(install, kubeconfig) + helm := exec.CommandContext(ctx, "helm", helmArgs...) + helm.Stdout = cmd.OutOrStdout() + helm.Stderr = cmd.ErrOrStderr() + if err := helm.Run(); err != nil { + return fmt.Errorf("install pterodactyl operator: %w", err) + } + fmt.Fprintln(cmd.OutOrStdout(), "panel keys are stored only in the agent Secret") + return nil +} + +func pterodactylHelmArgs(install pterodactylInstall, kubeconfig string) []string { + args := []string{ + "upgrade", "--install", "operator", install.Chart, + "--namespace", install.Namespace, + "--create-namespace", + "--set", "crds.enabled=false", + "--set-string", "panel.url=" + install.PanelURL, + "--set-string", "panel.existingSecret=" + install.SecretName, + } + if install.MimirEndpoint != "" { + args = append(args, + "--set-string", "alloy.mimir.serviceEndpoint="+install.MimirEndpoint, + "--set", fmt.Sprintf("alloy.mimir.tls.enabled=%t", install.MimirTLS), + ) + if install.MimirSecretName != "" { + args = append(args, + "--set", "alloy.mimir.secretName="+install.MimirSecretName, + "--set-json", fmt.Sprintf(`alloy.alloy.envFrom=[{"secretRef":{"name":"%s"}}]`, install.MimirSecretName), + ) + } else { + args = append(args, "--set", "alloy.mimir.secretName=") + } + if install.AgentID != "" { + args = append(args, "--set-string", "alloy.agentId="+install.AgentID) + } + } + args = append(args, "--wait", "--timeout", "180s", "--kubeconfig", kubeconfig) + return args +} + +func configurePterodactylMetrics(ctx context.Context, cmd *cobra.Command, install *pterodactylInstall, kubeconfig string) error { + if install.AgentID != "" { + if _, err := uuid.Parse(install.AgentID); err != nil { + return fmt.Errorf("invalid agent ID for alloy.agentId: %w", err) + } + } + endpoint := strings.TrimSpace(os.Getenv(config.EnvMimirServiceEndpoint)) + if endpoint == "" { + endpoint = config.DefaultMimirServiceEndpoint + } + install.MimirEndpoint = endpoint + install.MimirTLS = pterodactylMimirTLS() + token := strings.TrimSpace(os.Getenv(config.EnvMimirBearerToken)) + if token == "" { + token = existingMimirToken(ctx, kubeconfig) + } + if token == "" && install.AgentID != "" { + apiClient, err := getAuthenticatedAPIClient(cmd) + if err != nil { + if install.MimirTLS { + return fmt.Errorf("log in, or set %s, before installing Pterodactyl metrics: %w", config.EnvMimirBearerToken, err) + } + } else { + log, logErr := logger.NewLogger("info", "") + if logErr != nil { + return fmt.Errorf("logger: %w", logErr) + } + issued, issueErr := issueMetricsWriteCredential(ctx, apiClient, install.AgentID, log) + if issueErr != nil { + return fmt.Errorf("issue metrics write credential: %w", issueErr) + } + token = issued + } + } + if install.MimirTLS && token == "" { + return fmt.Errorf("%s is required for TLS remote_write (production)", config.EnvMimirBearerToken) + } + if token == "" { + return nil + } + install.MimirSecretName = config.DefaultMimirCredentialsSecret + return applyMimirSecret(ctx, install.Namespace, kubeconfig, token) +} + +func pterodactylMimirTLS() bool { + value, set := os.LookupEnv(config.EnvMimirTLSEnabled) + if !set { + return true + } + switch strings.ToLower(strings.TrimSpace(value)) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} + +func existingMimirToken(ctx context.Context, kubeconfig string) string { + namespaces := []string{ + config.DefaultProxmoxOperatorHelmNamespace, + config.DefaultVirtFusionOperatorHelmNamespace, + config.DefaultSolusVMOperatorHelmNamespace, + config.DefaultPterodactylOperatorHelmNamespace, + } + for _, ns := range namespaces { + cmd := exec.CommandContext(ctx, "kubectl", withKubeconfig(kubeconfig, "get", "secret", config.DefaultMimirCredentialsSecret, "-n", ns, "-o", "jsonpath={.data.MIMIR_BEARER_TOKEN}")...) + out, err := cmd.Output() + if err != nil || len(bytesTrim(out)) == 0 { + continue + } + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(out))) + if err != nil || len(raw) == 0 { + continue + } + return string(raw) + } + return "" +} + +func bytesTrim(in []byte) string { + return strings.TrimSpace(string(in)) +} + +func applyMimirSecret(ctx context.Context, namespace, kubeconfig, token string) error { + ns := exec.CommandContext(ctx, "kubectl", withKubeconfig(kubeconfig, "create", "namespace", namespace)...) + if out, err := ns.CombinedOutput(); err != nil && !strings.Contains(string(out), "AlreadyExists") { + return fmt.Errorf("create namespace: %w", err) + } + manifest := map[string]any{ + "apiVersion": "v1", + "kind": "Secret", + "metadata": map[string]string{ + "name": config.DefaultMimirCredentialsSecret, + "namespace": namespace, + }, + "type": "Opaque", + "data": map[string]string{ + config.EnvMimirBearerToken: base64.StdEncoding.EncodeToString([]byte(token)), + }, + } + raw, err := json.Marshal(manifest) + if err != nil { + return fmt.Errorf("encode mimir secret: %w", err) + } + apply := exec.CommandContext(ctx, "kubectl", withKubeconfig(kubeconfig, "apply", "-f", "-")...) + apply.Stdin = strings.NewReader(string(raw)) + if out, err := apply.CombinedOutput(); err != nil { + return fmt.Errorf("write mimir secret: %s", strings.TrimSpace(string(out))) + } + return nil +} + +func withKubeconfig(kubeconfig string, args ...string) []string { + if strings.TrimSpace(kubeconfig) == "" { + return args + } + return append([]string{"--kubeconfig", kubeconfig}, args...) +} + +func applyPanelSecret(ctx context.Context, install pterodactylInstall, kubeconfig string) error { + ns := exec.CommandContext(ctx, "kubectl", withKubeconfig(kubeconfig, "create", "namespace", install.Namespace)...) + if out, err := ns.CombinedOutput(); err != nil && !strings.Contains(string(out), "AlreadyExists") { + return fmt.Errorf("create namespace: %w", err) + } + manifest := map[string]any{ + "apiVersion": "v1", + "kind": "Secret", + "metadata": map[string]string{ + "name": install.SecretName, + "namespace": install.Namespace, + }, + "type": "Opaque", + "data": map[string]string{ + "PANEL_URL": base64.StdEncoding.EncodeToString([]byte(install.PanelURL)), + "APPLICATION_KEY": base64.StdEncoding.EncodeToString([]byte(install.ApplicationKey)), + "CLIENT_KEY": base64.StdEncoding.EncodeToString([]byte(install.ClientKey)), + "PANEL_USER_ID": base64.StdEncoding.EncodeToString([]byte(install.PanelUserID)), + }, + } + raw, err := json.Marshal(manifest) + if err != nil { + return fmt.Errorf("encode panel secret: %w", err) + } + apply := exec.CommandContext(ctx, "kubectl", withKubeconfig(kubeconfig, "apply", "-f", "-")...) + apply.Stdin = strings.NewReader(string(raw)) + if _, err := apply.CombinedOutput(); err != nil { + return fmt.Errorf("write panel secret: %w", err) + } + return nil +} diff --git a/internal/cli/cluster_pterodactyl_test.go b/internal/cli/cluster_pterodactyl_test.go new file mode 100644 index 0000000..a79bf49 --- /dev/null +++ b/internal/cli/cluster_pterodactyl_test.go @@ -0,0 +1,169 @@ +package cli + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func clearPterodactylEnv(t *testing.T) { + t.Helper() + for _, key := range []string{ + "PTERODACTYL_PANEL_URL", + "PTERODACTYL_APPLICATION_KEY", + "PTERODACTYL_APPLICATION_KEY_FILE", + "PTERODACTYL_CLIENT_KEY", + "PTERODACTYL_CLIENT_KEY_FILE", + "PTERODACTYL_PANEL_USER_ID", + "PTERODACTYL_OPERATOR_CHART", + } { + t.Setenv(key, "") + } +} + +func newPterodactylCmd(panelURL, appFile, clientFile, userID string) *cobra.Command { + cmd := &cobra.Command{} + cmd.Flags().String("panel-url", panelURL, "") + cmd.Flags().String("application-key-file", appFile, "") + cmd.Flags().String("client-key-file", clientFile, "") + cmd.Flags().String("panel-user-id", userID, "") + cmd.Flags().String("operator-chart", "", "") + cmd.Flags().String("pterodactyl-chart", "", "") + return cmd +} + +func TestPterodactylHelmArgsDisablesCRDSubchart(t *testing.T) { + args := pterodactylHelmArgs(pterodactylInstall{ + Chart: "oci://example.invalid/pterodactyl-operator", + Namespace: "pterodactyl-system", + PanelURL: "https://panel.example.com", + SecretName: "operator-pterodactyl-operator-panel-credentials", + }, "/tmp/kubeconfig") + joined := strings.Join(args, " ") + if !strings.Contains(joined, "--set crds.enabled=false") { + t.Fatalf("operator chart must not adopt CRDs installed before peering: %s", joined) + } +} + +func TestPterodactylHelmArgsSetsAlloy(t *testing.T) { + args := pterodactylHelmArgs(pterodactylInstall{ + Chart: "oci://example.invalid/pterodactyl-operator", + Namespace: "pterodactyl-system", + PanelURL: "https://panel.example.com", + SecretName: "operator-pterodactyl-operator-panel-credentials", + AgentID: "f93ae364-c92a-4501-ac20-c4564ffb86f7", + MimirEndpoint: "metrics.noderings.com", + MimirTLS: true, + MimirSecretName: "mimir-credentials", + }, "/tmp/kubeconfig") + joined := strings.Join(args, " ") + for _, want := range []string{ + "alloy.mimir.serviceEndpoint=metrics.noderings.com", + "alloy.mimir.tls.enabled=true", + "alloy.mimir.secretName=mimir-credentials", + "alloy.agentId=f93ae364-c92a-4501-ac20-c4564ffb86f7", + } { + if !strings.Contains(joined, want) { + t.Fatalf("missing %s in %s", want, joined) + } + } +} + +func TestInstallPterodactylRejectsMissingURL(t *testing.T) { + clearPterodactylEnv(t) + _, err := loadPterodactylInstall(newPterodactylCmd("", "", "", "1"), "operator-chart", true) + if !errors.Is(err, errPterodactylCredentialsRequired) { + t.Fatalf("expected credentials error, got %v", err) + } +} + +func TestPreflightPterodactylAllowsPromptLater(t *testing.T) { + clearPterodactylEnv(t) + if err := preflightPterodactylInstall(newPterodactylCmd("", "", "", "")); err != nil { + t.Fatal(err) + } +} + +func TestInstallPterodactylReadsEnv(t *testing.T) { + clearPterodactylEnv(t) + t.Setenv("PTERODACTYL_PANEL_URL", "http://192.168.1.111/") + t.Setenv("PTERODACTYL_APPLICATION_KEY", "ptla_env") + t.Setenv("PTERODACTYL_CLIENT_KEY", "ptlc_env") + t.Setenv("PTERODACTYL_PANEL_USER_ID", "4") + got, err := loadPterodactylInstall(newPterodactylCmd("", "", "", ""), "operator-chart", true) + if err != nil { + t.Fatal(err) + } + if got.PanelURL != "http://192.168.1.111" || got.ApplicationKey != "ptla_env" || got.ClientKey != "ptlc_env" || got.PanelUserID != "4" { + t.Fatalf("env credentials were not used: %+v", got) + } +} + +func TestHypervisorDriverRejectsPterodactyl(t *testing.T) { + _, err := parseHypervisorDriver("pterodactyl") + if err == nil || !strings.Contains(err.Error(), "unsupported") { + t.Fatalf("pterodactyl must not be a hypervisor driver, got %v", err) + } +} + +func TestInstallPterodactylRejectsHelmInjection(t *testing.T) { + clearPterodactylEnv(t) + _, err := loadPterodactylInstall(newPterodactylCmd("http://192.168.1.111,cluster.enabled=false", "", "", "1"), "operator-chart", true) + if err == nil || !strings.Contains(err.Error(), "--panel-url") { + t.Fatalf("expected panel url error, got %v", err) + } +} + +func TestInstallPterodactylReadsKeyFiles(t *testing.T) { + dir := t.TempDir() + app := filepath.Join(dir, "app") + client := filepath.Join(dir, "client") + if err := os.WriteFile(app, []byte("ptla_test\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(client, []byte("ptlc_test\n"), 0o600); err != nil { + t.Fatal(err) + } + clearPterodactylEnv(t) + t.Setenv("PTERODACTYL_PANEL_URL", "http://evil.example") + t.Setenv("PTERODACTYL_APPLICATION_KEY", "ptla_ignored") + got, err := loadPterodactylInstall(newPterodactylCmd("http://192.168.1.111", app, client, "1"), "operator-chart", true) + if err != nil { + t.Fatal(err) + } + if got.PanelURL != "http://192.168.1.111" || got.ApplicationKey != "ptla_test" || got.ClientKey != "ptlc_test" { + t.Fatal("flags did not override env") + } + if got.Namespace != "pterodactyl-system" { + t.Fatalf("namespace %s", got.Namespace) + } +} + +func TestInstallPterodactylReadsKeyFileEnv(t *testing.T) { + dir := t.TempDir() + app := filepath.Join(dir, "app") + client := filepath.Join(dir, "client") + if err := os.WriteFile(app, []byte("ptla_file\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(client, []byte("ptlc_file\n"), 0o600); err != nil { + t.Fatal(err) + } + clearPterodactylEnv(t) + t.Setenv("PTERODACTYL_PANEL_URL", "https://panel.example.com") + t.Setenv("PTERODACTYL_APPLICATION_KEY_FILE", app) + t.Setenv("PTERODACTYL_APPLICATION_KEY", "ptla_ignored") + t.Setenv("PTERODACTYL_CLIENT_KEY_FILE", client) + t.Setenv("PTERODACTYL_PANEL_USER_ID", "3") + got, err := loadPterodactylInstall(newPterodactylCmd("", "", "", ""), "operator-chart", true) + if err != nil { + t.Fatal(err) + } + if got.ApplicationKey != "ptla_file" || got.ClientKey != "ptlc_file" || got.PanelUserID != "3" { + t.Fatalf("key files from env were not used: %+v", got) + } +} diff --git a/internal/cli/cluster_register_opts.go b/internal/cli/cluster_register_opts.go index 59d9aba..86b352d 100644 --- a/internal/cli/cluster_register_opts.go +++ b/internal/cli/cluster_register_opts.go @@ -10,6 +10,8 @@ import ( "github.com/noderings/cli/internal/install" "github.com/noderings/cli/internal/logger" "github.com/noderings/cli/internal/state" + + "github.com/spf13/cobra" ) type clusterRegisterOpts struct { @@ -20,6 +22,8 @@ type clusterRegisterOpts struct { operatorChartPath string operatorChartVersion string hypervisorDriver string + installPterodactyl bool + command *cobra.Command proxmoxInstancesFile string virtfusionInstancesFile string solusvmInstancesFile string @@ -174,9 +178,14 @@ func collectOffloadNamespaces(opts clusterRegisterOpts) []string { out = append(out, ns) } - // VNC first (production default). Operator is only included when explicitly set - // via --operator-namespace (normally offloaded from the remote cluster after inbound peering). + // VNC first (production default). The game console Service is offloaded the same + // way when --pterodactyl is set: local pterodactyl-system, remote {agentID}-pterodactyl-system. + // Operator is only included when explicitly set via --operator-namespace + // (normally offloaded from the remote cluster after inbound peering). add(opts.vncGatewayNamespace) + if opts.installPterodactyl { + add(config.DefaultPterodactylOperatorHelmNamespace) + } add(opts.operatorNamespace) for _, ns := range opts.offloadNamespaces { add(ns) @@ -194,14 +203,17 @@ func parseHypervisorDriver(raw string) (string, error) { return config.HypervisorDriverVirtFusion, nil case config.HypervisorDriverSolusVM: return config.HypervisorDriverSolusVM, nil + case "pterodactyl": + return "", UsageErrorf("unsupported --hypervisor-driver %q. Pass --pterodactyl for game servers. --hypervisor-driver is proxmox, virtfusion, or solusvm", raw) default: return "", UsageErrorf("unsupported --hypervisor-driver %q (want proxmox, virtfusion, or solusvm)", raw) } } // resolveHypervisorDriver uses an explicit flag, then the org driver. -// There is no proxmox default: an empty org with no flag is an error. -func resolveHypervisorDriver(flagRaw string, flagChanged bool, orgDriver string) (string, error) { +// allowUnset is for a Pterodactyl-only agent: no hypervisor until one is added later. +// There is no proxmox default. An empty org with no flag is an error unless allowUnset. +func resolveHypervisorDriver(flagRaw string, flagChanged bool, orgDriver string, allowUnset bool) (string, error) { org := strings.TrimSpace(orgDriver) if flagChanged { parsed, err := parseHypervisorDriver(flagRaw) @@ -222,7 +234,10 @@ func resolveHypervisorDriver(flagRaw string, flagChanged bool, orgDriver string) if org != "" { return parseHypervisorDriver(org) } - return "", UsageErrorf("this organization has no hypervisor driver yet. Pass --hypervisor-driver (proxmox, virtfusion, or solusvm) when registering the first agent") + if allowUnset { + return "", nil + } + return "", UsageErrorf("this organization has no hypervisor driver yet. Pass --hypervisor-driver (proxmox, virtfusion, or solusvm), or --pterodactyl for game servers only") } func hypervisorDriverToAPI(driver string) *generated.V1PlatformDriver { @@ -253,10 +268,14 @@ func validateRegisterHypervisorOpts(opts clusterRegisterOpts) error { if pveFile != "" || svmFile != "" { return UsageErrorf("--proxmox-instances-file and --solusvm-instances-file are not valid with --hypervisor-driver virtfusion (use --virtfusion-instances-file)") } - case config.HypervisorDriverProxmox, "": + case config.HypervisorDriverProxmox: if vfFile != "" || svmFile != "" { return UsageErrorf("--virtfusion-instances-file and --solusvm-instances-file are not valid with --hypervisor-driver proxmox") } + case "": + if pveFile != "" || vfFile != "" || svmFile != "" { + return UsageErrorf("hypervisor instance files need --hypervisor-driver (proxmox, virtfusion, or solusvm)") + } } return nil } diff --git a/internal/cli/cluster_register_opts_test.go b/internal/cli/cluster_register_opts_test.go index 2666a1e..1326a23 100644 --- a/internal/cli/cluster_register_opts_test.go +++ b/internal/cli/cluster_register_opts_test.go @@ -140,6 +140,25 @@ func TestCollectOffloadNamespaces(t *testing.T) { if len(withOperator) != len(wantWithOp) { t.Fatalf("got %v, want %v", withOperator, wantWithOp) } + for i := range wantWithOp { + if withOperator[i] != wantWithOp[i] { + t.Fatalf("got %v, want %v", withOperator, wantWithOp) + } + } + + withGame := collectOffloadNamespaces(clusterRegisterOpts{ + vncGatewayNamespace: config.DefaultVNCGatewayNamespace, + installPterodactyl: true, + }) + wantGame := []string{config.DefaultVNCGatewayNamespace, config.DefaultPterodactylOperatorHelmNamespace} + if len(withGame) != len(wantGame) { + t.Fatalf("got %v, want %v", withGame, wantGame) + } + for i := range wantGame { + if withGame[i] != wantGame[i] { + t.Fatalf("got %v, want %v", withGame, wantGame) + } + } } func TestParseHypervisorDriver(t *testing.T) { @@ -169,26 +188,47 @@ func TestParseHypervisorDriver(t *testing.T) { func TestResolveHypervisorDriver(t *testing.T) { t.Parallel() - if _, err := resolveHypervisorDriver("", false, ""); err == nil { + if _, err := resolveHypervisorDriver("", false, "", false); err == nil { t.Fatal("expected error when org has no driver") } else if !strings.Contains(err.Error(), "--hypervisor-driver") { t.Fatalf("empty-org error should mention --hypervisor-driver, got %v", err) } - got, err := resolveHypervisorDriver("", false, config.HypervisorDriverVirtFusion) + got, err := resolveHypervisorDriver("", false, config.HypervisorDriverVirtFusion, false) if err != nil || got != config.HypervisorDriverVirtFusion { t.Fatalf("inherit org got %q err=%v", got, err) } - got, err = resolveHypervisorDriver("solusvm", true, config.HypervisorDriverSolusVM) + got, err = resolveHypervisorDriver("solusvm", true, config.HypervisorDriverSolusVM, false) if err != nil || got != config.HypervisorDriverSolusVM { t.Fatalf("matching flag got %q err=%v", got, err) } - if _, err := resolveHypervisorDriver("solusvm", true, config.HypervisorDriverVirtFusion); err == nil { + if _, err := resolveHypervisorDriver("solusvm", true, config.HypervisorDriverVirtFusion, false); err == nil { t.Fatal("expected mismatch error") } - got, err = resolveHypervisorDriver("virtfusion", true, "") + got, err = resolveHypervisorDriver("virtfusion", true, "", false) if err != nil || got != config.HypervisorDriverVirtFusion { t.Fatalf("explicit flag with empty org got %q err=%v", got, err) } + got, err = resolveHypervisorDriver("", false, "", true) + if err != nil || got != "" { + t.Fatalf("pterodactyl-only got %q err=%v", got, err) + } + got, err = resolveHypervisorDriver("", false, config.HypervisorDriverProxmox, true) + if err != nil || got != config.HypervisorDriverProxmox { + t.Fatalf("pterodactyl on an existing hypervisor org got %q err=%v", got, err) + } +} + +func TestConflictingHypervisorNamespace(t *testing.T) { + t.Parallel() + if err := conflictingHypervisorNamespace(nil, config.HypervisorDriverProxmox); err != nil { + t.Fatal(err) + } + if err := conflictingHypervisorNamespace([]string{config.DefaultProxmoxOperatorHelmNamespace}, config.HypervisorDriverProxmox); err != nil { + t.Fatal(err) + } + if err := conflictingHypervisorNamespace([]string{config.DefaultProxmoxOperatorHelmNamespace}, config.HypervisorDriverVirtFusion); err == nil { + t.Fatal("expected a second hypervisor to be rejected") + } } func TestValidateRegisterHypervisorOpts(t *testing.T) { diff --git a/internal/cli/operator_collect.go b/internal/cli/operator_collect.go index 525907d..b3330e1 100644 --- a/internal/cli/operator_collect.go +++ b/internal/cli/operator_collect.go @@ -47,10 +47,10 @@ func collectOperatorInstallInputs( if nonInteractive { return fmt.Errorf("proxmox credentials required: set PROXMOX_* env, --proxmox-instances-file, or run interactively (without --yes)") } - log.Info("Configure Proxmox API access for the operator (supports multiple instances)") + beginCredentialPrompt("Configure Proxmox API access for the operator (supports multiple instances)") for i := 0; ; i++ { defaultID := fmt.Sprintf("proxmox-%d", i+1) - id, err := promptString("Proxmox instance ID (local to this agent, not the platform name)", defaultID) + id, err := promptString("Proxmox instance ID (use the same name you use in the NodeRings UI when defining the platform)", defaultID) if err != nil { return err } @@ -139,11 +139,11 @@ func collectVirtFusionOperatorInstallInputs( if nonInteractive { return fmt.Errorf("virtfusion credentials required: set VIRTFUSION_URL, VIRTFUSION_TOKEN, VIRTFUSION_USER_API_TOKEN, VIRTFUSION_USER_ID, VIRTFUSION_USER_NAME, --virtfusion-instances-file, or run interactively (without --yes)") } - log.Info("Configure VirtFusion API access for the operator (supports multiple instances)") log.Info("Create a normal VirtFusion client user (not an admin). Copy the numeric user ID. Log in as that user and generate a User API token under Account → API.") + beginCredentialPrompt("Configure VirtFusion API access for the operator (supports multiple instances)") for i := 0; ; i++ { defaultID := fmt.Sprintf("vf-%d", i+1) - id, err := promptString("VirtFusion instance ID (local to this agent, not the platform name)", defaultID) + id, err := promptString("VirtFusion instance ID (use the same name you use in the NodeRings UI when defining the platform)", defaultID) if err != nil { return err } @@ -241,10 +241,10 @@ func collectSolusVMOperatorInstallInputs( if nonInteractive { return fmt.Errorf("solusvm credentials required: set SOLUSVM_URL and SOLUSVM_TOKEN, --solusvm-instances-file, or run interactively (without --yes)") } - log.Info("Configure SolusVM 2 API access for the operator (supports multiple instances)") + beginCredentialPrompt("Configure SolusVM 2 API access for the operator (supports multiple instances)") for i := 0; ; i++ { defaultID := fmt.Sprintf("svm-%d", i+1) - id, err := promptString("SolusVM instance ID (local to this agent, not the platform name)", defaultID) + id, err := promptString("SolusVM instance ID (use the same name you use in the NodeRings UI when defining the platform)", defaultID) if err != nil { return err } diff --git a/internal/cli/prompt.go b/internal/cli/prompt.go index c0a2c62..f93beb7 100644 --- a/internal/cli/prompt.go +++ b/internal/cli/prompt.go @@ -19,7 +19,7 @@ func confirmYesNo(question, nonInteractiveHint string) (bool, error) { return false, fmt.Errorf("stdin is not a terminal; %s", nonInteractiveHint) } - fmt.Fprintf(os.Stderr, "%s [y/N]: ", question) + fmt.Fprintf(os.Stderr, "%s [y/N]: ", colorPromptLabel(question)) reader := bufio.NewReader(os.Stdin) line, err := reader.ReadString('\n') if err != nil { @@ -37,6 +37,41 @@ func isStdoutTerminal() bool { return term.IsTerminal(int(os.Stdout.Fd())) } +func isStderrTerminal() bool { + return term.IsTerminal(int(os.Stderr.Fd())) +} + +func promptColorEnabled() bool { + return isStderrTerminal() && os.Getenv("NO_COLOR") == "" +} + +// beginCredentialPrompt marks the start of an interactive Proxmox, VirtFusion, +// SolusVM, or Pterodactyl question block. The rule and title stay plain when +// stderr is not a terminal. +func beginCredentialPrompt(title string) { + fmt.Fprintln(os.Stderr) + fmt.Fprint(os.Stderr, formatCredentialBanner(title, promptColorEnabled())) +} + +func formatCredentialBanner(title string, color bool) string { + line := "========" + waiting := "Waiting for your input. What you type is shown." + if !color { + return line + "\n" + title + "\n" + line + "\n" + waiting + "\n" + } + return "\033[1;36m" + line + "\033[0m\n" + + "\033[1;33m" + title + "\033[0m\n" + + "\033[1;36m" + line + "\033[0m\n" + + "\033[2m" + waiting + "\033[0m\n" +} + +func colorPromptLabel(label string) string { + if !promptColorEnabled() { + return label + } + return "\033[1;33m" + label + "\033[0m" +} + // promptVisibleToken asks for an API token with echo on. Do not add a // promptSecret / term.ReadPassword path: hidden paste looks like it failed. func promptVisibleToken(label string) (string, error) { @@ -56,9 +91,9 @@ func promptString(label, defaultValue string) (string, error) { return "", fmt.Errorf("stdin is not a terminal; set env/flags or --proxmox-instances-file / --virtfusion-instances-file for non-interactive install") } if defaultValue != "" { - fmt.Fprintf(os.Stderr, "%s [%s]: ", label, defaultValue) + fmt.Fprintf(os.Stderr, "%s [%s]: ", colorPromptLabel(label), defaultValue) } else { - fmt.Fprintf(os.Stderr, "%s: ", label) + fmt.Fprintf(os.Stderr, "%s: ", colorPromptLabel(label)) } reader := bufio.NewReader(os.Stdin) line, err := reader.ReadString('\n') diff --git a/internal/cli/prompt_banner_test.go b/internal/cli/prompt_banner_test.go new file mode 100644 index 0000000..55640c1 --- /dev/null +++ b/internal/cli/prompt_banner_test.go @@ -0,0 +1,40 @@ +package cli + +import ( + "strings" + "testing" +) + +func TestCredentialBannerPlain(t *testing.T) { + got := formatCredentialBanner("Configure Proxmox API access", false) + if strings.Contains(got, "\033") { + t.Fatalf("plain banner included color: %q", got) + } + if !strings.Contains(got, "========\nConfigure Proxmox API access\n========\n") { + t.Fatalf("banner shape: %q", got) + } + if !strings.Contains(got, "Waiting for your input") { + t.Fatalf("missing wait line: %q", got) + } +} + +func TestCredentialBannerColor(t *testing.T) { + got := formatCredentialBanner("Configure Pterodactyl panel access", true) + if !strings.Contains(got, "\033[1;36m========\033[0m") { + t.Fatalf("missing rule color: %q", got) + } + if !strings.Contains(got, "\033[1;33mConfigure Pterodactyl panel access\033[0m") { + t.Fatalf("missing title color: %q", got) + } +} + +func TestWithKubeconfig(t *testing.T) { + plain := withKubeconfig("", "apply", "-f", "-") + if len(plain) != 3 || plain[0] != "apply" { + t.Fatalf("empty kubeconfig: %#v", plain) + } + got := withKubeconfig("/etc/rancher/k3s/k3s.yaml", "upgrade", "--install") + if got[0] != "--kubeconfig" || got[1] != "/etc/rancher/k3s/k3s.yaml" || got[2] != "upgrade" { + t.Fatalf("kubeconfig args: %#v", got) + } +} diff --git a/internal/config/constants.go b/internal/config/constants.go index 512414a..93c1181 100644 --- a/internal/config/constants.go +++ b/internal/config/constants.go @@ -169,6 +169,13 @@ const ( DefaultSolusVMOperatorHelmNamespace = "solusvm-system" // SolusVMCRDAPIGroup is the API group registered by solusvm-operator CRDs. SolusVMCRDAPIGroup = "vm.solusvm.com" + + // Pterodactyl is a second release on the agent, not a hypervisor driver. + DefaultPterodactylOperatorChartOCI = "oci://" + DefaultHarborRegistry + "/" + DefaultHarborPublicProject + "/pterodactyl-operator" + DefaultPterodactylOperatorCRDsChartOCI = "oci://" + DefaultHarborRegistry + "/" + DefaultHarborPublicProject + "/pterodactyl-operator-crds" + DefaultPterodactylOperatorChartVersion = "0.1.0" + DefaultPterodactylOperatorHelmNamespace = "pterodactyl-system" + PterodactylCRDAPIGroup = "gs.pterodactyl.com" // DefaultHypervisorCRDsHelmNamespace is where standalone CRD charts are // installed (cluster-scoped CRDs, not the operator runtime namespace). DefaultHypervisorCRDsHelmNamespace = "kube-system" @@ -237,6 +244,8 @@ const ( EnvProxmoxOperatorCRDsChart = "PROXMOX_OPERATOR_CRDS_CHART" EnvVirtFusionOperatorCRDsChart = "VIRTFUSION_OPERATOR_CRDS_CHART" EnvSolusVMOperatorCRDsChart = "SOLUSVM_OPERATOR_CRDS_CHART" + EnvPterodactylOperatorChart = "PTERODACTYL_OPERATOR_CHART" + EnvPterodactylOperatorCRDsChart = "PTERODACTYL_OPERATOR_CRDS_CHART" EnvHypervisorOperatorCRDsChartVersion = "HYPERVISOR_OPERATOR_CRDS_CHART_VERSION" EnvMimirServiceEndpoint = "MIMIR_SERVICE_ENDPOINT" //nolint:gosec // G101: environment variable name, not a credential value diff --git a/internal/install/helm_cli.go b/internal/install/helm_cli.go index ce8781f..f5c671f 100644 --- a/internal/install/helm_cli.go +++ b/internal/install/helm_cli.go @@ -40,9 +40,10 @@ const ( helmCRDCannotImport = "exists and cannot be imported" helmChartFile = "Chart.yaml" - helmReleaseProxmoxCRDs = "proxmox-operator-crds" - helmReleaseVirtFusionCRDs = "virtfusion-operator-crds" - helmReleaseSolusVMCRDs = "solusvm-operator-crds" + helmReleaseProxmoxCRDs = "proxmox-operator-crds" + helmReleaseVirtFusionCRDs = "virtfusion-operator-crds" + helmReleaseSolusVMCRDs = "solusvm-operator-crds" + helmReleasePterodactylCRDs = "pterodactyl-operator-crds" kubectlCmdApply = "apply" kubectlCmdAnnotate = "annotate" diff --git a/internal/install/hypervisor_crds.go b/internal/install/hypervisor_crds.go index beb9290..0929103 100644 --- a/internal/install/hypervisor_crds.go +++ b/internal/install/hypervisor_crds.go @@ -50,6 +50,13 @@ func hypervisorCRDCharts() []hypervisorCRDChart { oci: config.DefaultSolusVMOperatorCRDsChartOCI, version: crdChartVersion(config.DefaultSolusVMOperatorChartVersion), }, + { + release: helmReleasePterodactylCRDs, + envKey: config.EnvPterodactylOperatorCRDsChart, + sibling: operatorChartSiblings(helmReleasePterodactylCRDs), + oci: config.DefaultPterodactylOperatorCRDsChartOCI, + version: crdChartVersion(config.DefaultPterodactylOperatorChartVersion), + }, } } @@ -61,9 +68,11 @@ func localOperatorChartEnvs() []string { config.EnvProxmoxOperatorCRDsChart, config.EnvVirtFusionOperatorCRDsChart, config.EnvSolusVMOperatorCRDsChart, + config.EnvPterodactylOperatorCRDsChart, config.EnvProxmoxOperatorChart, config.EnvVirtFusionOperatorChart, config.EnvSolusVMOperatorChart, + config.EnvPterodactylOperatorChart, } } @@ -184,6 +193,7 @@ func hypervisorCRDAPIGroups() []string { config.ProxmoxCRDAPIGroup, config.VirtFusionCRDAPIGroup, config.SolusVMCRDAPIGroup, + config.PterodactylCRDAPIGroup, } } @@ -267,9 +277,9 @@ func helmCRDOCIHint(c hypervisorCRDChart, chart string) string { if !isOCIRef(chart) { return "" } - return fmt.Sprintf("\nset %s to a local chart dir, or place %s next to %s / %s / %s", + return fmt.Sprintf("\nset %s to a local chart dir, or place %s next to %s / %s / %s / %s", c.envKey, c.release, - config.EnvVirtFusionOperatorChart, config.EnvProxmoxOperatorChart, config.EnvSolusVMOperatorChart) + config.EnvVirtFusionOperatorChart, config.EnvProxmoxOperatorChart, config.EnvSolusVMOperatorChart, config.EnvPterodactylOperatorChart) } func ensureOneCRDChart(ctx context.Context, kubeconfig string, c hypervisorCRDChart, logger Logger) error { @@ -291,7 +301,7 @@ func ensureOneCRDChart(ctx context.Context, kubeconfig string, c hypervisorCRDCh return fmt.Errorf("helm %s: %w\n%s%s", c.release, err, out, helmCRDOCIHint(c, chart)) } -// EnsureHypervisorCRDs installs the Proxmox, VirtFusion, and SolusVM CRD charts. +// EnsureHypervisorCRDs installs the Proxmox, VirtFusion, SolusVM, and Pterodactyl CRD charts. // Mothership Liqo AllowList always includes those API groups; missing CRDs on a // provider stall custom-resource informers with "the server could not find the requested resource". // @@ -309,3 +319,9 @@ func EnsureHypervisorCRDs(ctx context.Context, kubeconfig string, logger Logger) } return nil } + +// AnnotateOperatorCRDsKeep marks operator CRDs so a later chart upgrade with +// crds.enabled=false does not delete them. +func AnnotateOperatorCRDsKeep(ctx context.Context, kubeconfig string, logger Logger) error { + return keepHypervisorCRDsFromHelmPrune(ctx, kubeconfig, logger) +} diff --git a/internal/install/hypervisor_crds_test.go b/internal/install/hypervisor_crds_test.go index e940171..d34ae86 100644 --- a/internal/install/hypervisor_crds_test.go +++ b/internal/install/hypervisor_crds_test.go @@ -111,6 +111,15 @@ func TestResolveCRDChartFallsBackToDefaultOCI(t *testing.T) { if ver != config.DefaultSolusVMOperatorChartVersion { t.Fatalf("solusvm version=%q", ver) } + + ptero := crdChartNamed(t, helmReleasePterodactylCRDs) + got, ver = resolveCRDChart(ptero) + if got != config.DefaultPterodactylOperatorCRDsChartOCI { + t.Fatalf("pterodactyl oci=%q", got) + } + if ver != config.DefaultPterodactylOperatorChartVersion { + t.Fatalf("pterodactyl version=%q", ver) + } } func TestIsHelmCRDOwnershipConflict(t *testing.T) { @@ -140,6 +149,9 @@ func TestIsHypervisorCRDName(t *testing.T) { if !isHypervisorCRDName("solusvmvms." + config.SolusVMCRDAPIGroup) { t.Fatal("solusvm") } + if !isHypervisorCRDName("pterodactylgamecatalogs." + config.PterodactylCRDAPIGroup) { + t.Fatal("pterodactyl") + } if isHypervisorCRDName("connections.networking.liqo.io") { t.Fatal("liqo must not be treated as a hypervisor CRD") } diff --git a/internal/install/liqo-provider-values.yaml b/internal/install/liqo-provider-values.yaml index 17a2a99..a602ee8 100644 --- a/internal/install/liqo-provider-values.yaml +++ b/internal/install/liqo-provider-values.yaml @@ -136,8 +136,25 @@ offloading: resource: solusvmvncrequests workers: 2 type: AllowList + - group: gs.pterodactyl.com + version: v1alpha1 + resource: pterodactylservers + workers: 2 + type: AllowList + - group: gs.pterodactyl.com + version: v1alpha1 + resource: pterodactylactions + workers: 2 + type: AllowList + - group: gs.pterodactyl.com + version: v1alpha1 + resource: pterodactylgamecatalogs + workers: 2 + type: AllowList skip: annotations: + - kopf.zalando.org/last-handled-configuration - virtfusion-operator.kopf.dev/last-handled-configuration - solusvm-operator.kopf.dev/last-handled-configuration - proxmox-operator.kopf.dev/last-handled-configuration + - pterodactyl-operator.kopf.dev/last-handled-configuration diff --git a/internal/install/liqo.go b/internal/install/liqo.go index 98e1f5f..6a60bc0 100644 --- a/internal/install/liqo.go +++ b/internal/install/liqo.go @@ -73,7 +73,7 @@ func (l *LiqoManager) Install(ctx context.Context) error { // Check if Liqo is already installed if l.isInstalled(ctx) { l.logger.Info("Liqo appears to be already installed, skipping installation") - return nil + return l.PrepareGameCatalogReflection(ctx) } // Execute liqoctl install k3s with proper flags @@ -172,7 +172,7 @@ func (l *LiqoManager) Install(ctx context.Context) error { } l.logger.Info("✓ Liqo installed successfully") - return nil + return l.PrepareGameCatalogReflection(ctx) } // prepareLocalChart pulls the Harbor OCI chart (when configured) and returns an extracted chart path. diff --git a/internal/install/pterodactyl_reflection.go b/internal/install/pterodactyl_reflection.go new file mode 100644 index 0000000..9761322 --- /dev/null +++ b/internal/install/pterodactyl_reflection.go @@ -0,0 +1,118 @@ +package install + +import ( + "context" + "fmt" + "slices" + + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + + "github.com/noderings/cli/internal/config" +) + +const ( + catalogAPIGroup = config.PterodactylCRDAPIGroup + catalogResource = "pterodactylgamecatalogs" + vkRoleLocal = "liqo-virtual-kubelet-local" + vkRoleRemote = "liqo-virtual-kubelet-remote" +) + +// PrepareGameCatalogReflection installs the operator CRDs and the Liqo role +// rules a new virtual-kubelet needs to reflect PterodactylGameCatalog. +// Already-installed Liqo does not re-apply its values, so this runs on every +// install, including the skip path. +func (l *LiqoManager) PrepareGameCatalogReflection(ctx context.Context) error { + if l.k8sClient == nil || l.k8sClient.GetClientset() == nil { + return fmt.Errorf("kubernetes client is not connected") + } + if err := EnsureHypervisorCRDs(ctx, l.getKubeconfigPath(), l.logger); err != nil { + return err + } + return ensureCatalogClusterRoles(ctx, l.k8sClient.GetClientset()) +} + +func ensureCatalogClusterRoles(ctx context.Context, cs kubernetes.Interface) error { + if err := ensureCatalogRole(ctx, cs, vkRoleLocal, localCatalogRules()); err != nil { + return err + } + return ensureCatalogRole(ctx, cs, vkRoleRemote, remoteCatalogRules()) +} + +func ensureCatalogRole(ctx context.Context, cs kubernetes.Interface, name string, want []rbacv1.PolicyRule) error { + role, err := cs.RbacV1().ClusterRoles().Get(ctx, name, metav1.GetOptions{}) + if err != nil { + if apierrors.IsNotFound(err) { + return fmt.Errorf("ClusterRole %s is missing; Liqo is not ready to reflect the game catalog", name) + } + return fmt.Errorf("get ClusterRole %s: %w", name, err) + } + next, changed := mergeCatalogRules(role.Rules, want) + if !changed { + return nil + } + role.Rules = next + if _, err := cs.RbacV1().ClusterRoles().Update(ctx, role, metav1.UpdateOptions{}); err != nil { + return fmt.Errorf("update ClusterRole %s: %w", name, err) + } + return nil +} + +func localCatalogRules() []rbacv1.PolicyRule { + return []rbacv1.PolicyRule{ + {APIGroups: []string{catalogAPIGroup}, Resources: []string{catalogResource}, Verbs: []string{"get", "list", "watch"}}, + {APIGroups: []string{catalogAPIGroup}, Resources: []string{catalogResource + "/status"}, Verbs: []string{"get", "patch", "update"}}, + } +} + +func remoteCatalogRules() []rbacv1.PolicyRule { + return []rbacv1.PolicyRule{ + {APIGroups: []string{catalogAPIGroup}, Resources: []string{catalogResource}, Verbs: []string{"create", "delete", "get", "list", "patch", "update", "watch"}}, + } +} + +func mergeCatalogRules(have, want []rbacv1.PolicyRule) ([]rbacv1.PolicyRule, bool) { + changed := false + for _, rule := range want { + if catalogRuleCovered(have, rule) { + continue + } + have = append(have, rule) + changed = true + } + return have, changed +} + +func catalogRuleCovered(have []rbacv1.PolicyRule, want rbacv1.PolicyRule) bool { + for _, rule := range have { + if !sameCatalogStrings(rule.APIGroups, want.APIGroups) || !sameCatalogStrings(rule.Resources, want.Resources) { + continue + } + if catalogVerbsCover(rule.Verbs, want.Verbs) { + return true + } + } + return false +} + +func catalogVerbsCover(have, want []string) bool { + for _, verb := range want { + if !slices.Contains(have, verb) && !slices.Contains(have, "*") { + return false + } + } + return true +} + +func sameCatalogStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + left := append([]string(nil), a...) + right := append([]string(nil), b...) + slices.Sort(left) + slices.Sort(right) + return slices.Equal(left, right) +} diff --git a/internal/install/pterodactyl_reflection_test.go b/internal/install/pterodactyl_reflection_test.go new file mode 100644 index 0000000..06d54e5 --- /dev/null +++ b/internal/install/pterodactyl_reflection_test.go @@ -0,0 +1,23 @@ +package install + +import ( + "testing" + + rbacv1 "k8s.io/api/rbac/v1" +) + +func TestMergeCatalogRulesSkipsCoveredVerbs(t *testing.T) { + have := []rbacv1.PolicyRule{{ + APIGroups: []string{catalogAPIGroup}, + Resources: []string{catalogResource}, + Verbs: []string{"get", "list", "watch"}, + }} + next, changed := mergeCatalogRules(have, localCatalogRules()[:1]) + if changed || len(next) != 1 { + t.Fatalf("covered rule was added: changed=%v len=%d", changed, len(next)) + } + next, changed = mergeCatalogRules(have, remoteCatalogRules()) + if !changed || len(next) != 2 { + t.Fatalf("missing verbs were not added: changed=%v len=%d", changed, len(next)) + } +}