This repository has been archived on 2023-03-15. You can view files and clone it, but cannot push or open issues or pull requests.
infrastructure/docker/bckp/kv_to_s3.go

83 lines
2.1 KiB
Go
Raw Normal View History

2020-05-30 12:10:32 +00:00
package main
import (
"github.com/hashicorp/consul/api"
2020-05-30 15:57:59 +00:00
"errors"
2020-05-30 12:10:32 +00:00
"log"
2020-05-30 15:57:59 +00:00
"fmt"
"os"
"encoding/base64"
2020-05-30 12:10:32 +00:00
/*"github.com/aws/aws-sdk-go/service/s3"*/
)
2020-05-30 15:57:59 +00:00
const consul_addr string = "KV2S3_CONSUL_ADDR"
const enc_key string = "KV2S3_ENC_KEY"
const key_exp_bits int = 256
const key_exp_bytes int = key_exp_bits / 8
2020-05-30 12:10:32 +00:00
func errIsPanic(err error, format string, a ...interface{}) {
if err != nil {
log.Panicf(format, a...)
}
}
2020-05-30 15:57:59 +00:00
func absentIsErr(present bool) error {
if !present {
return errors.New("Environement variable is not set.")
}
return nil
}
2020-05-30 12:10:32 +00:00
func main() {
log.Println("starting consul kv backup...")
2020-05-30 15:57:59 +00:00
//--- Ask Consul to Snapshot our KV
var present bool
2020-05-30 12:10:32 +00:00
conf := api.DefaultConfig()
2020-05-30 15:57:59 +00:00
conf.Address, present = os.LookupEnv(consul_addr)
err := absentIsErr(present)
errIsPanic(err, "%v env required. %v", consul_addr, err)
2020-05-30 12:10:32 +00:00
//@FIXME add later support for HTTPS
options := api.QueryOptions {
// Prevent from backuping forever silently a desynchronized node
AllowStale: false,
}
consul, err := api.NewClient(conf)
errIsPanic(err, "Unable to build a new client. %v", err)
2020-05-30 15:57:59 +00:00
reader, _, err := consul.Snapshot().Save(&options)
2020-05-30 12:10:32 +00:00
errIsPanic(err, "Snapshot failed. %v", err)
2020-05-30 15:57:59 +00:00
//--- Get encryption key and check it
b64_key, present := os.LookupEnv(enc_key)
err = absentIsErr(present)
errIsPanic(err, "%v env required. %v", enc_key, err)
raw_key, err := base64.StdEncoding.DecodeString(b64_key)
errIsPanic(err, "Unable to decode base64 key. %v", err)
err = nil
key_size_bytes := len(raw_key)
key_size_bits := key_size_bytes
if key_size_bytes != key_exp_bytes {
msg := fmt.Sprintf(
"Key size is %d bits (%d bytes) instead of %d bits (%d bytes).",
key_size_bits,
key_size_bytes,
key_exp_bits,
key_exp_bytes)
err = errors.New(msg)
}
errIsPanic(err, "We deliberately support only 256 bits (32 bytes) keys. %v", err)
//--- Encryption
// Not a simple thing to do it in a streaming manner
// To understand why age by Filippo Valsorda seems to be a good fit:
// https://neilmadden.blog/2019/12/30/a-few-comments-on-age/
2020-05-30 12:10:32 +00:00
}