server.go

212 lines
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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
package digitalocean

import (
	"fmt"
	"strings"
	"time"

	"congo.gg/pkg/platform"
	"github.com/digitalocean/godo"
)

// CreateServer creates a DigitalOcean droplet
func (b *backend) CreateServer(opts platform.ServerOptions) (*platform.Server, error) {
	// Translate region and size
	region, ok := regions[opts.Region]
	if !ok {
		return nil, fmt.Errorf("%w: %s", platform.ErrUnsupportedRegion, opts.Region)
	}
	size, ok := sizes[opts.Size]
	if !ok {
		return nil, fmt.Errorf("%w: %s", platform.ErrUnsupportedSize, opts.Size)
	}

	// Handle SSH key (expects fingerprint from GetSSHKeyFingerprint)
	var sshKeyIDs []godo.DropletCreateSSHKey
	if opts.SSHKey != "" {
		sshKeyIDs = append(sshKeyIDs, godo.DropletCreateSSHKey{Fingerprint: opts.SSHKey})
	}

	createReq := &godo.DropletCreateRequest{
		Name:    opts.Name,
		Region:  region,
		Size:    size,
		Image:   godo.DropletCreateImage{Slug: opts.Image},
		SSHKeys: sshKeyIDs,
		Tags:    opts.Tags,
		Backups: opts.Backups,
	}

	// Associate with VPC for private networking
	if opts.VpcID != "" {
		createReq.VPCUUID = opts.VpcID
	}

	droplet, _, err := b.client.Droplets.Create(b.ctx, createReq)
	if err != nil {
		return nil, fmt.Errorf("create droplet: %w", err)
	}

	return b.waitForDroplet(droplet.ID)
}

// GetServer retrieves a droplet by name
func (b *backend) GetServer(name string) (*platform.Server, error) {
	droplets, _, err := b.client.Droplets.ListByName(b.ctx, name, nil)
	if err != nil {
		return nil, fmt.Errorf("list droplets: %w", err)
	}

	for _, d := range droplets {
		if d.Name == name {
			return b.dropletToServer(&d), nil
		}
	}

	return nil, platform.ErrNotFound
}

// DeleteServer destroys a droplet
func (b *backend) DeleteServer(id string) error {
	// DigitalOcean uses int IDs
	var dropletID int
	if _, err := fmt.Sscanf(id, "%d", &dropletID); err != nil {
		return fmt.Errorf("invalid droplet ID %q: %w", id, err)
	}

	_, err := b.client.Droplets.Delete(b.ctx, dropletID)
	if err != nil {
		if strings.Contains(err.Error(), "not found") {
			return platform.ErrNotFound
		}
		return fmt.Errorf("delete droplet: %w", err)
	}
	return nil
}

// Helper methods

func (b *backend) waitForDroplet(id int) (*platform.Server, error) {
	timeout := time.After(5 * time.Minute)
	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-timeout:
			return nil, platform.ErrTimeout
		case <-ticker.C:
			droplet, _, err := b.client.Droplets.Get(b.ctx, id)
			if err != nil {
				continue
			}
			if droplet.Status == "active" {
				return b.dropletToServer(droplet), nil
			}
		}
	}
}

func (b *backend) dropletToServer(d *godo.Droplet) *platform.Server {
	var publicIP, privateIP string
	for _, network := range d.Networks.V4 {
		switch network.Type {
		case "public":
			if publicIP == "" {
				publicIP = network.IPAddress
			}
		case "private":
			if privateIP == "" {
				privateIP = network.IPAddress
			}
		}
	}

	return &platform.Server{
		ID:        fmt.Sprintf("%d", d.ID),
		Name:      d.Name,
		IP:        publicIP,
		PrivateIP: privateIP,
		Size:      d.Size.Slug,
		Region:    d.Region.Slug,
		Status:    d.Status,
	}
}

// TagServer tags a droplet with a DigitalOcean tag.
// Creates the tag if it doesn't exist.
func (b *backend) TagServer(serverID string, tag string) error {
	// Ensure tag exists
	_, _, err := b.client.Tags.Get(b.ctx, tag)
	if err != nil {
		_, _, err = b.client.Tags.Create(b.ctx, &godo.TagCreateRequest{Name: tag})
		if err != nil && !strings.Contains(err.Error(), "already exists") {
			return fmt.Errorf("create tag %q: %w", tag, err)
		}
	}

	// Tag the droplet
	_, err = b.client.Tags.TagResources(b.ctx, tag, &godo.TagResourcesRequest{
		Resources: []godo.Resource{
			{ID: serverID, Type: godo.DropletResourceType},
		},
	})
	if err != nil {
		return fmt.Errorf("tag server %s with %q: %w", serverID, tag, err)
	}

	return nil
}

// GetSSHKeyFingerprint finds or registers an SSH key, returns its fingerprint.
func (b *backend) GetSSHKeyFingerprint(publicKey string) (string, error) {
	// List existing keys
	keys, _, err := b.client.Keys.List(b.ctx, nil)
	if err != nil {
		return "", err
	}

	// Compare just the key type and data (not the comment)
	// Trim whitespace to handle trailing newlines
	publicKey = strings.TrimSpace(publicKey)
	keyParts := strings.Fields(publicKey)
	keyContent := ""
	if len(keyParts) >= 2 {
		keyContent = keyParts[0] + " " + keyParts[1]
	}

	for _, k := range keys {
		existingParts := strings.Fields(strings.TrimSpace(k.PublicKey))
		if len(existingParts) >= 2 {
			existingContent := existingParts[0] + " " + existingParts[1]
			if existingContent == keyContent {
				return k.Fingerprint, nil
			}
		}
	}

	// Create new key
	key, _, err := b.client.Keys.Create(b.ctx, &godo.KeyCreateRequest{
		Name:      fmt.Sprintf("congo-%d", time.Now().Unix()),
		PublicKey: publicKey,
	})
	if err != nil {
		// If key already in use, it means the content matched but we didn't find it
		// This can happen if DO returned paginated results - list all pages
		if strings.Contains(err.Error(), "already in use") {
			keys, _, _ = b.client.Keys.List(b.ctx, &godo.ListOptions{PerPage: 200})
			for _, k := range keys {
				existingParts := strings.Fields(strings.TrimSpace(k.PublicKey))
				if len(existingParts) >= 2 {
					existingContent := existingParts[0] + " " + existingParts[1]
					if existingContent == keyContent {
						return k.Fingerprint, nil
					}
				}
			}
		}
		return "", fmt.Errorf("create SSH key: %w", err)
	}

	return key.Fingerprint, nil
}