Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(resources): refactor pg and add mysql (#686)

qsliu62533384d68e
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..3c82527589
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+resources/mysql/mysql-8.0.28-linux-glibc2.17-x86_64-minimal.tar.xz filter=lfs diff=lfs merge=lfs -text
+resources/mysql/mysql-8.0.28-macos11-arm64.tar.gz filter=lfs diff=lfs merge=lfs -text
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 8c4bc48e6c..3f7dbe233f 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -33,6 +33,7 @@ jobs:
uses: actions/checkout@v2
with:
fetch-depth: 0
+ lfs: true
- uses: actions/setup-go@v2
with:
go-version: 1.17
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 029da757ca..4353715927 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -16,7 +16,7 @@ import (
"github.com/bytebase/bytebase/common"
enterprise "github.com/bytebase/bytebase/enterprise/service"
dbdriver "github.com/bytebase/bytebase/plugin/db"
- "github.com/bytebase/bytebase/resources"
+ "github.com/bytebase/bytebase/resources/postgres"
"github.com/bytebase/bytebase/server"
"github.com/bytebase/bytebase/store"
"github.com/spf13/cobra"
@@ -177,7 +177,7 @@ type Main struct {
// Otherwise, we will get database is closed error from runner when we shutdown the server.
serverCancel context.CancelFunc
- pgBinDir string
+ pg *postgres.Instance
pgStarted bool
// db is a connection to the database storing Bytebase data.
db *store.DB
@@ -291,15 +291,15 @@ func NewMain(activeProfile Profile, logger *zap.Logger) (*Main, error) {
fmt.Printf("debug=%t\n", debug)
fmt.Println("-----Config END-------")
- pgBinDir, err := resources.InstallPostgres(resourceDir, pgDataDir, activeProfile.pgUser)
+ pgInstance, err := postgres.Install(resourceDir, pgDataDir, activeProfile.pgUser)
if err != nil {
return nil, err
}
return &Main{
- profile: &activeProfile,
- l: logger,
- pgBinDir: pgBinDir,
+ profile: &activeProfile,
+ l: logger,
+ pg: pgInstance,
}, nil
}
@@ -327,8 +327,7 @@ func (m *Main) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
m.serverCancel = cancel
- pgDataDir := path.Join(m.profile.dataDir, "pgdata")
- if err := resources.StartPostgres(m.pgBinDir, pgDataDir, m.profile.datastorePort, os.Stderr, os.Stderr); err != nil {
+ if err := m.pg.Start(m.profile.datastorePort, os.Stderr, os.Stderr, 0 /* waitSec */); err != nil {
return err
}
m.pgStarted = true
@@ -428,8 +427,7 @@ func (m *Main) Close() error {
if m.pgStarted {
m.l.Info("Trying to shutdown postgresql server...")
- pgDataDir := path.Join(m.profile.dataDir, "pgdata")
- if err := resources.StopPostgres(m.pgBinDir, pgDataDir, os.Stdout, os.Stderr); err != nil {
+ if err := m.pg.Stop(os.Stdout, os.Stderr); err != nil {
return err
}
m.pgStarted = false
diff --git a/resources/mysql/mysql-8.0.28-linux-glibc2.17-x86_64-minimal.tar.xz b/resources/mysql/mysql-8.0.28-linux-glibc2.17-x86_64-minimal.tar.xz
new file mode 100644
index 0000000000..70aa85d87a
--- /dev/null
+++ b/resources/mysql/mysql-8.0.28-linux-glibc2.17-x86_64-minimal.tar.xz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:39d58319a2d34b27dc229eb32c07f3902863fb5dfe25d25b5d537cc7299b4fed
+size 54089904
diff --git a/resources/mysql/mysql.go b/resources/mysql/mysql.go
new file mode 100644
index 0000000000..ffa4fc4e26
--- /dev/null
+++ b/resources/mysql/mysql.go
@@ -0,0 +1,153 @@
+package mysql
+
+import (
+ "database/sql"
+ "embed"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "time"
+
+ "github.com/bytebase/bytebase/resources/utils"
+
+ // install mysql driver
+ _ "github.com/go-sql-driver/mysql"
+)
+
+//go:embed mysql-8.0.28-macos11-arm64.tar.gz mysql-8.0.28-linux-glibc2.17-x86_64-minimal.tar.xz
+var resources embed.FS
+
+// Instance is MySQL instance installed by bytebase for testing.
+type Instance struct {
+ // basedir is the directory where the mysql binary is installed.
+ basedir string
+ // datadir is the directory where the mysql data is stored.
+ datadir string
+ // port is the port of the mysql instance.
+ port int
+ // proc is the process of the mysql instance.
+ proc *os.Process
+}
+
+// Port returns the port of the mysql instance.
+func (i Instance) Port() int { return i.port }
+
+// Start starts the mysql instance on the given port, outputs to stdout and stderr.
+// Waits at most `waitSec` seconds for the mysql instance to ready for connection.
+// If `waitSec` is 0, it returns immediately.
+func (i *Instance) Start(port int, stdout, stderr io.Writer, waitSec int) (err error) {
+ i.port = port
+ cmd := exec.Command(filepath.Join(i.basedir, "bin", "mysqld"),
+ fmt.Sprintf("--defaults-file=%s", filepath.Join(i.basedir, "my.cnf")),
+ fmt.Sprintf("--port=%d", i.port),
+ )
+ cmd.Stdout = stdout
+ cmd.Stderr = stderr
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ i.proc = cmd.Process
+
+ // wait for mysql to start
+ db, err := sql.Open("mysql", fmt.Sprintf("root@tcp(localhost:%d)/mysql", i.port))
+ if err != nil {
+ return err
+ }
+ for retry := 0; waitSec > 0; retry++ {
+ if err := db.Ping(); err == nil {
+ break
+ }
+ if retry > waitSec {
+ err := i.proc.Kill()
+ if err != nil {
+ return fmt.Errorf("mysql instance has started as process %d, but failed to kill it, error: %w", i.proc.Pid, err)
+ }
+ return fmt.Errorf("failed to connect to mysql")
+ }
+ time.Sleep(time.Second)
+ }
+
+ return nil
+}
+
+// Stop stops the mysql instance, outputs to stdout and stderr.
+func (i *Instance) Stop(stdout, stderr io.Writer) error {
+ return i.proc.Kill()
+}
+
+// Install installs mysql on basedir, prepares the data directory and default user.
+func Install(basedir, datadir, user string) (*Instance, error) {
+ var tarName, version string
+ // Mysql uses both tar.gz and tar.xz, so we use this ugly hack.
+ var extractFn func(io.Reader, string) error
+ switch {
+ case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
+ tarName = "mysql-8.0.28-macos11-arm64.tar.gz"
+ version = "mysql-8.0.28-macos11-arm64"
+ extractFn = utils.ExtractTarGz
+ case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
+ tarName = "mysql-8.0.28-linux-glibc2.17-x86_64-minimal.tar.xz"
+ version = "mysql-8.0.28-linux-glibc2.17-x86_64-minimal"
+ extractFn = utils.ExtractTarXz
+ default:
+ return nil, fmt.Errorf("unsupported os %q and arch %q", runtime.GOOS, runtime.GOARCH)
+ }
+
+ tarF, err := resources.Open(tarName)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open mysql dist %q, error: %w", tarName, err)
+ }
+ defer tarF.Close()
+
+ if err := extractFn(tarF, basedir); err != nil {
+ return nil, fmt.Errorf("failed to extract mysql distribution %q, error: %w", tarName, err)
+ }
+
+ basedir = filepath.Join(basedir, version)
+
+ socket, err := os.Create(filepath.Join(basedir, "mysql.sock"))
+ if err != nil {
+ return nil, err
+ }
+ socket.Close()
+
+ pidFile, err := os.Create(filepath.Join(basedir, "mysql.pid"))
+ if err != nil {
+ return nil, err
+ }
+ pidFile.Close()
+
+ const configFmt = `[mysqld]
+basedir=%s
+datadir=%s
+pid-file=mysql.pid
+socket=mysql.sock
+user=%s
+`
+ defaultCfgFile, err := os.Create(filepath.Join(basedir, "my.cnf"))
+ if err != nil {
+ return nil, err
+ }
+ fmt.Fprintf(defaultCfgFile, configFmt, basedir, datadir, user)
+ defaultCfgFile.Close()
+
+ args := []string{
+ fmt.Sprintf("--defaults-file=%s", defaultCfgFile.Name()),
+ "--initialize-insecure",
+ }
+
+ cmd := exec.Command(filepath.Join(basedir, "bin", "mysqld"), args...)
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ if err := cmd.Run(); err != nil {
+ return nil, fmt.Errorf("failed to initialize mysql, error: %w", err)
+ }
+
+ return &Instance{
+ basedir: basedir,
+ datadir: datadir,
+ }, nil
+}
diff --git a/resources/mysql/mysql_test.go b/resources/mysql/mysql_test.go
new file mode 100644
index 0000000000..d00a4e60b7
--- /dev/null
+++ b/resources/mysql/mysql_test.go
@@ -0,0 +1,41 @@
+package mysql
+
+import (
+ "database/sql"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ _ "github.com/go-sql-driver/mysql"
+)
+
+func TestStartMySQL(t *testing.T) {
+ basedir := t.TempDir()
+ datadir := filepath.Join(basedir, "data")
+ if err := os.Mkdir(datadir, 0755); err != nil {
+ t.Fatal(err)
+ }
+
+ mysql, err := Install(basedir, datadir, "root")
+ if err != nil {
+ t.Fatalf("Failed to start MySQL: %s", err)
+ }
+ if err := mysql.Start(13306, os.Stdout, os.Stderr, 60); err != nil {
+ t.Fatalf("Failed to start MySQL: %s", err)
+ }
+
+ db, err := sql.Open("mysql", fmt.Sprintf("root@tcp(localhost:%d)/mysql", mysql.Port()))
+ if err != nil {
+ t.Fatalf("Failed to open MySQL: %s", err)
+ }
+ defer db.Close()
+
+ if err := db.Ping(); err != nil {
+ t.Fatalf("Failed to ping MySQL: %s", err)
+ }
+
+ if err := mysql.Stop(os.Stdout, os.Stderr); err != nil {
+ t.Fatalf("Failed to stop MySQL: %s", err)
+ }
+}
diff --git a/resources/postgres/postgres.go b/resources/postgres/postgres.go
new file mode 100644
index 0000000000..35f5c0737e
--- /dev/null
+++ b/resources/postgres/postgres.go
@@ -0,0 +1,161 @@
+package postgres
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/bytebase/bytebase/resources/utils"
+)
+
+// Instance is a postgres instance installed by bytebase
+// for backend storage or testing.
+type Instance struct {
+ // basedir is the directory where the postgres binary is installed.
+ basedir string
+ // datadir is the directory where the postgres data is stored.
+ datadir string
+ // port is the port number of the postgres instance.
+ port int
+}
+
+// Port returns the port number of the postgres instance.
+func (i Instance) Port() int { return i.port }
+
+// Start starts a postgres instance on given port, outputs to stdout and stderr.
+//
+// If port is 0, then it will choose a random unused port.
+//
+// If waitSec > 0, watis at most `waitSec` seconds for the postgres instance to start.
+// Otherwise, returns immediately.
+func (i *Instance) Start(port int, stdout, stderr io.Writer, waitSec int) (err error) {
+ pgbin := filepath.Join(i.basedir, "bin", "pg_ctl")
+
+ i.port = port
+
+ p := exec.Command(pgbin, "start", "-w",
+ "-D", i.datadir,
+ "-o", fmt.Sprintf(`"-p %d"`, i.port))
+ p.Stdout = stdout
+ p.Stderr = stderr
+
+ if err := p.Run(); err != nil {
+ return fmt.Errorf("failed to start postgres %q, error %v", p.String(), err)
+ }
+
+ // TODO
+ for retry := 0; waitSec > 0; retry++ {
+ break
+ }
+
+ return nil
+}
+
+// Stop stops a postgres instance, outputs to stdout and stderr.
+func (i *Instance) Stop(stdout, stderr io.Writer) error {
+ pgbin := filepath.Join(i.basedir, "bin", "pg_ctl")
+ p := exec.Command(pgbin, "stop", "-w",
+ "-D", i.datadir)
+ p.Stderr = stderr
+ p.Stdout = stdout
+
+ if err := p.Run(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Install returns the postgres binary depending on the OS.
+func Install(resourceDir, pgDataDir, pgUser string) (*Instance, error) {
+ var tarName string
+ switch runtime.GOOS {
+ case "darwin":
+ tarName = "postgres-darwin-x86_64.txz"
+ case "linux":
+ if isAlpineLinux() {
+ tarName = "postgres-linux-x86_64-alpine_linux.txz"
+ } else {
+ tarName = "postgres-linux-x86_64.txz"
+ }
+ default:
+ return nil, fmt.Errorf("OS %q is not supported", runtime.GOOS)
+ }
+ log.Printf("Installing Postgres OS %q Arch %q txz %q\n", runtime.GOOS, runtime.GOARCH, tarName)
+ f, err := resources.Open(tarName)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ version := strings.TrimRight(tarName, ".txz")
+
+ pgBinDir := path.Join(resourceDir, version)
+ if _, err := os.Stat(pgBinDir); err != nil {
+ if !os.IsNotExist(err) {
+ return nil, fmt.Errorf("failed to check binary directory path %q, error: %w", pgBinDir, err)
+ }
+ // Install if not exist yet.
+ // The ordering below made Postgres installation atomic.
+ tmpDir := path.Join(resourceDir, fmt.Sprintf("tmp-%s", version))
+ if err := os.RemoveAll(tmpDir); err != nil {
+ return nil, fmt.Errorf("failed to remove postgres binary temp directory %q, error: %w", tmpDir, err)
+ }
+ if err := utils.ExtractTarXz(f, tmpDir); err != nil {
+ return nil, fmt.Errorf("failed to extract txz file, error: %w", err)
+ }
+ if err := os.Rename(tmpDir, pgBinDir); err != nil {
+ return nil, fmt.Errorf("failed to rename postgres binary directory from %q to %q, error: %w", tmpDir, pgBinDir, err)
+ }
+ }
+
+ if err := initDB(pgBinDir, pgDataDir, pgUser); err != nil {
+ return nil, err
+ }
+
+ return &Instance{
+ basedir: pgBinDir,
+ datadir: pgDataDir,
+ }, nil
+}
+
+func isAlpineLinux() bool {
+ _, err := os.Stat("/etc/alpine-release")
+ return err == nil
+}
+
+// initDB inits a postgres database.
+func initDB(pgBinDir, pgDataDir, pgUser string) error {
+ _, err := os.Stat(pgDataDir)
+ if err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("failed to check data directory path %q, error: %w", pgDataDir, err)
+ }
+ // Skip initDB if setup already.
+ if err == nil {
+ return nil
+ }
+
+ if err := os.MkdirAll(pgDataDir, os.ModePerm); err != nil {
+ return fmt.Errorf("failed to make postgres data directory %q, error: %w", pgDataDir, err)
+ }
+
+ args := []string{
+ "-U", pgUser,
+ "-D", pgDataDir,
+ }
+ initDBBinary := filepath.Join(pgBinDir, "bin", "initdb")
+ p := exec.Command(initDBBinary, args...)
+ p.Stderr = os.Stderr
+ p.Stdout = os.Stdout
+
+ if err := p.Run(); err != nil {
+ return fmt.Errorf("failed to initdb %q, error %v", p.String(), err)
+ }
+
+ return nil
+}
diff --git a/resources/postgres_dev.go b/resources/postgres/resources_dev.go
similarity index 76%
rename from resources/postgres_dev.go
rename to resources/postgres/resources_dev.go
index af5f8265e1..15cd94f9f7 100644
--- a/resources/postgres_dev.go
+++ b/resources/postgres/resources_dev.go
@@ -1,9 +1,9 @@
//go:build !release
// +build !release
-package resources
+package postgres
import "embed"
//go:embed postgres-darwin-x86_64.txz postgres-linux-x86_64-alpine_linux.txz postgres-linux-x86_64.txz
-var postgresResources embed.FS
+var resources embed.FS
diff --git a/resources/postgres_release.go b/resources/postgres/resources_release.go
similarity index 68%
rename from resources/postgres_release.go
rename to resources/postgres/resources_release.go
index b981d6e8b9..bddd7c53f9 100644
--- a/resources/postgres_release.go
+++ b/resources/postgres/resources_release.go
@@ -1,9 +1,9 @@
//go:build release
// +build release
-package resources
+package postgres
import "embed"
//go:embed postgres-linux-x86_64-alpine_linux.txz
-var postgresResources embed.FS
+var resources embed.FS
diff --git a/resources/resources.go b/resources/resources.go
deleted file mode 100644
index 79dc08d5d3..0000000000
--- a/resources/resources.go
+++ /dev/null
@@ -1,181 +0,0 @@
-package resources
-
-import (
- "archive/tar"
- "bytes"
- "fmt"
- "io"
- "log"
- "os"
- "os/exec"
- "path"
- "path/filepath"
- "runtime"
- "strings"
-
- // Embeded postgres binaries.
- _ "embed"
-
- "github.com/xi2/xz"
-)
-
-// InstallPostgres returns the postgres binary depending on the OS.
-func InstallPostgres(resourceDir, pgDataDir, pgUser string) (string, error) {
- var tarName string
- switch runtime.GOOS {
- case "darwin":
- tarName = "postgres-darwin-x86_64.txz"
- case "linux":
- if isAlpineLinux() {
- tarName = "postgres-linux-x86_64-alpine_linux.txz"
- } else {
- tarName = "postgres-linux-x86_64.txz"
- }
- default:
- return "", fmt.Errorf("OS %q is not supported", runtime.GOOS)
- }
- log.Printf("Installing Postgres OS %q Arch %q txz %q\n", runtime.GOOS, runtime.GOARCH, tarName)
- data, err := postgresResources.ReadFile(tarName)
- if err != nil {
- return "", err
- }
- version := strings.TrimRight(tarName, ".txz")
-
- pgBinDir := path.Join(resourceDir, version)
- if _, err := os.Stat(pgBinDir); err != nil {
- if !os.IsNotExist(err) {
- return "", fmt.Errorf("failed to check binary directory path %q, error: %w", pgBinDir, err)
- }
- // Install if not exist yet.
- // The ordering below made Postgres installation atomic.
- tmpDir := path.Join(resourceDir, fmt.Sprintf("tmp-%s", version))
- if err := os.RemoveAll(tmpDir); err != nil {
- return "", fmt.Errorf("failed to remove postgres binary temp directory %q, error: %w", tmpDir, err)
- }
- if err := extractTXZ(tmpDir, data); err != nil {
- return "", fmt.Errorf("failed to extract txz file, error: %w", err)
- }
- if err := os.Rename(tmpDir, pgBinDir); err != nil {
- return "", fmt.Errorf("failed to rename postgres binary directory from %q to %q, error: %w", tmpDir, pgBinDir, err)
- }
- }
-
- if err := initDB(pgBinDir, pgDataDir, pgUser); err != nil {
- return "", err
- }
-
- return pgBinDir, nil
-}
-
-func isAlpineLinux() bool {
- _, err := os.Stat("/etc/alpine-release")
- return err == nil
-}
-
-func extractTXZ(directory string, data []byte) error {
- xzReader, err := xz.NewReader(bytes.NewReader(data), 0)
- if err != nil {
- return err
- }
- tarReader := tar.NewReader(xzReader)
- reader := func() io.Reader {
- return tarReader
- }
- for {
- header, err := tarReader.Next()
- if err == io.EOF {
- return nil
- }
- if err != nil {
- return err
- }
-
- targetPath := filepath.Join(directory, header.Name)
- if err := os.MkdirAll(filepath.Dir(targetPath), os.ModePerm); err != nil {
- return err
- }
-
- switch header.Typeflag {
- case tar.TypeReg:
- outFile, err := os.OpenFile(targetPath, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- if _, err := io.Copy(outFile, reader()); err != nil {
- return err
- }
- case tar.TypeSymlink:
- // We need to remove existing file and redo the symlink.
- if err := os.RemoveAll(targetPath); err != nil {
- return err
- }
- if err := os.Symlink(header.Linkname, targetPath); err != nil {
- return err
- }
- }
- }
-}
-
-// initDB inits a postgres database.
-func initDB(pgBinDir, pgDataDir, pgUser string) error {
- _, err := os.Stat(pgDataDir)
- if err != nil && !os.IsNotExist(err) {
- return fmt.Errorf("failed to check data directory path %q, error: %w", pgDataDir, err)
- }
- // Skip initDB if setup already.
- if err == nil {
- return nil
- }
-
- if err := os.MkdirAll(pgDataDir, os.ModePerm); err != nil {
- return fmt.Errorf("failed to make postgres data directory %q, error: %w", pgDataDir, err)
- }
-
- args := []string{
- "-U", pgUser,
- "-D", pgDataDir,
- }
- initDBBinary := filepath.Join(pgBinDir, "bin", "initdb")
- p := exec.Command(initDBBinary, args...)
- p.Stderr = os.Stderr
- p.Stdout = os.Stdout
-
- if err := p.Run(); err != nil {
- return fmt.Errorf("failed to initdb %q, error %v", p.String(), err)
- }
-
- return nil
-}
-
-// StartPostgres starts postgres process.
-func StartPostgres(pgBinDir, pgdataDir string, port int, stdout, stderr *os.File) error {
- pgbin := filepath.Join(pgBinDir, "bin", "pg_ctl")
- p := exec.Command(pgbin, "start", "-w",
- "-D", pgdataDir,
- "-o", fmt.Sprintf(`"-p %d"`, port))
- p.Stdout = stdout
- p.Stderr = stderr
-
- if err := p.Run(); err != nil {
- return fmt.Errorf("failed to start postgres %q, error %v", p.String(), err)
- }
-
- return nil
-}
-
-// StopPostgres stops postgres process.
-func StopPostgres(pgBinDir, pgDataDir string, stdout, stderr *os.File) error {
- pgbin := filepath.Join(pgBinDir, "bin", "pg_ctl")
- p := exec.Command(pgbin, "stop", "-w",
- "-D", pgDataDir)
- p.Stderr = stderr
- p.Stdout = stdout
-
- if err := p.Run(); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/resources/utils/extract.go b/resources/utils/extract.go
new file mode 100644
index 0000000000..72e46a587d
--- /dev/null
+++ b/resources/utils/extract.go
@@ -0,0 +1,86 @@
+package utils
+
+import (
+ "archive/tar"
+ "compress/gzip"
+ "fmt"
+ "io"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+
+ "github.com/xi2/xz"
+)
+
+// ExtractTarGz extracts the given file as .tar.gz format to the given directory.
+func ExtractTarGz(tarGzF io.Reader, targetDir string) error {
+ gzipR, err := gzip.NewReader(tarGzF)
+ if err != nil {
+ return err
+ }
+ defer gzipR.Close()
+ return extractTar(gzipR, targetDir)
+}
+
+// ExtractTarXz extracts the given file as .tar.xz or .txz format to the given directory.
+func ExtractTarXz(tarXzF io.Reader, targetDir string) error {
+ xzR, err := xz.NewReader(tarXzF, 0)
+ if err != nil {
+ return err
+ }
+ return extractTar(xzR, targetDir)
+}
+
+func extractTar(r io.Reader, targetDir string) error {
+ tarReader := tar.NewReader(r)
+ for {
+ header, err := tarReader.Next()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+
+ targetPath, err := filepath.Abs(filepath.Join(targetDir, header.Name))
+ if err != nil {
+ return fmt.Errorf("failed to get absolute path for %q, error: %w", header.Name, err)
+ }
+
+ // Ensure that output paths constructed from zip archive entries
+ // are validated to prevent writing files to unexpected locations.
+ if strings.Contains(targetPath, "..") {
+ return fmt.Errorf("invalid path %q", targetPath)
+ }
+
+ if err := os.MkdirAll(path.Dir(targetPath), os.ModePerm); err != nil {
+ return fmt.Errorf("failed to create directory %q, error: %w", header.Name, err)
+ }
+
+ switch header.Typeflag {
+ case tar.TypeReg:
+ outFile, err := os.OpenFile(targetPath, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
+ if err != nil {
+ return err
+ }
+ defer outFile.Close()
+
+ if _, err := io.Copy(outFile, tarReader); err != nil {
+ return err
+ }
+ case tar.TypeDir:
+ if err := os.MkdirAll(targetPath, os.FileMode(header.Mode)); err != nil {
+ return err
+ }
+ case tar.TypeSymlink:
+ if err := os.Symlink(header.Linkname, targetPath); err != nil {
+ return err
+ }
+ default:
+ return fmt.Errorf("unsupported type flag %d", header.Typeflag)
+ }
+ }
+
+ return nil
+}