Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(engine): engine database upgrade improvement #3811

Merged
merged 4 commits into from
Jan 7, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion engine/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ BUILDTIME := `date "+%m/%d/%y-%H:%M:%S"`

TARGET_DIR = ./dist
TARGET_ENGINE = cds-engine
TARGET_LDFLAGS = -ldflags "-X github.com/ovh/cds/sdk.VERSION=$(VERSION) -X github.com/ovh/cds/sdk.GOOS=$$GOOS -X github.com/ovh/cds/sdk.GOARCH=$$GOARCH -X github.com/ovh/cds/sdk.GITHASH=$(GITHASH) -X github.com/ovh/cds/sdk.BUILDTIME=$(BUILDTIME) -X github.com/ovh/cds/sdk.BINARY=$(TARGET_ENGINE)"
DBMIGRATE = $(words $(wildcard sql/*.sql))
TARGET_LDFLAGS = -ldflags "-X github.com/ovh/cds/sdk.VERSION=$(VERSION) -X github.com/ovh/cds/sdk.GOOS=$$GOOS -X github.com/ovh/cds/sdk.GOARCH=$$GOARCH -X github.com/ovh/cds/sdk.GITHASH=$(GITHASH) -X github.com/ovh/cds/sdk.BUILDTIME=$(BUILDTIME) -X github.com/ovh/cds/sdk.BINARY=$(TARGET_ENGINE) -X github.com/ovh/cds/sdk.DBMIGRATE=$(DBMIGRATE)"
TARGET_OS = $(if ${OS},${OS},windows darwin linux freebsd)
TARGET_ARCH = $(if ${ARCH},${ARCH},amd64 arm 386)

Expand Down
104 changes: 102 additions & 2 deletions engine/api/database/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ package database

import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"

"github.com/mholt/archiver"
"github.com/olekukonko/tablewriter"
"github.com/rubenv/sql-migrate"
"github.com/spf13/cobra"
Expand All @@ -23,8 +30,17 @@ var DBCmd = &cobra.Command{
var upgradeCmd = &cobra.Command{
Use: "upgrade",
Short: "Upgrade schema",
Long: "Migrates the database to the most recent version available.",
Run: upgradeCmdFunc,
Long: `Migrates the database to the most recent version available.

Example of usage:
yesnault marked this conversation as resolved.
Show resolved Hide resolved

engine database upgrade --db-password=your-password --db-sslmode=disable --db-name=cds --migrate-dir=./sql

If the directory --migrate-dir is not up to date with the current version, this
directory will be automatically updated with the release from https://github.com/ovh/cds/releases

`,
Run: upgradeCmdFunc,
}

var downgradeCmd = &cobra.Command{
Expand Down Expand Up @@ -85,11 +101,95 @@ type statusRow struct {
}

func upgradeCmdFunc(cmd *cobra.Command, args []string) {
source := migrate.FileMigrationSource{
Dir: sqlMigrateDir,
}

migrations, err := source.FindMigrations()
if err != nil {
sdk.Exit("Error: %s\n", err)
yesnault marked this conversation as resolved.
Show resolved Hide resolved
}

if sdk.VERSION != "snapshot" {
nbMigrateOnThisVersion, err := strconv.Atoi(sdk.DBMIGRATE)
if err == nil { // no err -> it's a real release
fmt.Printf("There is %d migrate files locally. Current engine needs %d files\n", len(migrations), nbMigrateOnThisVersion)
yesnault marked this conversation as resolved.
Show resolved Hide resolved
if nbMigrateOnThisVersion > len(migrations) {
fmt.Printf("This version %s should contains %d migrate files.\n", sdk.VERSION, nbMigrateOnThisVersion)
downloadSQLTarGz()
migrations, err := source.FindMigrations()
if err != nil {
sdk.Exit("Error: %s\n", err)
yesnault marked this conversation as resolved.
Show resolved Hide resolved
}
fmt.Printf("sql.tar.gz downloaded, there is now %d migrate files locally\n", len(migrations))
yesnault marked this conversation as resolved.
Show resolved Hide resolved
}
} else {
sdk.Exit("Invalid compilation flag DBMIGRATE")
}
}

if err := ApplyMigrations(migrate.Up, sqlMigrateDryRun, sqlMigrateLimitUp); err != nil {
sdk.Exit("Error: %s\n", err)
yesnault marked this conversation as resolved.
Show resolved Hide resolved
}
}

// downloadSQLTarGz downloads sql.tar.gz from github release corresponding to the current engine version
// check status 200 on download
// then write sql.tar.gz file in tmpdir
// then unzip sql.tar.gz file
// then move all sql file to sqlMigrateDir directory
func downloadSQLTarGz() {
yesnault marked this conversation as resolved.
Show resolved Hide resolved
currentTag := sdk.VERSION[:strings.LastIndex(sdk.VERSION, "+")]
urlTarGZ := fmt.Sprintf("https://github.com/ovh/cds/releases/download/%s/sql.tar.gz", currentTag)
fmt.Printf("Getting sql.tar.gz from github on %s...\n", urlTarGZ)

resp, err := http.Get(urlTarGZ)
yesnault marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
sdk.Exit("Error while getting sql.tar.gz from Github: %s\n", err)
yesnault marked this conversation as resolved.
Show resolved Hide resolved
}
defer resp.Body.Close()

if err := sdk.CheckContentTypeBinary(resp); err != nil {
sdk.Exit(err.Error())
}

if resp.StatusCode != 200 {
sdk.Exit("Error http code: %d, url called: %s\n", resp.StatusCode, urlTarGZ)
yesnault marked this conversation as resolved.
Show resolved Hide resolved
}

tmpfile, err := ioutil.TempFile(os.TempDir(), "sql.tar.gz")
if err != nil {
sdk.Exit(err.Error())
}
defer tmpfile.Close()

if _, err = io.Copy(tmpfile, resp.Body); err != nil {
sdk.Exit("Error on creating file: %v", err.Error())
}

dest := tmpfile.Name() + "extract"
if err := archiver.TarGz.Open(tmpfile.Name(), dest); err != nil {
sdk.Exit("Unarchive sql.tar.gz failed: %v", err)
}
// the directory dest/sql/ -> contains all sql files
fmt.Printf("Unarchive to %s\n", dest)

dirFiles := dest + "/sql"
files, err := ioutil.ReadDir(dirFiles)
if err != nil {
sdk.Exit("Error on readDir %s", dirFiles)
}
for _, f := range files {
if strings.HasSuffix(f.Name(), ".sql") {
src := dirFiles + "/" + f.Name()
dest := sqlMigrateDir + "/" + filepath.Base(f.Name())
if err := os.Rename(src, dest); err != nil {
sdk.Exit("Error on move %s to %s err:%v", src, dest, err)
}
}
}
}

func downgradeCmdFunc(cmd *cobra.Command, args []string) {
if err := ApplyMigrations(migrate.Down, sqlMigrateDryRun, sqlMigrateLimitDown); err != nil {
sdk.Exit("Error: %s\n", err)
Expand Down
2 changes: 1 addition & 1 deletion engine/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ var updateCmd = &cobra.Command{

resp, err := http.Get(urlBinary)
if err != nil {
sdk.Exit("Error while getting binary from CDS API: %s\n", err)
sdk.Exit("Error while getting binary from: %s err:%s\n", urlBinary, err)
}
defer resp.Body.Close()

Expand Down
8 changes: 7 additions & 1 deletion sdk/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ var (

//BINARY is set with -ldflags "-X github.com/ovh/cds/sdk.BINARY=$(BINARY)"
BINARY = ""

//DBMIGRATE is set with -ldflags "-X github.com/ovh/cds/sdk.DBMIGRATE=$(DBMIGRATE)"
// this flag contains the number of sql files to migrate for this version
DBMIGRATE = ""
)

func init() {
Expand All @@ -41,6 +45,7 @@ type Version struct {
OS string `json:"os"`
GitHash string `json:"git_hash"`
BuildTime string `json:"build_time"`
DBMigrate string `json:"db_migrate"`
}

// VersionCurrent returns the current version
Expand All @@ -51,10 +56,11 @@ func VersionCurrent() Version {
OS: GOOS,
GitHash: GITHASH,
BuildTime: BUILDTIME,
DBMigrate: DBMIGRATE,
}
}

// VersionString returns a string contains all about current version
func VersionString() string {
return fmt.Sprintf("CDS %s version:%s os:%s architecture:%s git.hash:%s build.time:%s", BINARY, VERSION, GOOS, GOARCH, GITHASH, BUILDTIME)
return fmt.Sprintf("CDS %s version:%s os:%s architecture:%s git.hash:%s build.time:%s db.migrate:%s", BINARY, VERSION, GOOS, GOARCH, GITHASH, BUILDTIME, DBMIGRATE)
}