migrations

package
v1.9.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 5, 2024 License: GPL-3.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AddAppSyncStatus = &gormigrate.Migration{
	ID: "20231103-update-table-setting",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "AppStoreSyncStatus", Value: "SyncSuccess"}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddBackupAccountDir = &gormigrate.Migration{
	ID: "20200620-add-backup-dir",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.BackupAccount{}, &model.Cronjob{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddBindAddress = &gormigrate.Migration{
	ID: "20231024-add-bind-address",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "BindAddress", Value: "0.0.0.0"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "Ipv6", Value: "disable"}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddBindAndAllowIPs = &gormigrate.Migration{
	ID: "20230517-add-bind-and-allow",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "BindDomain", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "AllowIPs", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "TimeZone", Value: common.LoadTimeZoneByCmd()}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "NtpSite", Value: "pool.ntp.org"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "MonitorInterval", Value: "5"}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddCommandGroup = &gormigrate.Migration{
	ID: "20231030-add-command-group",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Command{}); err != nil {
			return err
		}
		defaultCommand := &model.Group{IsDefault: true, Name: "默认", Type: "command"}
		if err := tx.Create(defaultCommand).Error; err != nil {
			return err
		}
		if err := tx.Model(&model.Command{}).Where("1 = 1").Update("group_id", defaultCommand.ID).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddDatabaseSSL = &gormigrate.Migration{
	ID: "20231126-add-database-ssl",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Database{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddDatabases = &gormigrate.Migration{
	ID: "20230831-add-databases",
	Migrate: func(tx *gorm.DB) error {
		installRepo := repo.NewIAppInstallRepo()
		_ = tx.Where("name = ? AND address = ?", "local", "127.0.0.1").Delete(&model.Database{}).Error
		mysql := addDatabaseData(tx, installRepo, "mysql")
		if mysql.AppInstallID != 0 {
			if err := tx.Create(mysql).Error; err != nil {
				return err
			}
		}
		mariadb := addDatabaseData(tx, installRepo, "mariadb")
		if mariadb.AppInstallID != 0 {
			if err := tx.Create(mariadb).Error; err != nil {
				return err
			}
		}
		redis := addDatabaseData(tx, installRepo, "redis")
		if redis.AppInstallID != 0 {
			if err := tx.Create(redis).Error; err != nil {
				return err
			}
		}
		postgresql := addDatabaseData(tx, installRepo, "postgresql")
		if postgresql.AppInstallID != 0 {
			if err := tx.Create(postgresql).Error; err != nil {
				return err
			}
		}
		mongodb := addDatabaseData(tx, installRepo, "mongodb")
		if mongodb.AppInstallID != 0 {
			if err := tx.Create(mongodb).Error; err != nil {
				return err
			}
		}
		memcached := addDatabaseData(tx, installRepo, "memcached")
		if memcached.AppInstallID != 0 {
			if err := tx.Create(memcached).Error; err != nil {
				return err
			}
		}

		return nil
	},
}
View Source
var AddDefaultCA = &gormigrate.Migration{
	ID: "20231129-add-default-ca",
	Migrate: func(tx *gorm.DB) error {
		caService := service.NewIWebsiteCAService()
		if _, err := caService.Create(request.WebsiteCACreate{
			CommonName:       "1Panel-CA",
			Country:          "CN",
			KeyType:          "P256",
			Name:             "1Panel",
			Organization:     "FIT2CLOUD",
			OrganizationUint: "1Panel",
			Province:         "Beijing",
			City:             "Beijing",
		}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddDefaultGroup = &gormigrate.Migration{
	ID: "2023022-change-default-group",
	Migrate: func(tx *gorm.DB) error {
		defaultGroup := &model.Group{
			Name:      "默认",
			IsDefault: true,
			Type:      "website",
		}
		if err := tx.Create(defaultGroup).Error; err != nil {
			return err
		}
		if err := tx.Model(&model.Group{}).Where("name = ? AND type = ?", "default", "host").Update("name", "默认").Error; err != nil {
			return err
		}
		if err := tx.Model(&model.Website{}).Where("1 = 1").Update("website_group_id", defaultGroup.ID).Error; err != nil {
			return err
		}
		return tx.Migrator().DropTable("website_groups")
	},
}
View Source
var AddDefaultNetwork = &gormigrate.Migration{
	ID: "20230928-add-default-network",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "DefaultNetwork", Value: "all"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "LastCleanTime", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "LastCleanSize", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "LastCleanData", Value: ""}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddDockerSockPath = &gormigrate.Migration{
	ID: "20231128-add-docker-sock-path",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "DockerSockPath", Value: "unix:///var/run/docker.sock"}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddEntranceAndSSL = &gormigrate.Migration{
	ID: "20230414-add-entrance-and-ssl",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Model(&model.Setting{}).
			Where("key = ? AND value = ?", "SecurityEntrance", "onepanel").
			Updates(map[string]interface{}{"value": ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "SSLType", Value: "self"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "SSLID", Value: "0"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "SSL", Value: "disable"}).Error; err != nil {
			return err
		}
		return tx.AutoMigrate(&model.Website{})
	},
}
View Source
var AddFavorite = &gormigrate.Migration{
	ID: "20231020-add-favorite",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Favorite{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddMfaInterval = &gormigrate.Migration{
	ID: "20230625-add-mfa-interval",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "MFAInterval", Value: "30"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "SystemIP", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "OneDriveID", Value: "MDEwOTM1YTktMWFhOS00ODU0LWExZGMtNmU0NWZlNjI4YzZi"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "OneDriveSc", Value: "akpuOFF+YkNXOU1OLWRzS1ZSRDdOcG1LT2ZRM0RLNmdvS1RkVWNGRA=="}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddPostgresqlSuperUser = &gormigrate.Migration{
	ID: "20231225-add-postgresql-super_user",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.DatabasePostgresql{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddRemoteDB = &gormigrate.Migration{
	ID: "20230724-add-remote-db",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Database{}, &model.DatabaseMysql{}); err != nil {
			return err
		}
		installRepo := repo.NewIAppInstallRepo()
		mysqlInfo, err := installRepo.LoadBaseInfo("mysql", "")
		if err == nil {
			if err := tx.Create(&model.Database{
				Name:     "local",
				Type:     "mysql",
				Version:  mysqlInfo.Version,
				From:     "local",
				Address:  "127.0.0.1",
				Username: "root",
				Password: mysqlInfo.Password,
			}).Error; err != nil {
				return err
			}
		}
		return nil
	},
}
View Source
var AddSettingRecycleBin = &gormigrate.Migration{
	ID: "20231129-add-setting-recycle-bin",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "FileRecycleBin", Value: "enable"}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableApp = &gormigrate.Migration{
	ID: "20200921-add-table-app",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&model.App{}, &model.AppDetail{}, &model.Tag{}, &model.AppTag{}, &model.AppInstall{}, &model.AppInstallResource{})
	},
}
View Source
var AddTableBackupAccount = &gormigrate.Migration{
	ID: "20200916-add-table-backup",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.BackupAccount{}, &model.BackupRecord{}); err != nil {
			return err
		}

		item := &model.BackupAccount{
			Type: "LOCAL",
			Vars: fmt.Sprintf("{\"dir\":\"%s\"}", global.CONF.System.Backup),
		}
		if err := tx.Create(item).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableCronjob = &gormigrate.Migration{
	ID: "20200921-add-table-cronjob",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&model.Cronjob{}, &model.JobRecords{})
	},
}
View Source
var AddTableDatabaseMysql = &gormigrate.Migration{
	ID: "20201020-add-table-database_mysql",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&model.DatabaseMysql{})
	},
}
View Source
var AddTableDatabasePostgresql = &gormigrate.Migration{
	ID: "20231225-add-table-database_postgresql",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.DatabasePostgresql{}); err != nil {
			return err
		}
		if err := tx.AutoMigrate(&model.Cronjob{}); err != nil {
			return err
		}
		var jobs []model.Cronjob
		if err := tx.Where("type == ?", "database").Find(&jobs).Error; err != nil {
			return err
		}
		for _, job := range jobs {
			if job.DBName == "all" {
				if err := tx.Model(&model.Cronjob{}).Where("id = ?", job.ID).Update("db_type", "mysql").Error; err != nil {
					global.LOG.Errorf("update db type of cronjob %s failed, err: %v", job.Name, err)
					continue
				}
			}
			var db model.DatabaseMysql
			if err := tx.Where("id == ?", job.DBName).First(&db).Error; err != nil {
				continue
			}
			var database model.Database
			if err := tx.Where("name == ?", db.MysqlName).First(&database).Error; err != nil {
				continue
			}
			if err := tx.Model(&model.Cronjob{}).Where("id = ?", job.ID).Update("db_type", database.Type).Error; err != nil {
				global.LOG.Errorf("update db type of cronjob %s failed, err: %v", job.Name, err)
				continue
			}
		}
		return nil
	},
}
View Source
var AddTableFirewall = &gormigrate.Migration{
	ID: "20230908-add-table-firewall",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Firewall{}, model.SnapshotStatus{}, &model.Cronjob{}); err != nil {
			return err
		}
		_ = tx.Exec("alter table remote_dbs rename to databases;").Error
		if err := tx.AutoMigrate(&model.Database{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableHost = &gormigrate.Migration{
	ID: "20200818-add-table-host",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Host{}); err != nil {
			return err
		}
		if err := tx.AutoMigrate(&model.Group{}); err != nil {
			return err
		}
		if err := tx.AutoMigrate(&model.Command{}); err != nil {
			return err
		}
		group := model.Group{
			Name: "default", Type: "host", IsDefault: true,
		}
		if err := tx.Create(&group).Error; err != nil {
			return err
		}
		host := model.Host{
			Name: "localhost", Addr: "127.0.0.1", User: "root", Port: 22, AuthMode: "password", GroupID: group.ID,
		}
		if err := tx.Create(&host).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableImageRepo = &gormigrate.Migration{
	ID: "20201009-add-table-imagerepo",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.ImageRepo{}, &model.ComposeTemplate{}, &model.Compose{}); err != nil {
			return err
		}
		item := &model.ImageRepo{
			Name:        "Docker Hub",
			Protocol:    "https",
			DownloadUrl: "docker.io",
			Status:      constant.StatusSuccess,
		}
		if err := tx.Create(item).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableMonitor = &gormigrate.Migration{
	ID: "20200905-add-table-monitor",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&model.MonitorBase{}, &model.MonitorIO{}, &model.MonitorNetwork{})
	},
}
View Source
var AddTableOperationLog = &gormigrate.Migration{
	ID: "20200809-add-table-operation-log",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&model.OperationLog{}, &model.LoginLog{})
	},
}
View Source
var AddTablePHPExtensions = &gormigrate.Migration{
	ID: "20240102-add-php-extensions",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.PHPExtensions{}); err != nil {
			return err
		}
		if err := tx.Create(&model.PHPExtensions{Name: "默认", Extensions: "bcmath,gd,gettext,intl,pcntl,shmop,soap,sockets,sysvsem,xmlrpc,zip"}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableRuntime = &gormigrate.Migration{
	ID: "20230406-add-table-runtime",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&model.Runtime{})
	},
}
View Source
var AddTableSetting = &gormigrate.Migration{
	ID: "20200908-add-table-setting",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Setting{}); err != nil {
			return err
		}
		encryptKey := common.RandStr(16)
		if err := tx.Create(&model.Setting{Key: "UserName", Value: global.CONF.System.Username}).Error; err != nil {
			return err
		}
		global.CONF.System.EncryptKey = encryptKey
		pass, _ := encrypt.StringEncrypt(global.CONF.System.Password)
		if err := tx.Create(&model.Setting{Key: "Password", Value: pass}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "Email", Value: ""}).Error; err != nil {
			return err
		}

		if err := tx.Create(&model.Setting{Key: "PanelName", Value: "1Panel"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "Language", Value: "zh"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "Theme", Value: "auto"}).Error; err != nil {
			return err
		}

		if err := tx.Create(&model.Setting{Key: "SessionTimeout", Value: "86400"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "LocalTime", Value: ""}).Error; err != nil {
			return err
		}

		if err := tx.Create(&model.Setting{Key: "ServerPort", Value: global.CONF.System.Port}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "SecurityEntrance", Value: global.CONF.System.Entrance}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "JWTSigningKey", Value: common.RandStr(16)}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "EncryptKey", Value: encryptKey}).Error; err != nil {
			return err
		}

		if err := tx.Create(&model.Setting{Key: "ExpirationTime", Value: time.Now().AddDate(0, 0, 10).Format("2006-01-02 15:04:05")}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "ExpirationDays", Value: "0"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "ComplexityVerification", Value: "enable"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "MFAStatus", Value: "disable"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "MFASecret", Value: ""}).Error; err != nil {
			return err
		}

		if err := tx.Create(&model.Setting{Key: "MonitorStatus", Value: "enable"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "MonitorStoreDays", Value: "7"}).Error; err != nil {
			return err
		}

		if err := tx.Create(&model.Setting{Key: "MessageType", Value: "none"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "EmailVars", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "WeChatVars", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "DingVars", Value: ""}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "SystemVersion", Value: global.CONF.System.Version}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "SystemStatus", Value: "Free"}).Error; err != nil {
			return err
		}
		if err := tx.Create(&model.Setting{Key: "AppStoreVersion", Value: ""}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableSnap = &gormigrate.Migration{
	ID: "20230106-add-table-snap",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Snapshot{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddTableWebsite = &gormigrate.Migration{
	ID: "20201009-add-table-website",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Website{}, &model.WebsiteDomain{}, &model.WebsiteDnsAccount{}, &model.WebsiteSSL{}, &model.WebsiteAcmeAccount{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var AddWebsiteCA = &gormigrate.Migration{
	ID: "20231125-add-website-ca",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.WebsiteCA{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var DropDatabaseLocal = &gormigrate.Migration{
	ID: "20230914-drop-database-local",
	Migrate: func(tx *gorm.DB) error {
		_ = tx.Where("name = ? AND address = ?", "local", "127.0.0.1").Delete(&model.Database{}).Error
		return nil
	},
}
View Source
var EncryptHostPassword = &gormigrate.Migration{
	ID: "20230703-encrypt-host-password",
	Migrate: func(tx *gorm.DB) error {
		var hosts []model.Host
		if err := tx.Where("1 = 1").Find(&hosts).Error; err != nil {
			return err
		}

		var encryptSetting model.Setting
		if err := tx.Where("key = ?", "EncryptKey").Find(&encryptSetting).Error; err != nil {
			return err
		}
		global.CONF.System.EncryptKey = encryptSetting.Value

		for _, host := range hosts {
			if len(host.Password) != 0 {
				pass, err := encrypt.StringEncrypt(host.Password)
				if err != nil {
					return err
				}
				if err := tx.Model(&model.Host{}).Where("id = ?", host.ID).Update("password", pass).Error; err != nil {
					return err
				}
			}
			if len(host.PrivateKey) != 0 {
				key, err := encrypt.StringEncrypt(host.PrivateKey)
				if err != nil {
					return err
				}
				if err := tx.Model(&model.Host{}).Where("id = ?", host.ID).Update("private_key", key).Error; err != nil {
					return err
				}
			}
			if len(host.PassPhrase) != 0 {
				pass, err := encrypt.StringEncrypt(host.PassPhrase)
				if err != nil {
					return err
				}
				if err := tx.Model(&model.Host{}).Where("id = ?", host.ID).Update("pass_phrase", pass).Error; err != nil {
					return err
				}
			}
		}
		return nil
	},
}
View Source
var UpdateAcmeAccount = &gormigrate.Migration{
	ID: "20231117-update-acme-account",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.WebsiteAcmeAccount{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateAppDetail = &gormigrate.Migration{
	ID: "20230704-update-app-detail",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.AppDetail{}); err != nil {
			return err
		}
		if err := tx.Model(&model.AppDetail{}).Where("1 = 1").Update("ignore_upgrade", "0").Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateAppInstallResource = &gormigrate.Migration{
	ID: "20230831-update-app_install_resource",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.AppInstallResource{}); err != nil {
			return err
		}
		if err := tx.Model(&model.AppInstallResource{}).Where("1 = 1").Updates(map[string]interface{}{
			"from": "local",
		}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateBackupRecordPath = &gormigrate.Migration{
	ID: "20240124-update-cronjob-spec",
	Migrate: func(tx *gorm.DB) error {
		var (
			backupRecords []model.BackupRecord
			localAccount  model.BackupAccount
		)

		_ = tx.Where("type = ?", "LOCAL").First(&localAccount).Error
		if localAccount.ID == 0 {
			return nil
		}
		varMap := make(map[string]string)
		if err := json.Unmarshal([]byte(localAccount.Vars), &varMap); err != nil {
			return err
		}
		dir, ok := varMap["dir"]
		if !ok {
			return errors.New("load local backup dir failed")
		}
		if dir != "/" {
			dir += "/"
		}
		_ = tx.Where("source = ?", "LOCAL").Find(&backupRecords).Error
		for _, record := range backupRecords {
			_ = tx.Model(&model.BackupRecord{}).
				Where("id = ?", record.ID).
				Updates(map[string]interface{}{"file_dir": strings.TrimPrefix(record.FileDir, dir)}).Error
		}
		return nil
	},
}
View Source
var UpdateCronjobSpec = &gormigrate.Migration{
	ID: "20240122-update-cronjob-spec",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Cronjob{}); err != nil {
			return err
		}
		if err := tx.AutoMigrate(&model.BackupRecord{}); err != nil {
			return err
		}
		var (
			jobs           []model.Cronjob
			backupAccounts []model.BackupAccount
		)
		mapAccount := make(map[uint]model.BackupAccount)
		if err := tx.Find(&jobs).Error; err != nil {
			return err
		}
		_ = tx.Find(&backupAccounts).Error
		for _, item := range backupAccounts {
			mapAccount[item.ID] = item
		}
		for _, job := range jobs {
			if job.KeepLocal && mapAccount[uint(job.TargetDirID)].Type != constant.Local {
				if err := tx.Model(&model.Cronjob{}).
					Where("id = ?", job.ID).
					Updates(map[string]interface{}{
						"backup_accounts":  fmt.Sprintf("%v,%v", mapAccount[uint(job.TargetDirID)].Type, constant.Local),
						"default_download": constant.Local,
					}).Error; err != nil {
					return err
				}
				job.DefaultDownload = constant.Local
			} else {
				if err := tx.Model(&model.Cronjob{}).
					Where("id = ?", job.ID).
					Updates(map[string]interface{}{
						"backup_accounts":  mapAccount[uint(job.TargetDirID)].Type,
						"default_download": mapAccount[uint(job.TargetDirID)].Type,
					}).Error; err != nil {
					return err
				}
				job.DefaultDownload = mapAccount[uint(job.TargetDirID)].Type
			}
			if job.Type != "directory" && job.Type != "database" && job.Type != "website" && job.Type != "app" && job.Type != "snapshot" && job.Type != "log" {
				continue
			}

			itemPath := mapAccount[uint(job.TargetDirID)].BackupPath
			if job.DefaultDownload == constant.Local || itemPath == "/" {
				itemPath = ""
			} else {
				itemPath = strings.TrimPrefix(itemPath, "/") + "/"
			}

			var records []model.JobRecords
			_ = tx.Where("cronjob_id = ?", job.ID).Find(&records).Error
			for _, record := range records {
				if job.Type == "snapshot" && record.Status == constant.StatusSuccess {
					var snaps []model.Snapshot
					_ = tx.Where("name like ?", "snapshot_"+"%").Find(&snaps).Error
					for _, snap := range snaps {
						item := model.BackupRecord{
							From:       "cronjob",
							CronjobID:  job.ID,
							Type:       "snapshot",
							Name:       job.Name,
							FileDir:    "system_snapshot",
							FileName:   snap.Name + ".tar.gz",
							Source:     snap.From,
							BackupType: snap.From,
							BaseModel: model.BaseModel{
								CreatedAt: job.CreatedAt,
							},
						}
						_ = tx.Create(&item).Error
					}
					continue
				}
				if job.Type == "log" && record.Status == constant.StatusSuccess {
					item := model.BackupRecord{
						From:       "cronjob",
						CronjobID:  job.ID,
						Type:       "log",
						Name:       job.Name,
						FileDir:    path.Dir(strings.TrimPrefix(record.File, itemPath)),
						FileName:   path.Base(record.File),
						Source:     mapAccount[uint(job.TargetDirID)].Type,
						BackupType: mapAccount[uint(job.TargetDirID)].Type,
						BaseModel: model.BaseModel{
							CreatedAt: job.CreatedAt,
						},
					}
					_ = tx.Create(&item).Error
					continue
				}
				if job.Type == "directory" && record.Status == constant.StatusSuccess {
					item := model.BackupRecord{
						From:       "cronjob",
						CronjobID:  job.ID,
						Type:       "directory",
						Name:       job.Name,
						FileDir:    path.Dir(strings.TrimPrefix(record.File, itemPath)),
						FileName:   path.Base(record.File),
						BackupType: mapAccount[uint(job.TargetDirID)].Type,
						BaseModel: model.BaseModel{
							CreatedAt: job.CreatedAt,
						},
					}
					if record.FromLocal {
						item.Source = constant.Local
					} else {
						item.Source = mapAccount[uint(job.TargetDirID)].Type
					}
					_ = tx.Create(&item).Error
					continue
				}
				if strings.Contains(record.File, ",") {
					files := strings.Split(record.File, ",")
					for _, file := range files {
						_ = tx.Model(&model.BackupRecord{}).
							Where("file_dir = ? AND file_name = ?", path.Dir(strings.TrimPrefix(file, itemPath)), path.Base(file)).
							Updates(map[string]interface{}{"cronjob_id": job.ID, "from": "cronjob"}).Error
					}
				} else {
					_ = tx.Model(&model.BackupRecord{}).
						Where("file_dir = ? AND file_name = ?", path.Dir(strings.TrimPrefix(record.File, itemPath)), path.Base(record.File)).
						Updates(map[string]interface{}{"cronjob_id": job.ID, "from": "cronjob"}).Error
				}
			}
		}

		_ = tx.Exec("ALTER TABLE cronjobs DROP COLUMN spec_type;").Error
		_ = tx.Exec("ALTER TABLE cronjobs DROP COLUMN week;").Error
		_ = tx.Exec("ALTER TABLE cronjobs DROP COLUMN day;").Error
		_ = tx.Exec("ALTER TABLE cronjobs DROP COLUMN hour;").Error
		_ = tx.Exec("ALTER TABLE cronjobs DROP COLUMN minute;").Error
		_ = tx.Exec("ALTER TABLE cronjobs DROP COLUMN second;").Error
		_ = tx.Exec("ALTER TABLE cronjobs DROP COLUMN entry_id;").Error

		return nil
	},
}
View Source
var UpdateCronjobWithDb = &gormigrate.Migration{
	ID: "20230809-update-cronjob-with-db",
	Migrate: func(tx *gorm.DB) error {
		var cronjobs []model.Cronjob
		if err := tx.Where("type = ? AND db_name != ?", "database", "all").Find(&cronjobs).Error; err != nil {
			return nil
		}

		for _, job := range cronjobs {
			var db model.DatabaseMysql
			if err := tx.Where("name = ?", job.DBName).First(&db).Error; err != nil {
				continue
			}
			if err := tx.Model(&model.Cronjob{}).
				Where("id = ?", job.ID).
				Updates(map[string]interface{}{"db_name": db.ID}).Error; err != nil {
				continue
			}
		}
		return nil
	},
}
View Source
var UpdateCronjobWithSecond = &gormigrate.Migration{
	ID: "20200524-update-table-cronjob",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Cronjob{}); err != nil {
			return err
		}
		var jobs []model.Cronjob
		if err := tx.Where("exclusion_rules != ?", "").Find(&jobs).Error; err != nil {
			return err
		}
		for _, job := range jobs {
			if strings.Contains(job.ExclusionRules, ";") {
				newRules := strings.ReplaceAll(job.ExclusionRules, ";", ",")
				if err := tx.Model(&model.Cronjob{}).Where("id = ?", job.ID).Update("exclusion_rules", newRules).Error; err != nil {
					return err
				}
			}
		}
		return nil
	},
}
View Source
var UpdateCronjobWithWebsite = &gormigrate.Migration{
	ID: "20230809-update-cronjob-with-website",
	Migrate: func(tx *gorm.DB) error {
		var cronjobs []model.Cronjob
		if err := tx.Where("(type = ? OR type = ?) AND website != ?", "website", "cutWebsiteLog", "all").Find(&cronjobs).Error; err != nil {
			return err
		}

		for _, job := range cronjobs {
			var web model.Website
			if err := tx.Where("primary_domain = ?", job.Website).First(&web).Error; err != nil {
				continue
			}
			if err := tx.Model(&model.Cronjob{}).
				Where("id = ?", job.ID).
				Updates(map[string]interface{}{"website": web.ID}).Error; err != nil {
				continue
			}
		}

		return nil
	},
}
View Source
var UpdateDatabase = &gormigrate.Migration{
	ID: "20230831-update-database",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Model(&model.DatabaseMysql{}).Where("`from` != ?", "local").Updates(map[string]interface{}{
			"from": "remote",
		}).Error; err != nil {
			return err
		}

		var datas []model.Database
		if err := tx.Find(&datas).Error; err != nil {
			return nil
		}
		for _, data := range datas {
			pass, err := encrypt.StringEncrypt(data.Password)
			if err != nil {
				global.LOG.Errorf("encrypt database %s password failed, err: %v", data.Name, err)
				continue
			}
			if err := tx.Model(&model.Database{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
				"password": pass,
			}).Error; err != nil {
				global.LOG.Errorf("updata database %s info failed, err: %v", data.Name, err)
			}
		}

		var mysqls []model.DatabaseMysql
		if err := tx.Find(&mysqls).Error; err != nil {
			return nil
		}
		for _, data := range mysqls {
			pass, err := encrypt.StringEncrypt(data.Password)
			if err != nil {
				global.LOG.Errorf("encrypt database db %s password failed, err: %v", data.Name, err)
				continue
			}
			if err := tx.Model(&model.DatabaseMysql{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
				"password": pass,
			}).Error; err != nil {
				global.LOG.Errorf("updata database db %s info failed, err: %v", data.Name, err)
			}
		}
		return nil
	},
}
View Source
var UpdateOneDriveToken = &gormigrate.Migration{
	ID: "20240117-update-onedrive-token",
	Migrate: func(tx *gorm.DB) error {
		var (
			backup        model.BackupAccount
			clientSetting model.Setting
			secretSetting model.Setting
		)
		_ = tx.Where("type = ?", "OneDrive").First(&backup).Error
		if backup.ID == 0 {
			return nil
		}
		if len(backup.Credential) == 0 {
			global.LOG.Error("OneDrive configuration lacks token information, please rebind.")
			return nil
		}

		_ = tx.Where("key = ?", "OneDriveID").First(&clientSetting).Error
		if clientSetting.ID == 0 {
			global.LOG.Error("system configuration lacks clientID information, please retry.")
			return nil
		}
		_ = tx.Where("key = ?", "OneDriveSc").First(&secretSetting).Error
		if secretSetting.ID == 0 {
			global.LOG.Error("system configuration lacks clientID information, please retry.")
			return nil
		}
		idItem, _ := base64.StdEncoding.DecodeString(clientSetting.Value)
		global.CONF.System.OneDriveID = string(idItem)
		scItem, _ := base64.StdEncoding.DecodeString(secretSetting.Value)
		global.CONF.System.OneDriveSc = string(scItem)

		varMap := make(map[string]interface{})
		varMap["isCN"] = false
		varMap["client_id"] = global.CONF.System.OneDriveID
		varMap["client_secret"] = global.CONF.System.OneDriveSc
		varMap["redirect_uri"] = constant.OneDriveRedirectURI
		varMap["refresh_token"] = backup.Credential
		token, refreshToken, err := client.RefreshToken("refresh_token", varMap)
		varMap["refresh_status"] = constant.StatusSuccess
		varMap["refresh_time"] = time.Now().Format("2006-01-02 15:04:05")
		if err != nil {
			varMap["refresh_msg"] = err.Error()
			varMap["refresh_status"] = constant.StatusFailed
		}
		varMap["refresh_token"] = refreshToken
		itemVars, _ := json.Marshal(varMap)
		if err := tx.Model(&model.BackupAccount{}).
			Where("id = ?", backup.ID).
			Updates(map[string]interface{}{
				"credential": token,
				"vars":       string(itemVars),
			}).Error; err != nil {
			return err
		}

		return nil
	},
}
View Source
var UpdateRedisParam = &gormigrate.Migration{
	ID: "20230804-update-redis-param",
	Migrate: func(tx *gorm.DB) error {
		var (
			app        model.App
			appInstall model.AppInstall
		)
		if err := tx.Where("key = ?", "redis").First(&app).Error; err != nil {
			return nil
		}
		if err := tx.Where("app_id = ?", app.ID).First(&appInstall).Error; err != nil {
			return nil
		}
		appInstall.Param = strings.ReplaceAll(appInstall.Param, "PANEL_DB_ROOT_PASSWORD", "PANEL_REDIS_ROOT_PASSWORD")
		appInstall.DockerCompose = strings.ReplaceAll(appInstall.DockerCompose, "PANEL_DB_ROOT_PASSWORD", "PANEL_REDIS_ROOT_PASSWORD")
		appInstall.Env = strings.ReplaceAll(appInstall.Env, "PANEL_DB_ROOT_PASSWORD", "PANEL_REDIS_ROOT_PASSWORD")
		if err := tx.Model(&model.AppInstall{}).Where("id = ?", appInstall.ID).Updates(appInstall).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateRuntime = &gormigrate.Migration{
	ID: "20230927-update-runtime",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Runtime{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateSnapshotRecords = &gormigrate.Migration{
	ID: "20240124-update-snapshot-records",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Snapshot{}); err != nil {
			return err
		}
		var snaps []model.Snapshot
		_ = tx.Find(&snaps).Error
		for _, snap := range snaps {
			_ = tx.Model(&model.Snapshot{}).
				Where("id = ?", snap.ID).
				Updates(map[string]interface{}{"default_download": snap.From}).Error
		}
		return nil
	},
}
View Source
var UpdateTableApp = &gormigrate.Migration{
	ID: "20230408-update-table-app",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.App{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateTableAppDetail = &gormigrate.Migration{
	ID: "20200517-update-table-app-detail",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.App{}); err != nil {
			return err
		}
		if err := tx.AutoMigrate(&model.AppDetail{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateTableHost = &gormigrate.Migration{
	ID: "20230410-update-table-host",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Host{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateTableSetting = &gormigrate.Migration{
	ID: "20200516-update-table-setting",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.Create(&model.Setting{Key: "AppStoreLastModified", Value: "0"}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateTableWebsite = &gormigrate.Migration{
	ID: "20230418-update-table-website",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Website{}); err != nil {
			return err
		}
		if err := tx.Model(&model.Website{}).Where("1 = 1").Update("site_dir", "/").Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateTag = &gormigrate.Migration{
	ID: "20231008-update-tag",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Tag{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateWebDavConf = &gormigrate.Migration{
	ID: "20240205-update-webdav-conf",
	Migrate: func(tx *gorm.DB) error {
		var backup model.BackupAccount
		_ = tx.Where("type = ?", constant.WebDAV).First(&backup).Error
		if backup.ID == 0 {
			return nil
		}
		varMap := make(map[string]interface{})
		if err := json.Unmarshal([]byte(backup.Vars), &varMap); err != nil {
			return err
		}
		delete(varMap, "addressItem")
		if port, ok := varMap["port"]; ok {
			varMap["address"] = fmt.Sprintf("%s:%v", varMap["address"], port)
			delete(varMap, "port")
		}

		vars, _ := json.Marshal(varMap)
		if err := tx.Model(&model.BackupAccount{}).Where("id = ?", backup.ID).Updates(map[string]interface{}{"vars": string(vars)}).Error; err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateWebsite = &gormigrate.Migration{
	ID: "20200530-update-table-website",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.Website{}); err != nil {
			return err
		}
		return nil
	},
}
View Source
var UpdateWebsiteBackupRecord = &gormigrate.Migration{
	ID: "20231218-update-backup-record-for-website",
	Migrate: func(tx *gorm.DB) error {
		backupRepo := repo.NewIBackupRepo()
		websitesBackups, _ := backupRepo.ListRecord(repo.NewCommonRepo().WithByType("website"))
		if len(websitesBackups) > 0 {
			for _, backup := range websitesBackups {
				backup.DetailName = backup.Name
				_ = backupRepo.UpdateRecord(&backup)
			}
		}
		return nil
	},
}
View Source
var UpdateWebsiteSSL = &gormigrate.Migration{
	ID: "20231128-update-website-ssl",
	Migrate: func(tx *gorm.DB) error {
		if err := tx.AutoMigrate(&model.WebsiteSSL{}); err != nil {
			return err
		}
		return nil
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL