feat: initial library code

This commit is contained in:
Julian Tölle 2024-04-29 21:00:04 +02:00
parent b331ddba81
commit 4f57df5b66
10 changed files with 575 additions and 0 deletions

85
util/control/retry.go Normal file
View file

@ -0,0 +1,85 @@
package control
import (
"context"
"errors"
"math"
"time"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)
// From https://github.com/hetznercloud/terraform-provider-hcloud/blob/v1.46.1/internal/control/retry.go
// ExponentialBackoffWithLimit returns a [hcloud.BackoffFunc] which implements an exponential
// backoff.
// It uses the formula:
//
// min(b^retries * d, limit)
func ExponentialBackoffWithLimit(b float64, d time.Duration, limit time.Duration) hcloud.BackoffFunc {
return func(retries int) time.Duration {
current := time.Duration(math.Pow(b, float64(retries))) * d
if current > limit {
return limit
} else {
return current
}
}
}
// DefaultRetries is a constant for the maximum number of retries we usually do.
// However, callers of Retry are free to choose a different number.
const DefaultRetries = 5
type abortErr struct {
Err error
}
func (e abortErr) Error() string {
return e.Err.Error()
}
func (e abortErr) Unwrap() error {
return e.Err
}
// AbortRetry aborts any further attempts of retrying an operation.
//
// If err is passed Retry returns the passed error. If nil is passed, Retry
// returns nil.
func AbortRetry(err error) error {
if err == nil {
return nil
}
return abortErr{Err: err}
}
// Retry executes f at most maxTries times.
func Retry(ctx context.Context, maxTries int, f func() error) error {
var err error
backoff := ExponentialBackoffWithLimit(2, 1*time.Second, 30*time.Second)
for try := 0; try < maxTries; try++ {
if ctx.Err() != nil {
return ctx.Err()
}
var aerr abortErr
err = f()
if errors.As(err, &aerr) {
return aerr.Err
}
if err != nil {
sleep := backoff(try)
time.Sleep(sleep)
continue
}
return nil
}
return err
}

16
util/randomid/randomid.go Normal file
View file

@ -0,0 +1,16 @@
package randomid
import (
"crypto/rand"
"encoding/hex"
"fmt"
)
func Generate() (string, error) {
b := make([]byte, 4)
_, err := rand.Read(b)
if err != nil {
return "", fmt.Errorf("failed to generate random string: %w", err)
}
return hex.EncodeToString(b), nil
}

View file

@ -0,0 +1,18 @@
package randomid
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGenerateRandomID(t *testing.T) {
found1, err := Generate()
assert.NoError(t, err)
found2, err := Generate()
assert.NoError(t, err)
assert.Len(t, found1, 8)
assert.Len(t, found2, 8)
assert.NotEqual(t, found1, found2)
}

45
util/sshkey/ssh_key.go Normal file
View file

@ -0,0 +1,45 @@
package sshkey
import (
"crypto/ed25519"
"encoding/pem"
"golang.org/x/crypto/ssh"
)
func GenerateKeyPair() ([]byte, []byte, error) {
pub, priv, err := ed25519.GenerateKey(nil)
if err != nil {
return nil, nil, err
}
pubBytes, err := encodePublicKey(pub)
if err != nil {
return nil, nil, err
}
privBytes, err := encodePrivateKey(priv)
if err != nil {
return nil, nil, err
}
return pubBytes, privBytes, nil
}
func encodePublicKey(pub ed25519.PublicKey) ([]byte, error) {
sshPub, err := ssh.NewPublicKey(pub)
if err != nil {
return nil, err
}
return ssh.MarshalAuthorizedKey(sshPub), nil
}
func encodePrivateKey(priv ed25519.PrivateKey) ([]byte, error) {
privPem, err := ssh.MarshalPrivateKey(priv, "")
if err != nil {
return nil, err
}
return pem.EncodeToMemory(privPem), nil
}

View file

@ -0,0 +1,25 @@
package sshkey
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGenerateSSHKeyPair(t *testing.T) {
pubBytes, privBytes, err := GenerateKeyPair()
assert.Nil(t, err)
pub := string(pubBytes)
priv := string(privBytes)
if !(strings.HasPrefix(priv, "-----BEGIN OPENSSH PRIVATE KEY-----\n") &&
strings.HasSuffix(priv, "-----END OPENSSH PRIVATE KEY-----\n")) {
assert.Fail(t, "private key is invalid", priv)
}
if !strings.HasPrefix(pub, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA") {
assert.Fail(t, "public key is invalid", pub)
}
}

View file

@ -0,0 +1,12 @@
package sshsession
import "golang.org/x/crypto/ssh"
func Run(client *ssh.Client, cmd string) ([]byte, error) {
sess, err := client.NewSession()
if err != nil {
return nil, err
}
defer sess.Close()
return sess.CombinedOutput(cmd)
}