All files / src/commands/k8s k8s.create.command.js

58.82% Statements 100/170
100% Branches 1/1
0% Functions 0/4
58.82% Lines 100/170

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x     193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x     193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x       193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                                                                                                               193x 193x  
import { z } from 'zod';
import { typewriterLogo } from '../../lib/ascii.js';
import { defineArgument } from '../../lib/define-argument.js';
import { defineCommand } from '../../lib/define-command.js';
import { defineOption } from '../../lib/define-option.js';
import { getK8sCluster, k8sCreate, k8sGetProduct } from '../../lib/k8s.js';
import { styleText } from '../../lib/style-text.js';
import { Logger } from '../../logger.js';
import { flavorCount, tags } from '../../parsers.js';
import { orgaIdOrNameOption, skipConfirmationOption } from '../global.options.js';
 
const DEPLOY_POLL_DELAY_MS = 10000;
 
export const k8sCreateCommand = defineCommand({
  description: 'Create a Kubernetes cluster',
  since: '4.3.0',
  options: {
    clusterVersion: defineOption({
      name: 'cluster-version',
      schema: z.string().optional(),
      description: 'Kubernetes version to deploy (e.g.: 1.36)',
      placeholder: 'cluster-version',
      complete: async () => {
        const product = await k8sGetProduct();
        return product.versions?.available ?? [];
      },
    }),
    description: defineOption({
      name: 'description',
      schema: z.string().max(4096).optional(),
      description: 'Free-form cluster description',
      placeholder: 'description',
    }),
    tag: defineOption({
      name: 'tag',
      schema: z.string().transform(tags).optional(),
      description: 'Semantic tags (comma-separated, e.g.: env:prod,team:platform)',
      placeholder: 'tag[,tag...]',
    }),
    autoscaling: defineOption({
      name: 'autoscaling',
      schema: z.boolean().default(false),
      description: 'Enable the cluster autoscaler',
    }),
    persistentStorage: defineOption({
      name: 'persistent-storage',
      schema: z.boolean().default(false),
      description: 'Enable persistent storage (Ceph CSI)',
    }),
    topology: defineOption({
      name: 'topology',
      schema: z
        .string()
        .transform((v) => v.toUpperCase())
        .optional(),
      description: 'Cluster topology (must be set with --flavor and --replication-factor)',
      placeholder: 'topology',
      complete: async () => {
        const product = await k8sGetProduct();
        return (product.topologies ?? []).map((t) => t.topology);
      },
    }),
    flavor: defineOption({
      name: 'flavor',
      schema: z
        .string()
        .transform((v) => v.toUpperCase())
        .optional(),
      description: 'Control plane flavor',
      placeholder: 'flavor',
      complete: async () => {
        const product = await k8sGetProduct();
        const flavors = new Set((product.topologies ?? []).flatMap((t) => t.availableFlavors ?? []));
        return [...flavors];
      },
    }),
    replicationFactor: defineOption({
      name: 'replication-factor',
      schema: z.coerce.number().int().optional(),
      description: 'Control plane replication factor',
      placeholder: 'replication-factor',
    }),
    nodeGroup: defineOption({
      name: 'nodegroup',
      schema: z.string().transform(flavorCount).optional(),
      description: 'Initial node group (format: <flavor>:<count>, e.g.: XS:3)',
      placeholder: 'flavor:count',
    }),
    yes: skipConfirmationOption,
    watch: defineOption({
      name: 'watch',
      schema: z.boolean().default(false),
      description: 'Watch the deployment until the cluster is deployed',
      aliases: ['w'],
    }),
    org: orgaIdOrNameOption,
  },
  args: [
    defineArgument({
      schema: z.string(),
      description: 'Kubernetes cluster name',
      placeholder: 'cluster-name',
    }),
  ],
  async handler(options, ...args) {
    const clusterName = args[0];
    const orgIdOrName = options.org;

    try {
      const cluster = await k8sCreate(clusterName, orgIdOrName, {
        version: options.clusterVersion,
        description: options.description,
        tags: options.tag,
        autoscaling: options.autoscaling,
        persistentStorage: options.persistentStorage,
        topology: options.topology,
        flavor: options.flavor,
        replicationFactor: options.replicationFactor,
        nodeGroup: options.nodeGroup,
        yes: options.yes,
      });

      if (options.watch) {
        await typewriterLogo();

        let deployedCluster = cluster;
        while (deployedCluster.status !== 'ACTIVE' && deployedCluster.status !== 'FAILED') {
          Logger.println(
            `⏳ Cluster status: ${styleText('yellow', deployedCluster.status)}. Waiting for ${DEPLOY_POLL_DELAY_MS / 1000}s before checking again...`,
          );
          await new Promise((resolve) => setTimeout(resolve, DEPLOY_POLL_DELAY_MS));

          deployedCluster = await getK8sCluster(orgIdOrName, cluster.id);
        }

        Logger.println('');
        switch (deployedCluster.status) {
          case 'ACTIVE':
            Logger.printSuccess(
              `Cluster ${styleText('green', `${deployedCluster.name} (${deployedCluster.id})`)} deployed successfully`,
            );
            break;
          case 'FAILED':
            throw new Error(
              `Cluster ${styleText('red', `${deployedCluster.name} (${deployedCluster.id})`)} deployment failed`,
            );
          default:
            throw new Error(`Unexpected cluster status: ${deployedCluster.status}`);
        }
      } else {
        Logger.println(`🚀 Cluster ${styleText('white', `${cluster.name} (${cluster.id})`)} is being deployed`);
      }

      const orgMessageComplement = orgIdOrName ? `--org "${orgIdOrName.orga_id || orgIdOrName.orga_name}"` : '';

      Logger.println('');
      Logger.println(
        `You can get its information with ${styleText('blue', `clever k8s get ${cluster.id} ${orgMessageComplement}`)}`,
      );
    } catch (error) {
      if (error.responseBody?.code === 'clever.core.quota-exceeded') {
        throw new Error(
          'Failed to create Kubernetes cluster: your quota exceeded, contact support to increase your quota',
        );
      } else {
        throw new Error(error.message);
      }
    }
  },
});