2021-04-20 21:31:37 +00:00
|
|
|
package garage
|
|
|
|
|
|
|
|
import (
|
2022-10-16 20:17:26 +00:00
|
|
|
"crypto/rand"
|
|
|
|
"encoding/hex"
|
2021-04-20 21:31:37 +00:00
|
|
|
"errors"
|
2022-10-19 14:53:31 +00:00
|
|
|
"fmt"
|
2021-04-20 21:31:37 +00:00
|
|
|
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
|
|
)
|
|
|
|
|
2022-10-16 20:17:26 +00:00
|
|
|
func randStr(l int) string {
|
|
|
|
b := make([]byte, l)
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return hex.EncodeToString(b)
|
|
|
|
}
|
|
|
|
|
2021-04-20 21:31:37 +00:00
|
|
|
// IsKeyNotFound returns true if the given error is the result of a key not
|
|
|
|
// being found in a bucket.
|
|
|
|
func IsKeyNotFound(err error) bool {
|
|
|
|
var mErr minio.ErrorResponse
|
|
|
|
return errors.As(err, &mErr) && mErr.Code == "NoSuchKey"
|
|
|
|
}
|
|
|
|
|
2022-10-15 14:28:03 +00:00
|
|
|
// S3APIClient is a client used to interact with garage's S3 API.
|
|
|
|
type S3APIClient = *minio.Client
|
|
|
|
|
|
|
|
// S3APICredentials describe data fields necessary for authenticating with a
|
|
|
|
// garage S3 API endpoint.
|
|
|
|
type S3APICredentials struct {
|
2021-04-20 21:31:37 +00:00
|
|
|
ID string `yaml:"id"`
|
|
|
|
Secret string `yaml:"secret"`
|
|
|
|
}
|
|
|
|
|
2022-10-16 20:17:26 +00:00
|
|
|
// NewS3APICredentials returns a new usable instance of S3APICredentials.
|
|
|
|
func NewS3APICredentials() S3APICredentials {
|
|
|
|
return S3APICredentials{
|
|
|
|
ID: randStr(8),
|
|
|
|
Secret: randStr(32),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-15 14:28:03 +00:00
|
|
|
// NewS3APIClient returns a minio client configured to use the given garage S3 API
|
2021-04-20 21:31:37 +00:00
|
|
|
// endpoint.
|
2022-10-19 14:53:31 +00:00
|
|
|
func NewS3APIClient(addr string, creds S3APICredentials) S3APIClient {
|
|
|
|
|
|
|
|
client, err := minio.New(addr, &minio.Options{
|
2021-04-20 21:31:37 +00:00
|
|
|
Creds: credentials.NewStaticV4(creds.ID, creds.Secret, ""),
|
|
|
|
Region: Region,
|
|
|
|
})
|
2022-10-19 14:53:31 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
panic(fmt.Sprintf("initializing minio client at addr %q and with creds %+v", addr, creds))
|
|
|
|
}
|
|
|
|
|
|
|
|
return client
|
2021-04-20 21:31:37 +00:00
|
|
|
}
|