2022-09-11 14:52:21 +02:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
2022-09-11 22:56:54 +02:00
|
|
|
"errors"
|
2022-09-11 14:52:21 +02:00
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
|
2022-09-11 22:56:54 +02:00
|
|
|
"go.uber.org/zap"
|
2022-09-11 14:52:21 +02:00
|
|
|
"golang.org/x/net/context"
|
|
|
|
)
|
|
|
|
|
|
|
|
// The idea behind storage is that we have file dir, with a git repo.
|
|
|
|
// This file repo can now take certain actions
|
|
|
|
|
|
|
|
type StorageConfig struct {
|
|
|
|
Path string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDefaultStorageConfig() (*StorageConfig, error) {
|
|
|
|
tempDir, err := os.MkdirTemp(os.TempDir(), "")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &StorageConfig{
|
|
|
|
Path: path.Join(tempDir, "kraken"),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type Service struct {
|
2022-09-11 22:56:54 +02:00
|
|
|
logger *zap.Logger
|
|
|
|
cfg *StorageConfig
|
2022-09-11 14:52:21 +02:00
|
|
|
}
|
|
|
|
|
2022-09-11 22:56:54 +02:00
|
|
|
func NewService(logger *zap.Logger, cfg *StorageConfig) *Service {
|
|
|
|
return &Service{logger: logger, cfg: cfg}
|
2022-09-11 14:52:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Service) getStoragePath(ctx context.Context) string {
|
|
|
|
return path.Join(s.cfg.Path, "storage")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Service) InitializeStorage(ctx context.Context) error {
|
|
|
|
return os.MkdirAll(s.getStoragePath(ctx), 0755)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Service) CleanupStorage(ctx context.Context) error {
|
2022-09-11 22:56:54 +02:00
|
|
|
doneRemovingChan := make(chan struct{}, 1)
|
|
|
|
go func(ctx context.Context) {
|
|
|
|
s.logger.Debug("Removing all temp storage")
|
|
|
|
os.RemoveAll(s.getStoragePath(ctx))
|
|
|
|
doneRemovingChan <- struct{}{}
|
|
|
|
}(ctx)
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return errors.New("could not cleanup storage aborting")
|
|
|
|
case <-doneRemovingChan:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2022-09-11 14:52:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Service) CreateArea(ctx context.Context) (*Area, error) {
|
|
|
|
dir, err := os.MkdirTemp(s.getStoragePath(ctx), "*")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Area{
|
|
|
|
Path: dir,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Service) RemoveArea(ctx context.Context, area *Area) error {
|
|
|
|
return os.RemoveAll(area.Path)
|
|
|
|
}
|