woj-server/internal/service/runner/deps.go

85 lines
1.9 KiB
Go

package runner
import (
"errors"
"fmt"
"git.0x7f.app/WOJ/woj-server/internal/e"
"git.0x7f.app/WOJ/woj-server/pkg/file"
"git.0x7f.app/WOJ/woj-server/pkg/utils"
"go.uber.org/zap"
"os"
"path/filepath"
)
type depConfig struct {
tarball string
image string
dockerfile string
}
func (s *service) loadImage(cfg *depConfig) e.Status {
err := utils.NewTryErr().
Try(func() error {
// import from tarball
if !file.Exist(cfg.tarball) {
return errors.New("tarball not exists")
}
return s.execute("bash", "-c", fmt.Sprintf("gzip -d -c %s | podman load", cfg.tarball))
}).
Or(func() error {
// pull from docker hub
return s.execute("podman", "pull", cfg.image)
}).
Or(func() error {
// build from dockerfile
if !file.Exist(cfg.dockerfile) {
return errors.New("dockerfile not exists")
}
return s.execute("podman", "build", "-f", cfg.dockerfile, "-t", cfg.image, ".")
}).
Done()
if err != nil {
s.log.Warn("load image failed", zap.Error(err))
return e.RunnerDepsBuildFailed
}
return e.Success
}
func (s *service) EnsureDeps(force bool) e.Status {
mark := filepath.Join(Prefix, ".mark.image")
// check mark
if force {
_ = os.Remove(mark)
} else if file.Exist(mark) {
return e.Success
}
// full
fullImage := &depConfig{
tarball: filepath.Join(TmpDir, "ubuntu-full.tar.gz"),
image: "git.0x7f.app/woj/ubuntu-full:latest",
dockerfile: filepath.Join(ScriptsDir, "ubuntu-full.Dockerfile"),
}
if s.loadImage(fullImage) != e.Success {
return e.RunnerDepsBuildFailed
}
// tiny
tinyImage := &depConfig{
tarball: filepath.Join(TmpDir, "ubuntu-tiny.tar.gz"),
image: "git.0x7f.app/woj/ubuntu-run:latest",
dockerfile: filepath.Join(ScriptsDir, "ubuntu-run.Dockerfile"),
}
if s.loadImage(tinyImage) != e.Success {
return e.RunnerDepsBuildFailed
}
// mark
_, _ = os.Create(mark)
return e.Success
}