feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,347 @@
|
||||
package isolation
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (a Agent) backupDirectory(tenantID uint64) (string, error) {
|
||||
root := strings.TrimSpace(a.BackupRoot)
|
||||
if root == "" {
|
||||
root = "/www/backup/sea-vhost"
|
||||
}
|
||||
if !filepath.IsAbs(root) || tenantID == 0 {
|
||||
return "", errors.New("invalid backup root")
|
||||
}
|
||||
return filepath.Join(filepath.Clean(root), strconv.FormatUint(tenantID, 10)), nil
|
||||
}
|
||||
|
||||
func (a Agent) createProjectBackup(w http.ResponseWriter, r *http.Request) {
|
||||
spec, ok := a.decode(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
projectRoot, err := a.projectPath(spec)
|
||||
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
|
||||
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
if len(spec.Databases) > 1 || (len(spec.Databases) == 1 && (spec.Databases[0] != spec.HostName || !managedWebHostPattern.MatchString(spec.HostName))) {
|
||||
http.Error(w, "invalid backup database ownership", 400)
|
||||
return
|
||||
}
|
||||
backupDir, err := a.backupDirectory(spec.TenantID)
|
||||
if err != nil || os.MkdirAll(backupDir, 0700) != nil || os.Chmod(backupDir, 0700) != nil {
|
||||
http.Error(w, "cannot prepare backup directory", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
stamp := time.Now().UTC().Format("20060102T150405.000000000Z")
|
||||
finalPath := filepath.Join(backupDir, spec.HostName+"-"+stamp+".tar.gz")
|
||||
temporary, err := os.CreateTemp(backupDir, "."+spec.HostName+"-*.tmp")
|
||||
if err != nil {
|
||||
http.Error(w, "cannot create backup", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
_ = temporary.Chmod(0600)
|
||||
var dumps []backupDatabaseFile
|
||||
for _, name := range spec.Databases {
|
||||
dump, dumpErr := a.dumpDatabase(r.Context(), backupDir, name)
|
||||
if dumpErr != nil {
|
||||
temporary.Close()
|
||||
http.Error(w, "cannot archive customer database", 500)
|
||||
return
|
||||
}
|
||||
defer os.Remove(dump.path)
|
||||
dumps = append(dumps, dump)
|
||||
}
|
||||
err = writeTarGzipDatabase(r.Context(), temporary, projectRoot, spec.HostName, dumps)
|
||||
if err == nil {
|
||||
err = temporary.Sync()
|
||||
}
|
||||
closeErr := temporary.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(temporaryPath, finalPath)
|
||||
}
|
||||
if err == nil && runtime.GOOS != "windows" {
|
||||
directory, openErr := os.Open(backupDir)
|
||||
if openErr != nil {
|
||||
err = openErr
|
||||
} else {
|
||||
err = directory.Sync()
|
||||
directory.Close()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "cannot archive project", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
info, err := os.Stat(finalPath)
|
||||
if err != nil {
|
||||
http.Error(w, "cannot inspect backup", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(w).Encode(ProjectBackup{TenantID: spec.TenantID, HostName: spec.HostName, ArchivePath: finalPath, SizeBytes: uint64(info.Size()), DatabaseCount: len(dumps)})
|
||||
}
|
||||
|
||||
func writeTarGzip(ctx context.Context, output io.Writer, root, hostName string) error {
|
||||
return writeTarGzipDatabase(ctx, output, root, hostName, nil)
|
||||
}
|
||||
|
||||
type backupDatabaseFile struct {
|
||||
name, path string
|
||||
size int64
|
||||
digest string
|
||||
}
|
||||
|
||||
func (a Agent) dumpDatabase(ctx context.Context, directory, name string) (backupDatabaseFile, error) {
|
||||
if !managedWebHostPattern.MatchString(name) {
|
||||
return backupDatabaseFile{}, errors.New("invalid managed database name")
|
||||
}
|
||||
cfg, err := a.mysqlConfig(ctx)
|
||||
if err != nil {
|
||||
return backupDatabaseFile{}, err
|
||||
}
|
||||
options, err := os.CreateTemp(directory, ".mysql-options-*")
|
||||
if err != nil {
|
||||
return backupDatabaseFile{}, err
|
||||
}
|
||||
defer os.Remove(options.Name())
|
||||
_ = options.Chmod(0600)
|
||||
if cfg.Net == "unix" {
|
||||
_, err = fmt.Fprintf(options, "[client]\nuser=%s\npassword=%s\nsocket=%s\nprotocol=SOCKET\n", mysqlOptionValue(cfg.User), mysqlOptionValue(cfg.Passwd), mysqlOptionValue(cfg.Addr))
|
||||
} else {
|
||||
_, err = fmt.Fprintf(options, "[client]\nuser=%s\npassword=%s\nhost=127.0.0.1\nport=%s\nprotocol=TCP\n", mysqlOptionValue(cfg.User), mysqlOptionValue(cfg.Passwd), strings.TrimPrefix(cfg.Addr, "127.0.0.1:"))
|
||||
}
|
||||
closeErr := options.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return backupDatabaseFile{}, err
|
||||
}
|
||||
file, err := os.CreateTemp(directory, ".database-*.sql")
|
||||
if err != nil {
|
||||
return backupDatabaseFile{}, err
|
||||
}
|
||||
_ = file.Chmod(0600)
|
||||
cleanup := func() { file.Close(); os.Remove(file.Name()) }
|
||||
command := exec.CommandContext(ctx, "/www/server/mysql/bin/mysqldump", "--defaults-extra-file="+options.Name(), "--single-transaction", "--quick", "--routines", "--events", "--triggers", "--hex-blob", "--no-tablespaces", "--set-gtid-purged=OFF", "--databases", name)
|
||||
hash := sha256.New()
|
||||
command.Stdout = io.MultiWriter(file, hash)
|
||||
if command.Run() != nil {
|
||||
cleanup()
|
||||
return backupDatabaseFile{}, errors.New("customer database dump failed")
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil || info.Size() == 0 {
|
||||
cleanup()
|
||||
return backupDatabaseFile{}, errors.New("empty customer database dump")
|
||||
}
|
||||
if err = file.Close(); err != nil {
|
||||
os.Remove(file.Name())
|
||||
return backupDatabaseFile{}, err
|
||||
}
|
||||
return backupDatabaseFile{name: name, path: file.Name(), size: info.Size(), digest: fmt.Sprintf("%x", hash.Sum(nil))}, nil
|
||||
}
|
||||
|
||||
func writeTarGzipDatabase(ctx context.Context, output io.Writer, root, hostName string, dumps []backupDatabaseFile) error {
|
||||
archiveRoot, openErr := os.OpenRoot(root)
|
||||
if openErr != nil {
|
||||
return openErr
|
||||
}
|
||||
defer archiveRoot.Close()
|
||||
gzipWriter := gzip.NewWriter(output)
|
||||
tarWriter := tar.NewWriter(gzipWriter)
|
||||
err := filepath.WalkDir(root, func(current string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !(info.Mode().IsRegular() || info.IsDir() || info.Mode()&os.ModeSymlink != 0) {
|
||||
return nil
|
||||
}
|
||||
relative, err := filepath.Rel(root, current)
|
||||
if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
|
||||
return errors.New("backup path escaped project root")
|
||||
}
|
||||
link := ""
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
link, err = os.Readlink(current)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
header, err := tar.FileInfoHeader(info, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
header.Name = filepath.ToSlash(filepath.Join(hostName, relative))
|
||||
if err = tarWriter.WriteHeader(header); err != nil || !info.Mode().IsRegular() {
|
||||
return err
|
||||
}
|
||||
file, err := archiveRoot.Open(relative)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(tarWriter, file)
|
||||
closeErr := file.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
return closeErr
|
||||
})
|
||||
manifest := map[string]any{"format": 2, "hostName": hostName, "createdAt": time.Now().UTC(), "databases": []map[string]any{}}
|
||||
entries := []map[string]any{}
|
||||
for _, dump := range dumps {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
break
|
||||
}
|
||||
name := ".sea-vhost-backup/databases/" + dump.name + ".sql"
|
||||
if err = tarWriter.WriteHeader(&tar.Header{Name: name, Mode: 0600, Size: dump.size, ModTime: time.Now().UTC()}); err != nil {
|
||||
break
|
||||
}
|
||||
file, openErr := os.Open(dump.path)
|
||||
if openErr != nil {
|
||||
err = openErr
|
||||
break
|
||||
}
|
||||
_, err = io.Copy(tarWriter, file)
|
||||
closeErr := file.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
entries = append(entries, map[string]any{"name": dump.name, "path": name, "bytes": dump.size, "sha256": dump.digest})
|
||||
}
|
||||
manifest["databases"] = entries
|
||||
if err == nil {
|
||||
data, marshalErr := json.Marshal(manifest)
|
||||
if marshalErr != nil {
|
||||
err = marshalErr
|
||||
} else {
|
||||
err = tarWriter.WriteHeader(&tar.Header{Name: ".sea-vhost-backup/manifest.json", Mode: 0600, Size: int64(len(data)), ModTime: time.Now().UTC()})
|
||||
if err == nil {
|
||||
_, err = tarWriter.Write(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
if closeErr := tarWriter.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if closeErr := gzipWriter.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a Agent) deleteProjectBackup(w http.ResponseWriter, r *http.Request) {
|
||||
var backup ProjectBackup
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&backup) != nil || !safeName.MatchString(backup.HostName) || backup.TenantID == 0 {
|
||||
http.Error(w, "invalid request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
directory, err := a.backupDirectory(backup.TenantID)
|
||||
cleaned := filepath.Clean(backup.ArchivePath)
|
||||
if err != nil || filepath.Dir(cleaned) != directory || !strings.HasPrefix(filepath.Base(cleaned), backup.HostName+"-") || !strings.HasSuffix(cleaned, ".tar.gz") {
|
||||
http.Error(w, "unsafe backup path", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
info, err := os.Lstat(cleaned)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
|
||||
http.Error(w, "unsafe backup file", http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
if err = os.Remove(cleaned); err != nil {
|
||||
http.Error(w, "cannot delete backup", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (a Agent) purgeProject(w http.ResponseWriter, r *http.Request) {
|
||||
spec, ok := a.decode(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
projectRoot, err := a.projectPath(spec)
|
||||
if err != nil {
|
||||
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
physicalErr := requirePhysicalDirectory(projectRoot)
|
||||
if physicalErr == nil {
|
||||
files, findErr := findProjectUserINIFiles(projectRoot, 512)
|
||||
if findErr != nil {
|
||||
http.Error(w, "unsafe PHP isolation file", http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
for _, file := range files {
|
||||
if err = a.removeUserINI(r.Context(), file); err != nil {
|
||||
http.Error(w, "cannot release PHP isolation file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err = os.RemoveAll(projectRoot); err != nil {
|
||||
http.Error(w, "cannot purge project", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(physicalErr, os.ErrNotExist) {
|
||||
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
// Probe identities first so retries are idempotent without depending on
|
||||
// distribution-specific userdel/groupdel error text.
|
||||
if a.command(ctx, "id", "-u", spec.HostName) == nil {
|
||||
if err = a.command(ctx, "userdel", spec.HostName); err != nil {
|
||||
http.Error(w, "cannot remove project identity", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
if a.command(ctx, "getent", "group", spec.HostName) == nil {
|
||||
if err = a.command(ctx, "groupdel", spec.HostName); err != nil {
|
||||
http.Error(w, "cannot remove project group", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
Reference in new issue
Block a user