Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
4933cb8
init impl
6543 Jun 10, 2023
aea8652
fix and add test
6543 Jun 10, 2023
cc3509f
add wip note
6543 Jun 10, 2023
c31f9bd
Merge branch 'master' into add_option_to_import_old_database
6543 Jun 10, 2023
f6b03e8
more
6543 Jun 10, 2023
fa7fe8a
dont run test twice
6543 Jun 10, 2023
2f4807c
next
6543 Jun 10, 2023
c864fce
old steps dont have a uuid - so drop that constrain for now
6543 Jun 10, 2023
ba06090
improve logs and speed
6543 Jun 10, 2023
cc2fd0e
rm test and add todo
6543 Jun 10, 2023
8769f65
make it able to migrate sqlite to mariadb
6543 Jun 10, 2023
8e94448
add import only mode
6543 Jun 11, 2023
1abda67
add copy func for non migrated old logs
6543 Jun 11, 2023
34db3d2
make sure migration is run after database import
6543 Jun 11, 2023
9829213
add docs for this feature
6543 Jun 11, 2023
9140291
wording ...
6543 Jun 11, 2023
02a3eea
Merge branch 'master' into add_option_to_import_old_database
6543 Jun 12, 2023
8936a7f
adopt code
6543 Jun 12, 2023
7b760ce
Merge branch 'master' into add_option_to_import_old_database
6543 Jun 12, 2023
c23013a
allow database migration tests to run 2min
6543 Jun 12, 2023
2699733
Merge branch 'master' into add_option_to_import_old_database
6543 Jun 13, 2023
f7b14db
Merge branch 'master' into add_option_to_import_old_database
6543 Jun 14, 2023
24a9462
Merge branch 'master' into add_option_to_import_old_database
6543 Jul 6, 2023
8ee0156
Update server/store/datastore/migration/copy.go
6543 Jul 6, 2023
3b014a0
Merge branch 'master' into add_option_to_import_old_database
6543 Jul 6, 2023
b34a171
Merge branch 'master' into add_option_to_import_old_database
6543 Jul 8, 2023
8e7a600
Merge branch 'master' into add_option_to_import_old_database
6543 Jul 11, 2023
0be1e09
Merge branch 'main' into add_option_to_import_old_database
6543 Jul 27, 2023
5138c47
update
6543 Jul 27, 2023
1c3c9aa
Merge branch 'main' into add_option_to_import_old_database
6543 Jul 29, 2023
2745a39
Merge branch 'main' into add_option_to_import_old_database
6543 Jul 29, 2023
b3649df
Merge branch 'main' into add_option_to_import_old_database
6543 Aug 3, 2023
78c9551
Merge branch 'main' into add_option_to_import_old_database
6543 Oct 26, 2023
ca818d0
Merge branch 'main' into add_option_to_import_old_database
6543 Mar 21, 2024
c97e715
Update server/store/datastore/migration/copy.go
6543 Mar 22, 2024
32caede
Merge branch 'main' into add_option_to_import_old_database
6543 Mar 22, 2024
f5e466b
Update server/store/datastore/migration/copy.go
6543 Mar 22, 2024
fa030a5
Merge branch 'main' into add_option_to_import_old_database
6543 Jul 5, 2024
c3b4b56
Update docs/docs/30-administration/30-database.md
6543 Jul 5, 2024
4d63c65
fix lint
6543 Jul 5, 2024
c9faaa1
Merge branch 'main' into add_option_to_import_old_database
6543 Aug 16, 2024
d17e9b0
adjust
6543 Aug 16, 2024
6380dca
adjust2
6543 Aug 16, 2024
56986c2
fix after new stuff was done
6543 Aug 16, 2024
5eb2cb3
sync
6543 Aug 16, 2024
6c8cf41
note
6543 Aug 16, 2024
9e72244
xormigrate quirk
6543 Aug 16, 2024
5bcfe45
got it done
6543 Aug 16, 2024
9e9f5d4
Merge branch 'main' into add_option_to_import_old_database
6543 Aug 16, 2024
e5067fc
seq is good enouth
6543 Aug 16, 2024
8f759c1
more time to test import of old database
6543 Aug 16, 2024
1bada2c
fix lint issue
6543 Aug 16, 2024
eaaca37
move const ontop and increase (reqire more ram but is faster)
6543 Aug 17, 2024
01fe704
Merge branch 'main' into add_option_to_import_old_database
6543 Aug 17, 2024
8908441
decrease for postgres
6543 Aug 17, 2024
0031744
decrease for postgres (2)
6543 Aug 17, 2024
d4feee2
Merge branch 'main' into add_option_to_import_old_database
6543 Sep 5, 2024
58e9386
ci.rerun()
6543 Sep 5, 2024
d1b4d24
Merge branch 'main' into add_option_to_import_old_database
6543 Sep 9, 2024
4492099
Merge branch 'main' into add_option_to_import_old_database
6543 Sep 22, 2024
3af78ff
Merge branch 'main' into add_option_to_import_old_database
6543 Sep 25, 2024
1c19193
Merge branch 'main' into add_option_to_import_old_database
6543 Oct 1, 2024
412b527
use generate to keep list up to date
6543 Oct 1, 2024
a435220
newline
6543 Oct 1, 2024
9b3f23f
have only copydata parte code generated
6543 Oct 1, 2024
113887a
Merge branch 'main' into add_option_to_import_old_database
6543 Oct 29, 2024
08d4245
Merge branch 'main' into add_option_to_import_old_database
6543 Nov 5, 2024
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
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ test-cli: ## Test cli code

test-server-datastore: ## Test server datastore
go test -timeout 300s -tags 'test $(TAGS)' -run TestMigrate go.woodpecker-ci.org/woodpecker/v2/server/store/...
go test -race -timeout 100s -tags 'test $(TAGS)' -skip TestMigrate go.woodpecker-ci.org/woodpecker/v2/server/store/...
go test -race -timeout 200s -tags 'test $(TAGS)' -skip TestMigrate go.woodpecker-ci.org/woodpecker/v2/server/store/...

test-server-datastore-coverage: ## Test server datastore with coverage report
go test -race -cover -coverprofile datastore-coverage.out -timeout 300s -tags 'test $(TAGS)' go.woodpecker-ci.org/woodpecker/v2/server/store/...
Expand Down
17 changes: 17 additions & 0 deletions cmd/server/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,23 @@ var flags = append([]cli.Flag{
Usage: "database driver configuration string",
Value: datasourceDefaultValue(),
},
&cli.StringFlag{
Sources: cli.EnvVars("WOODPECKER_OLD_DATABASE_DRIVER"),
Name: "old-driver",
Usage: "driver of database to be migrated & imported",
Value: "",
},
&cli.StringFlag{
Sources: cli.EnvVars("WOODPECKER_OLD_DATABASE_DATASOURCE"),
Name: "old-datasource",
Usage: "driver configuration of database to be migrated & imported",
Value: "",
},
&cli.BoolFlag{
Sources: cli.EnvVars("WOODPECKER_OLD_DATABASE_IMPORT_ONLY"),
Name: "import-old-datastore-only",
Usage: "if '--old-driver' and --old-datasource' are set, exit successfully after import.",
},
&cli.StringFlag{
Sources: cli.NewValueSourceChain(
cli.File(os.Getenv("WOODPECKER_PROMETHEUS_AUTH_TOKEN_FILE")),
Expand Down
28 changes: 23 additions & 5 deletions cmd/server/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ const (
func setupStore(ctx context.Context, c *cli.Command) (store.Store, error) {
datasource := c.String("db-datasource")
driver := c.String("db-driver")
oldDatasource := c.String("old-datasource")
oldDriver := c.String("old-driver")
importOnly := c.Bool("import-old-datastore-only")
xorm := store.XORM{
Log: c.Bool("db-log"),
ShowSQL: c.Bool("db-log-sql"),
Expand All @@ -61,7 +64,7 @@ func setupStore(ctx context.Context, c *cli.Command) (store.Store, error) {
ConnMaxLifetime: c.Duration("db-max-connection-timeout"),
}

if driver == "sqlite3" {
if driver == "sqlite3" || oldDriver == "sqlite3" {
if datastore.SupportedDriver("sqlite3") {
log.Debug().Msg("server has sqlite3 support")
} else {
Expand All @@ -85,16 +88,31 @@ func setupStore(ctx context.Context, c *cli.Command) (store.Store, error) {
XORM: xorm,
}
log.Trace().Msgf("setup datastore: %#v", *opts)
store, err := datastore.NewEngine(opts)
_store, err := datastore.NewEngine(opts)
if err != nil {
return nil, fmt.Errorf("could not open datastore: %w", err)
}

if err := store.Migrate(ctx, c.Bool("migrations-allow-long")); err != nil {
return nil, fmt.Errorf("could not migrate datastore: %w", err)
if oldDatasource == "" {
if err := _store.Migrate(ctx, c.Bool("migrations-allow-long")); err != nil {
return nil, fmt.Errorf("could not migrate datastore: %w", err)
}
} else {
oldOpts := &store.Opts{
Driver: oldDriver,
Config: oldDatasource,
}
log.Trace().Msgf("migrate and import from datastore: %#v", *oldOpts)
log.Info().Msg("database to convert detected")
if err := datastore.ImportOldDB(ctx, oldOpts, opts); err != nil {
return nil, err
}
if importOnly {
os.Exit(0)
}
}

return store, nil
return _store, nil
}

func checkSqliteFileExist(path string) error {
Expand Down
19 changes: 17 additions & 2 deletions docs/docs/30-administration/10-database.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,24 @@ WOODPECKER_DATABASE_DATASOURCE=postgres://root:password@1.2.3.4:5432/postgres?ss

Woodpecker does not create your database automatically. If you are using the MySQL or Postgres driver you will need to manually create your database using `CREATE DATABASE`.

## Database Migration
## Database Schema Migration

Woodpecker automatically handles database migration, including the initial creation of tables and indexes. New versions of Woodpecker will automatically upgrade the database unless otherwise specified in the release notes.
Woodpecker automatically handles database migration between versions, including the initial creation of tables and indexes. New versions of Woodpecker will automatically upgrade the database unless otherwise specified in the release notes.

## Database DBMS Migration

If you have an existing database and want to change the DBMS (e.g. from SQLite to Mariadb):

1. Rename `WOODPECKER_DATABASE_DRIVER` to `WOODPECKER_OLD_DATABASE_DRIVER` and `WOODPECKER_DATABASE_DATASOURCE` to `WOODPECKER_OLD_DATABASE_DATASOURCE`
2. Add the database configuration as you would with a new installation.

On next start, a schema migration will run on the **old** database.
Then the new database is initialized and all data copied.

:::info
If you don't want to start the server afterwards set `WOODPECKER_OLD_DATABASE_IMPORT_ONLY` to **true**.
If the new database already contains data the server will just error and exit.
:::

## Database Backups

Expand Down
12 changes: 12 additions & 0 deletions server/store/datastore/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,15 @@ func (s storage) Migrate(ctx context.Context, allowLong bool) error {
func (s storage) Close() error {
return s.engine.Close()
}

func ImportOldDB(ctx context.Context, srcOpts, destOpts *store.Opts) error {
srcEng, err := xorm.NewEngine(srcOpts.Driver, srcOpts.Config)
if err != nil {
return err
}
destEng, err := xorm.NewEngine(destOpts.Driver, destOpts.Config)
if err != nil {
return err
}
return migration.Copy(ctx, srcEng, destEng)
}
136 changes: 136 additions & 0 deletions server/store/datastore/migration/copy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright 2023 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package migration

import (
"context"
"fmt"
"time"

"github.com/rs/zerolog/log"
"xorm.io/xorm"
"xorm.io/xorm/schemas"
)

const perPage = 1000

func Copy(ctx context.Context, src, dest *xorm.Engine) error {
// first check if the new database already has existing data
for _, bean := range AllBeans {
exist, err := dest.IsTableExist(bean)
if err != nil {
return err
} else if exist {
return fmt.Errorf("existing table '%s' in import destination detected", dest.TableName(bean))
}
}

// next we make sure the all required migrations are executed
if err := Migrate(ctx, src, true); err != nil {
return fmt.Errorf("migrate source database failed: %w", err)
}

// init schema in destination
if err := initSchemaOnly(dest); err != nil {
return err
}

// copy data
return CopyData(ctx, src, dest)
}

func copyBean[T any](ctx context.Context, src, dest *xorm.Engine) error {
tableName := dest.TableName(new(T))
log.Info().Msgf("Start copy %s table", tableName)
aliveMsgCancel := showBeAliveSign(ctx, tableName)
defer aliveMsgCancel(nil)

page := 0
items := make([]*T, 0, perPage)

for {
// for each loop we just check if the context got canceled
if err := ctx.Err(); err != nil {
return err
}

// clean item list
items = items[:0]
log.Trace().Msgf("copy table '%s' page %d", tableName, page)

// read
if err := src.Limit(perPage, page*perPage).Find(&items); err != nil {
return fmt.Errorf("read data of table '%s' page %d failed: %w", tableName, page, err)
}

if len(items) == 0 {
break
}

// write
if _, err := dest.NoAutoTime().AllCols().InsertMulti(items); err != nil {
return fmt.Errorf("write data of table '%s' page %d failed: %w", tableName, page, err)
}

if len(items) < perPage {
break
}
page++
}

// for postgress we have to manually update the sequence for autoincrements
if dest.Dialect().URI().DBType == schemas.POSTGRES {
t, err := dest.TableInfo(new(T))
if err != nil {
return err
}
if t.AutoIncrement != "" {
max := 0
if _, err := dest.SQL(fmt.Sprintf("SELECT MAX(%s) FROM %s;", t.AutoIncrement, tableName)).Get(&max); err != nil {
return fmt.Errorf("could not get max value to calc auto increments max for postgress: %w", err)
}

log.Debug().Msgf("for '%s' found auto increment '%s' with current max at '%d'", tableName, t.AutoIncrement, max)

if max > 0 {
sql := fmt.Sprintf("SELECT pg_catalog.setval('%s_%s_seq', %d, true)", tableName, t.AutoIncrement, max)
if _, err := dest.Exec(sql); err != nil {
log.Debug().Err(err).Msgf("could not exec: '%s'", sql)
return fmt.Errorf("could not update auto increments for postgress: %w", err)
}
}
}
}

aliveMsgCancel(nil)
return nil
}

var showBeAliveSignDelay = time.Second * 20

func showBeAliveSign(ctx context.Context, taskName string) context.CancelCauseFunc {
ctx, cancel := context.WithCancelCause(ctx)
go func() {
for {
select {
case <-ctx.Done():
return
case <-time.After(showBeAliveSignDelay):
log.Info().Msgf("Migration '%s' is still running, please be patient", taskName)
}
}
}()
return cancel
}
69 changes: 69 additions & 0 deletions server/store/datastore/migration/copy_generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions server/store/datastore/migration/copy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package migration

import (
"context"
"os"
"testing"

"github.com/stretchr/testify/assert"
"xorm.io/xorm"
)

func TestCopy(t *testing.T) {
oldConfig := createSQLiteDB(t)
defer func() {
_ = os.Remove(oldConfig)
}()

srcEngine, err := xorm.NewEngine("sqlite3", oldConfig)
if !assert.NoError(t, err) {
t.FailNow()
}
defer srcEngine.Close()
destEngine, _ := xorm.NewEngine("sqlite3", ":memory:")
defer destEngine.Close()

err = Copy(context.Background(), srcEngine, destEngine)
assert.NoError(t, err)
}
Loading