// Migrates ${HOME}/.minio/config.json to '<export_path>/.minio.sys/config/config.json'
760147
func migrateConfigToMinioSys(objAPI ObjectLayer) (err error) {
	// Construct path to config.json for the given bucket.
	configFile := path.Join(minioConfigPrefix, minioConfigFile)

	// Verify if config was already available in .minio.sys in which case, nothing more to be done.
	if err = checkConfig(context.Background(), objAPI, configFile); err != errConfigNotFound {
		return err
	}

	defer func() {
		// Rename config.json to config.json.deprecated only upon
		// success of this function.
		if err == nil {
			os.Rename(getConfigFile(), getConfigFile()+".deprecated")
		}
	}()

	transactionConfigFile := configFile + ".transaction"

	// As object layer's GetObject() and PutObject() take respective lock on minioMetaBucket
	// and configFile, take a transaction lock to avoid data race between readConfig()
	// and saveConfig().
	objLock := globalNSMutex.NewNSLock(minioMetaBucket, transactionConfigFile)
	if err = objLock.GetLock(globalOperationTimeout); err != nil {
		return err
	}
	defer objLock.Unlock()

	// Verify if backend already has the file (after holding lock)
	if err = checkConfig(context.Background(), objAPI, configFile); err != errConfigNotFound {
		return err
	} // if errConfigNotFound proceed to migrate..

	var config = &serverConfig{}
	if _, err = Load(getConfigFile(), config); err != nil {
		if !os.IsNotExist(err) {
			return err
		}
		// Read from deprecate file as well if necessary.
		if _, err = Load(getConfigFile()+".deprecated", config); err != nil {
			if !os.IsNotExist(err) {
				return err
			}
			// If all else fails simply initialize the server config.
			return newSrvConfig(objAPI)
		}

	}
	return saveServerConfig(context.Background(), objAPI, config)
}
164306
func RunMigration(cmd *commands.Command, args []string) int {
	currpath, _ := os.Getwd()

	gps := utils.GetGOPATHs()
	if len(gps) == 0 {
		beeLogger.Log.Fatal("GOPATH environment variable is not set or empty")
	}

	gopath := gps[0]

	beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath)

	// Getting command line arguments
	if len(args) != 0 {
		cmd.Flag.Parse(args[1:])
	}
	if mDriver == "" {
		mDriver = utils.DocValue(config.Conf.Database.Driver)
		if mDriver == "" {
			mDriver = "mysql"
		}
	}
	if mConn == "" {
		mConn = utils.DocValue(config.Conf.Database.Conn)
		if mConn == "" {
			mConn = "root:@tcp(127.0.0.1:3306)/test"
		}
	}
	if mDir == "" {
		mDir = utils.DocValue(config.Conf.Database.Dir)
		if mDir == "" {
			mDir = utils.DocValue(path.Join(currpath, "database", "migrations"))
		}
	}

	beeLogger.Log.Infof("Using '%s' as 'driver'", mDriver)
	//Log sensitive connection information only when DEBUG is set to true.
	beeLogger.Log.Debugf("Conn: %s", utils.FILE(), utils.LINE(), mConn)
	beeLogger.Log.Infof("Using '%s' as 'dir'", mDir)
	driverStr, connStr, dirStr := string(mDriver), string(mConn), string(mDir)

	dirRune := []rune(dirStr)

	if dirRune[0] != '/' && dirRune[1] != ':' {
		dirStr = path.Join(currpath, dirStr)
	}

	if len(args) == 0 {
		// run all outstanding migrations
		beeLogger.Log.Info("Running all outstanding migrations")
		MigrateUpdate(currpath, driverStr, connStr, dirStr)
	} else {
		mcmd := args[0]
		switch mcmd {
		case "rollback":
			beeLogger.Log.Info("Rolling back the last migration operation")
			MigrateRollback(currpath, driverStr, connStr, dirStr)
		case "reset":
			beeLogger.Log.Info("Reseting all migrations")
			MigrateReset(currpath, driverStr, connStr, dirStr)
		case "refresh":
			beeLogger.Log.Info("Refreshing all migrations")
			MigrateRefresh(currpath, driverStr, connStr, dirStr)
		default:
			beeLogger.Log.Fatal("Command is missing")
		}
	}
	beeLogger.Log.Success("Migration successful!")
	return 0
}
911519
func migrate(goal, currpath, driver, connStr, dir string) {
	if dir == "" {
		dir = path.Join(currpath, "database", "migrations")
	}
	postfix := ""
	if runtime.GOOS == "windows" {
		postfix = ".exe"
	}
	binary := "m" + postfix
	source := binary + ".go"

	// Connect to database
	db, err := sql.Open(driver, connStr)
	if err != nil {
		beeLogger.Log.Fatalf("Could not connect to database using '%s': %s", connStr, err)
	}
	defer db.Close()

	checkForSchemaUpdateTable(db, driver)
	latestName, latestTime := getLatestMigration(db, goal)
	writeMigrationSourceFile(dir, source, driver, connStr, latestTime, latestName, goal)
	buildMigrationBinary(dir, binary)
	runMigrationBinary(dir, binary)
	removeTempFile(dir, source)
	removeTempFile(dir, binary)
}
813237
func Migrate(db *sql.DB, catalog string, configuration MigrationConfiguration) error {

	var err error
	if db == nil {
		return errs.Errorf("Database handle is nil\n")
	}

	m := GetMigrations(configuration)

	var tx *sql.Tx
	for nextVersion := int64(0); nextVersion < int64(len(m)) && err == nil; nextVersion++ {

		tx, err = db.Begin()
		if err != nil {
			return errs.Errorf("Failed to start transaction: %s\n", err)
		}

		err = MigrateToNextVersion(tx, &nextVersion, m, catalog)

		if err != nil {
			oldErr := err
			log.Info(nil, map[string]interface{}{
				"next_version": nextVersion,
				"migrations":   m,
				"err":          err,
			}, "Rolling back transaction due to: %v", err)

			if err = tx.Rollback(); err != nil {
				log.Error(nil, map[string]interface{}{
					"next_version": nextVersion,
					"migrations":   m,
					"err":          err,
				}, "error while rolling back transaction")
				return errs.Errorf("Error while rolling back transaction: %s\n", err)
			}
			return oldErr
		}

		if err = tx.Commit(); err != nil {
			log.Error(nil, map[string]interface{}{
				"migrations": m,
				"err":        err,
			}, "error during transaction commit: %v", err)
			return errs.Errorf("Error during transaction commit: %s\n", err)
		}

	}

	if err != nil {
		log.Error(nil, map[string]interface{}{
			"migrations": m,
			"err":        err,
		}, "migration failed with error: %v", err)
		return errs.Errorf("Migration failed with error: %s\n", err)
	}

	return nil
}
999894
func migrateV2ToV3() error {
	configFile := getConfigFile()

	cv2 := &configV2{}
	_, err := Load(configFile, cv2)
	if os.IsNotExist(err) {
		return nil
	} else if err != nil {
		return fmt.Errorf("Unable to load config version ‘2’. %v", err)
	}
	if cv2.Version != "2" {
		return nil
	}

	cred, err := auth.CreateCredentials(cv2.Credentials.AccessKey, cv2.Credentials.SecretKey)
	if err != nil {
		return fmt.Errorf("Invalid credential in V2 configuration file. %v", err)
	}

	srvConfig := &configV3{}
	srvConfig.Version = "3"
	srvConfig.Addr = ":9000"
	srvConfig.Credential = cred
	srvConfig.Region = cv2.Credentials.Region
	if srvConfig.Region == "" {
		// Region needs to be set for AWS Signature V4.
		srvConfig.Region = globalMinioDefaultRegion
	}
	srvConfig.Logger.Console = consoleLoggerV1{
		Enable: true,
		Level:  "fatal",
	}
	flogger := fileLoggerV1{}
	flogger.Level = "error"
	if cv2.FileLogger.Filename != "" {
		flogger.Enable = true
		flogger.Filename = cv2.FileLogger.Filename
	}
	srvConfig.Logger.File = flogger

	slogger := syslogLoggerV3{}
	slogger.Level = "debug"
	if cv2.SyslogLogger.Addr != "" {
		slogger.Enable = true
		slogger.Addr = cv2.SyslogLogger.Addr
	}
	srvConfig.Logger.Syslog = slogger

	if err = Save(configFile, srvConfig); err != nil {
		return fmt.Errorf("Failed to migrate config from ‘%s’ to ‘%s’. %v", cv2.Version, srvConfig.Version, err)
	}

	logger.Info(configMigrateMSGTemplate, configFile, cv2.Version, srvConfig.Version)
	return nil
}
775735
func (d *DashboardsStore) Migrate(ctx context.Context) error {
	// 1. Add UUIDs to cells without one
	boards, err := d.All(ctx)
	if err != nil {
		return err
	}
	if err := d.AddIDs(ctx, boards); err != nil {
		return nil
	}

	defaultOrg, err := d.client.OrganizationsStore.DefaultOrganization(ctx)
	if err != nil {
		return err
	}

	for _, board := range boards {
		if board.Organization == "" {
			board.Organization = defaultOrg.ID
			if err := d.Update(ctx, board); err != nil {
				return nil
			}
		}
	}

	return nil
}
773306
func (c *Client) MigrateVirtualMachineWithVolume(p *MigrateVirtualMachineWithVolumeParameter) (*VirtualMachine, error) {
	obj, err := c.Request("migrateVirtualMachineWithVolume", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*VirtualMachine), err
}
377459
func (s *VirtualMachineService) NewMigrateVirtualMachineWithVolumeParams(hostid string, virtualmachineid string) *MigrateVirtualMachineWithVolumeParams {
	p := &MigrateVirtualMachineWithVolumeParams{}
	p.p = make(map[string]interface{})
	p.p["hostid"] = hostid
	p.p["virtualmachineid"] = virtualmachineid
	return p
}
814407
func (s *SourcesStore) Migrate(ctx context.Context) error {
	sources, err := s.All(ctx)
	if err != nil {
		return err
	}
	if len(sources) == 0 {
		if err := s.Put(ctx, DefaultSource); err != nil {
			return err
		}
	}

	defaultOrg, err := s.client.OrganizationsStore.DefaultOrganization(ctx)
	if err != nil {
		return err
	}

	for _, source := range sources {
		if source.Organization == "" {
			source.Organization = defaultOrg.ID
		}
		if source.Role == "" {
			source.Role = roles.ViewerRoleName
		}
		if err := s.Update(ctx, source); err != nil {
			return nil
		}
	}

	return nil
}
623175
func (m Migration) Migrate(client *Client) error {
	complete, err := IsMigrationComplete(client.db, m.ID)
	if err != nil {
		return err
	}
	if complete {
		return nil
	}

	if client.logger != nil {
		client.logger.Info("Running migration ", m.ID, "")
	}

	if err = m.Up(client.db); err != nil {
		return err
	}

	return MarkMigrationAsComplete(client.db, m.ID)
}
13367
func (s *VirtualMachineService) MigrateVirtualMachine(p *MigrateVirtualMachineParams) (*MigrateVirtualMachineResponse, error) {
	resp, err := s.cs.newRequest("migrateVirtualMachine", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r MigrateVirtualMachineResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
1282694
func (c *Client) Migrate(host string, port uint, key string, destination string, timeout int64) (string, error) {
	var ret string

	err := c.command(
		&ret,
		[]byte("MIGRATE"),
		[]byte(host),
		to.Bytes(port),
		[]byte(key),
		[]byte(destination),
		to.Bytes(timeout),
	)

	return ret, err
}
1064157
func Migrate(name string, f func(db sqlx.Ext) error) error {
	return storage.Transaction(func(tx sqlx.Ext) error {
		_, err := tx.Exec(`lock table code_migration`)
		if err != nil {
			return errors.Wrap(err, "lock code migration table error")
		}

		res, err := tx.Exec(`
			insert into code_migration (
				id,
				applied_at
			) values ($1, $2)
			on conflict
				do nothing
		`, name, time.Now())
		if err != nil {
			switch err := err.(type) {
			case *pq.Error:
				switch err.Code.Name() {
				case "unique_violation":
					return nil
				}
			}

			return err
		}

		ra, err := res.RowsAffected()
		if err != nil {
			return err
		}

		if ra == 0 {
			return nil
		}

		return f(tx)
	})
}
364496
func migrateV12ToV13() error {
	configFile := getConfigFile()

	cv12 := &serverConfigV12{}
	_, err := Load(configFile, cv12)
	if os.IsNotExist(err) {
		return nil
	} else if err != nil {
		return fmt.Errorf("Unable to load config version ‘12’. %v", err)
	}
	if cv12.Version != "12" {
		return nil
	}

	// Copy over fields from V12 into V13 config struct
	srvConfig := &serverConfigV13{
		Logger: &loggerV7{},
		Notify: &notifierV3{},
	}
	srvConfig.Version = "13"
	srvConfig.Credential = cv12.Credential
	srvConfig.Region = cv12.Region
	if srvConfig.Region == "" {
		// Region needs to be set for AWS Signature Version 4.
		srvConfig.Region = globalMinioDefaultRegion
	}
	srvConfig.Logger.Console = cv12.Logger.Console
	srvConfig.Logger.File = cv12.Logger.File

	// check and set notifiers config
	if len(cv12.Notify.AMQP) == 0 {
		srvConfig.Notify.AMQP = make(map[string]target.AMQPArgs)
		srvConfig.Notify.AMQP["1"] = target.AMQPArgs{}
	} else {
		srvConfig.Notify.AMQP = cv12.Notify.AMQP
	}
	if len(cv12.Notify.ElasticSearch) == 0 {
		srvConfig.Notify.Elasticsearch = make(map[string]target.ElasticsearchArgs)
		srvConfig.Notify.Elasticsearch["1"] = target.ElasticsearchArgs{}
	} else {
		srvConfig.Notify.Elasticsearch = cv12.Notify.ElasticSearch
	}
	if len(cv12.Notify.Redis) == 0 {
		srvConfig.Notify.Redis = make(map[string]target.RedisArgs)
		srvConfig.Notify.Redis["1"] = target.RedisArgs{}
	} else {
		srvConfig.Notify.Redis = cv12.Notify.Redis
	}
	if len(cv12.Notify.PostgreSQL) == 0 {
		srvConfig.Notify.PostgreSQL = make(map[string]target.PostgreSQLArgs)
		srvConfig.Notify.PostgreSQL["1"] = target.PostgreSQLArgs{}
	} else {
		srvConfig.Notify.PostgreSQL = cv12.Notify.PostgreSQL
	}
	if len(cv12.Notify.Kafka) == 0 {
		srvConfig.Notify.Kafka = make(map[string]target.KafkaArgs)
		srvConfig.Notify.Kafka["1"] = target.KafkaArgs{}
	} else {
		srvConfig.Notify.Kafka = cv12.Notify.Kafka
	}
	if len(cv12.Notify.NATS) == 0 {
		srvConfig.Notify.NATS = make(map[string]target.NATSArgs)
		srvConfig.Notify.NATS["1"] = target.NATSArgs{}
	} else {
		srvConfig.Notify.NATS = cv12.Notify.NATS
	}

	// V12 will not have a webhook config. So we initialize one here.
	srvConfig.Notify.Webhook = make(map[string]target.WebhookArgs)
	srvConfig.Notify.Webhook["1"] = target.WebhookArgs{}

	if err = Save(configFile, srvConfig); err != nil {
		return fmt.Errorf("Failed to migrate config from ‘%s’ to ‘%s’. %v", cv12.Version, srvConfig.Version, err)
	}

	logger.Info(configMigrateMSGTemplate, configFile, cv12.Version, srvConfig.Version)
	return nil
}
236642
func (m *Migrate) Migrate() error {
	if err := m.createMigrationTableIfNotExists(); err != nil {
		return err
	}

	if m.initSchema != nil && m.isFirstRun() {
		return m.runInitSchema()
	}

	for _, migration := range m.migrations {
		if err := m.runMigration(migration); err != nil {
			return err
		}
	}
	return nil
}
985038
func (e *CombinedEtcdClient) Migrate(version *EtcdVersion) error {
	// We cannot use etcd/clientv3 to make this call as it is implemented in etcd/etcdctl.
	if version.Major != 3 {
		return fmt.Errorf("etcd 3.x required but got version '%s'", version)
	}
	return e.runEtcdctlCommand(version,
		"migrate",
		"--data-dir", e.cfg.dataDirectory,
	)
}
108859
func migrate(args []string, r *githistory.Rewriter, l *tasklog.Logger, opts *githistory.RewriteOptions) {
	requireInRepo()

	opts, err := rewriteOptions(args, opts, l)
	if err != nil {
		ExitWithError(err)
	}

	_, err = r.Rewrite(opts)
	if err != nil {
		ExitWithError(err)
	}
}