softplayer-backend/internal/controllers/environments.go

398 lines
10 KiB
Go
Raw Normal View History

2024-03-19 15:49:29 +00:00
package controllers
import (
"context"
2024-04-03 18:05:23 +00:00
"errors"
"fmt"
2024-05-05 19:07:12 +00:00
"strings"
2024-03-19 15:49:29 +00:00
2024-05-06 09:39:28 +00:00
"github.com/go-logr/logr"
2024-05-06 16:00:31 +00:00
"github.com/go-logr/zapr"
2024-05-02 10:47:52 +00:00
"github.com/google/uuid"
2024-04-19 14:23:53 +00:00
"github.com/joho/godotenv"
2024-05-06 16:00:31 +00:00
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
2024-04-19 14:23:53 +00:00
2024-05-06 16:00:31 +00:00
"git.badhouseplants.net/softplayer/softplayer-backend/internal/consts"
2024-04-03 18:05:23 +00:00
"git.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/kube"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2024-04-15 14:30:47 +00:00
"k8s.io/client-go/kubernetes"
2024-04-03 18:05:23 +00:00
"k8s.io/client-go/rest"
2024-03-19 15:49:29 +00:00
ctrl "sigs.k8s.io/controller-runtime"
)
type Environemnt struct {
Controller ctrl.Manager
2024-05-06 08:48:59 +00:00
Config *rest.Config
2024-04-03 18:05:23 +00:00
UserID string
2024-03-19 15:49:29 +00:00
Data *EnvironemntData
2024-04-03 18:05:23 +00:00
Token string
2024-03-19 15:49:29 +00:00
}
type EnvironemntData struct {
2024-05-02 10:47:52 +00:00
UUID string
2024-04-03 18:05:23 +00:00
Name string
2024-04-29 12:07:02 +00:00
Description string
2024-04-29 18:03:37 +00:00
Provider string
2024-04-03 18:05:23 +00:00
Kubernetes string
2024-04-29 17:34:55 +00:00
Location string
ServerType string
2024-05-06 08:44:08 +00:00
DiskSize int
2024-03-19 15:49:29 +00:00
}
2024-04-29 16:28:13 +00:00
func (e *EnvironemntData) buildVars() (string, error) {
2024-05-06 19:11:44 +00:00
// Please make sure that the same variables are used by ansible
2024-04-29 16:28:13 +00:00
vars := fmt.Sprintf(`# -- Generated by the softplayer controller
SP_PROVIDER=%s
SP_KUBERNETES=%s
SP_SERVER_TYPE=%s
2024-05-06 08:44:08 +00:00
SP_SERVER_LOCATION=%s
SP_DISK_SIZE=%d`,
2024-04-29 16:28:13 +00:00
e.Provider,
e.Kubernetes,
2024-04-29 17:34:55 +00:00
e.ServerType,
e.Location,
2024-05-06 08:44:08 +00:00
e.DiskSize,
2024-04-29 16:28:13 +00:00
)
return vars, nil
2024-04-03 18:05:23 +00:00
}
2024-05-06 08:44:08 +00:00
// Check whether used has passed the email verification
2024-04-03 18:05:23 +00:00
func (env *Environemnt) isNsVerified(ctx context.Context) error {
2024-05-06 16:00:31 +00:00
log, err := logr.FromContext(ctx)
if err != nil {
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
}
log = zapr.NewLogger(zapLog)
}
2024-05-06 08:48:59 +00:00
clientset, err := kubernetes.NewForConfig(env.Config)
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't create a new clientset")
return consts.ErrSystemError
2024-05-06 08:48:59 +00:00
}
ns, err := clientset.CoreV1().Namespaces().Get(ctx, env.UserID, metav1.GetOptions{})
if err != nil {
2024-05-06 16:01:11 +00:00
log.Error(err, "Couldn't get a user's namespace")
2024-05-06 16:00:31 +00:00
return consts.ErrSystemError
2024-04-03 18:05:23 +00:00
}
val, ok := ns.GetLabels()["email-verified"]
if !ok || val == "false" {
2024-04-29 18:03:37 +00:00
return errors.New("user email is not verified, can't create an new env")
2024-04-03 18:05:23 +00:00
}
2024-05-06 08:48:59 +00:00
2024-04-03 18:05:23 +00:00
return nil
}
// Create environment should create a new configmap in the user's namespace
// using a token that belongs to the user.
2024-03-19 15:49:29 +00:00
func (env *Environemnt) Create(ctx context.Context) error {
2024-05-06 16:00:31 +00:00
log, err := logr.FromContext(ctx)
if err != nil {
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
}
log = zapr.NewLogger(zapLog)
}
2024-04-03 18:05:23 +00:00
if err := env.isNsVerified(ctx); err != nil {
2024-05-06 16:00:31 +00:00
return status.Error(codes.Unauthenticated, err.Error())
2024-04-03 18:05:23 +00:00
}
2024-04-29 16:28:13 +00:00
2024-05-06 08:48:59 +00:00
// Prepare a new ID for a enironment
env.Data.UUID = uuid.New().String()
2024-04-03 18:05:23 +00:00
env.Controller.GetClient()
conf := &rest.Config{
Host: "https://kubernetes.default.svc.cluster.local:443",
BearerToken: env.Token,
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
controller, err := ctrl.NewManager(conf, ctrl.Options{})
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't init a controller")
return consts.ErrSystemError
2024-04-03 18:05:23 +00:00
}
2024-04-29 16:28:13 +00:00
vars, err := env.Data.buildVars()
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't build the environment's dotenv file", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-29 16:28:13 +00:00
}
2024-04-03 18:05:23 +00:00
obj := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
2024-05-02 10:47:52 +00:00
Name: env.Data.UUID,
2024-04-03 18:05:23 +00:00
Namespace: env.UserID,
Labels: map[string]string{
"component": "bootstrap",
2024-04-15 13:45:05 +00:00
"kind": "environment",
2024-04-03 18:05:23 +00:00
},
},
Data: map[string]string{
2024-05-02 10:47:52 +00:00
"name": env.Data.Name,
2024-04-29 12:07:02 +00:00
"description": env.Data.Description,
2024-04-29 16:28:13 +00:00
"vars": vars,
2024-04-03 18:05:23 +00:00
},
}
if err := kube.Create(ctx, controller.GetClient(), &obj, false); err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couln't create the environment's configmap", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-03 18:05:23 +00:00
}
2024-03-19 15:49:29 +00:00
return nil
}
2024-04-05 15:40:20 +00:00
2024-04-30 09:19:56 +00:00
func (env *Environemnt) Update(ctx context.Context) error {
2024-05-06 16:00:31 +00:00
log, err := logr.FromContext(ctx)
if err != nil {
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
}
log = zapr.NewLogger(zapLog)
2024-04-30 09:19:56 +00:00
}
env.Controller.GetClient()
conf := &rest.Config{
Host: "https://kubernetes.default.svc.cluster.local:443",
BearerToken: env.Token,
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
controller, err := ctrl.NewManager(conf, ctrl.Options{})
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't init a controller")
return consts.ErrSystemError
2024-04-30 09:19:56 +00:00
}
oldEnv := &Environemnt{
Controller: env.Controller,
UserID: env.UserID,
Token: env.Token,
2024-04-30 09:28:33 +00:00
Data: &EnvironemntData{
2024-05-02 10:47:52 +00:00
UUID: env.Data.UUID,
2024-04-30 09:28:33 +00:00
},
2024-04-30 09:19:56 +00:00
}
if err := oldEnv.Get(ctx); err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't get environment's configmap", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-30 09:19:56 +00:00
}
// Check whter immutable fields are changed
if oldEnv.Data.Provider != env.Data.Provider {
return errors.New("provider can't be changed")
}
if oldEnv.Data.Location != env.Data.Location {
return errors.New("location can't be changed")
}
vars, err := env.Data.buildVars()
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't build the environment's dotenv file", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-30 09:19:56 +00:00
}
obj := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
2024-05-02 10:47:52 +00:00
Name: env.Data.UUID,
2024-04-30 09:19:56 +00:00
Namespace: env.UserID,
Labels: map[string]string{
"component": "bootstrap",
"kind": "environment",
},
},
Data: map[string]string{
2024-05-02 10:47:52 +00:00
"name": env.Data.Name,
2024-04-30 09:19:56 +00:00
"description": env.Data.Description,
"vars": vars,
},
}
if err := kube.Update(ctx, controller.GetClient(), &obj); err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couln't update the environment's configmap", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-30 09:19:56 +00:00
}
return nil
}
2024-04-05 15:40:20 +00:00
func (env *Environemnt) Delete(ctx context.Context) error {
2024-05-06 16:00:31 +00:00
log, err := logr.FromContext(ctx)
if err != nil {
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
}
log = zapr.NewLogger(zapLog)
}
2024-04-05 15:40:20 +00:00
env.Controller.GetClient()
conf := &rest.Config{
Host: "https://kubernetes.default.svc.cluster.local:443",
BearerToken: env.Token,
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
controller, err := ctrl.NewManager(conf, ctrl.Options{})
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "couldn't init a controller")
return consts.ErrSystemError
2024-04-05 15:40:20 +00:00
}
obj := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
2024-05-02 10:47:52 +00:00
Name: env.Data.UUID,
2024-04-05 15:40:20 +00:00
Namespace: env.UserID,
Labels: map[string]string{
"component": "bootstrap",
},
},
}
if err := kube.Delete(ctx, controller.GetClient(), &obj, false); err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couln't remove environment's configmap", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-05 15:40:20 +00:00
}
return nil
}
2024-04-15 13:45:05 +00:00
2024-05-06 16:00:31 +00:00
func (env *Environemnt) List(ctx context.Context, searchString string) ([]*Environemnt, error) {
2024-05-06 09:39:28 +00:00
log, err := logr.FromContext(ctx)
if err != nil {
2024-05-06 16:00:31 +00:00
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
}
log = zapr.NewLogger(zapLog)
2024-05-06 09:39:28 +00:00
}
2024-05-06 16:00:31 +00:00
2024-04-15 14:16:25 +00:00
env.Controller.GetClient()
2024-04-15 13:45:05 +00:00
conf := &rest.Config{
Host: "https://kubernetes.default.svc.cluster.local:443",
BearerToken: env.Token,
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
2024-04-15 14:30:47 +00:00
clientset, err := kubernetes.NewForConfig(conf)
2024-04-15 13:45:05 +00:00
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't create a new clientset")
return nil, consts.ErrSystemError
2024-04-19 14:23:53 +00:00
}
2024-04-30 08:00:06 +00:00
configmaps, err := clientset.CoreV1().ConfigMaps(env.UserID).List(ctx, metav1.ListOptions{LabelSelector: "kind=environment"})
2024-04-15 14:44:34 +00:00
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't list configmaps")
return nil, consts.ErrSystemError
2024-04-30 08:00:06 +00:00
}
result := []*Environemnt{}
for _, cm := range configmaps.Items {
i := &Environemnt{}
data := &EnvironemntData{
2024-05-02 11:33:30 +00:00
UUID: cm.GetName(),
2024-04-30 08:00:06 +00:00
}
i.Token = env.Token
i.UserID = env.UserID
i.Data = data
2024-04-30 08:20:46 +00:00
i.Controller = env.Controller
2024-04-30 08:00:06 +00:00
if err := i.Get(ctx); err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't get an environment", "environment_id", i.Data.UUID)
return nil, consts.ErrSystemError
2024-04-30 08:00:06 +00:00
}
2024-05-05 19:07:12 +00:00
if len(searchString) > 0 {
if strings.Contains(i.Data.Name, searchString) {
result = append(result, i)
}
if strings.Contains(i.Data.Description, searchString) {
result = append(result, i)
}
} else {
result = append(result, i)
}
2024-04-15 13:45:05 +00:00
}
return result, nil
}
2024-04-19 14:23:53 +00:00
func (env *Environemnt) Get(ctx context.Context) error {
2024-05-06 16:00:31 +00:00
log, err := logr.FromContext(ctx)
if err != nil {
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
}
log = zapr.NewLogger(zapLog)
}
2024-04-19 14:23:53 +00:00
env.Controller.GetClient()
conf := &rest.Config{
Host: "https://kubernetes.default.svc.cluster.local:443",
BearerToken: env.Token,
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
clientset, err := kubernetes.NewForConfig(conf)
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't create a new clientset")
return consts.ErrSystemError
2024-04-19 14:23:53 +00:00
}
2024-05-02 11:15:55 +00:00
envData, err := clientset.CoreV1().ConfigMaps(env.UserID).Get(ctx, env.Data.UUID, metav1.GetOptions{})
2024-04-19 14:23:53 +00:00
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't get an environment's configmap", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-19 14:23:53 +00:00
}
res, err := godotenv.Unmarshal(envData.Data["vars"])
if err != nil {
2024-05-06 16:00:31 +00:00
log.Error(err, "Couldn't parse environment's dotenv file from a configmap", "environment_id", env.Data.UUID)
return consts.ErrSystemError
2024-04-19 14:23:53 +00:00
}
2024-05-02 10:47:52 +00:00
if val, ok := envData.Data["name"]; ok {
env.Data.Name = val
} else {
env.Data.Name = ""
}
2024-05-02 11:02:38 +00:00
if val, ok := envData.Data["description"]; ok {
2024-04-30 08:12:41 +00:00
env.Data.Description = val
2024-04-30 08:30:21 +00:00
} else {
env.Data.Description = ""
2024-04-30 08:12:41 +00:00
}
2024-04-19 14:23:53 +00:00
2024-04-30 08:12:41 +00:00
if val, ok := res["SP_PROVIDER"]; ok {
env.Data.Provider = val
2024-04-30 08:30:21 +00:00
} else {
env.Data.Provider = ""
2024-04-30 08:12:41 +00:00
}
if val, ok := res["SP_KUBERNETES"]; ok {
env.Data.Kubernetes = val
2024-04-30 08:30:21 +00:00
} else {
env.Data.Kubernetes = ""
2024-04-30 08:12:41 +00:00
}
if val, ok := res["SP_SERVER_TYPE"]; ok {
env.Data.ServerType = val
2024-04-30 08:30:21 +00:00
} else {
env.Data.ServerType = ""
2024-04-30 08:12:41 +00:00
}
if val, ok := res["SP_SERVER_LOCATION"]; ok {
env.Data.Location = val
2024-04-30 08:30:21 +00:00
} else {
env.Data.Location = ""
2024-04-30 08:12:41 +00:00
}
2024-04-30 07:47:00 +00:00
2024-04-19 14:23:53 +00:00
return nil
}