// runMigration is the entry point for starting a migration
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
}
1011274
func Migrate(c *context.APIContext, f form.MigrateRepo) {
	ctxUser := c.User
	// Not equal means context user is an organization,
	// or is another user/organization if current user is admin.
	if f.Uid != ctxUser.ID {
		org, err := models.GetUserByID(f.Uid)
		if err != nil {
			if errors.IsUserNotExist(err) {
				c.Error(422, "", err)
			} else {
				c.Error(500, "GetUserByID", err)
			}
			return
		} else if !org.IsOrganization() && !c.User.IsAdmin {
			c.Error(403, "", "Given user is not an organization")
			return
		}
		ctxUser = org
	}

	if c.HasError() {
		c.Error(422, "", c.GetErrMsg())
		return
	}

	if ctxUser.IsOrganization() && !c.User.IsAdmin {
		// Check ownership of organization.
		if !ctxUser.IsOwnedBy(c.User.ID) {
			c.Error(403, "", "Given user is not owner of organization")
			return
		}
	}

	remoteAddr, err := f.ParseRemoteAddr(c.User)
	if err != nil {
		if models.IsErrInvalidCloneAddr(err) {
			addrErr := err.(models.ErrInvalidCloneAddr)
			switch {
			case addrErr.IsURLError:
				c.Error(422, "", err)
			case addrErr.IsPermissionDenied:
				c.Error(422, "", "You are not allowed to import local repositories")
			case addrErr.IsInvalidPath:
				c.Error(422, "", "Invalid local path, it does not exist or not a directory")
			default:
				c.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error())
			}
		} else {
			c.Error(500, "ParseRemoteAddr", err)
		}
		return
	}

	repo, err := models.MigrateRepository(c.User, ctxUser, models.MigrateRepoOptions{
		Name:        f.RepoName,
		Description: f.Description,
		IsPrivate:   f.Private || setting.Repository.ForcePrivate,
		IsMirror:    f.Mirror,
		RemoteAddr:  remoteAddr,
	})
	if err != nil {
		if repo != nil {
			if errDelete := models.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
				log.Error(2, "DeleteRepository: %v", errDelete)
			}
		}

		if errors.IsReachLimitOfRepo(err) {
			c.Error(422, "", err)
		} else {
			c.Error(500, "MigrateRepository", models.HandleMirrorCredentials(err.Error(), true))
		}
		return
	}

	log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName)
	c.JSON(201, repo.APIFormat(&api.Permission{true, true, true}))
}
1165495
func (m Migrations) Migrate(db *sqlx.DB) error {
	var initialized bool
	for _, migration := range m {
		if !initialized {
			db.Exec("CREATE TABLE IF NOT EXISTS schema_migrations (id bigint PRIMARY KEY)")
			initialized = true
		}

		tx, err := db.Begin()
		if err != nil {
			return err
		}

		if _, err := tx.Exec("LOCK TABLE schema_migrations IN ACCESS EXCLUSIVE MODE"); err != nil {
			tx.Rollback()
			return err
		}
		var tmp bool
		if err := tx.QueryRow("SELECT true FROM schema_migrations WHERE id = $1", migration.ID).Scan(&tmp); err != sql.ErrNoRows {
			tx.Rollback()
			if err == nil {
				continue
			}
			return err
		}

		for _, s := range migration.Stmts {
			if _, err = tx.Exec(s); err != nil {
				tx.Rollback()
				return err
			}
		}

		if _, err := tx.Exec("INSERT INTO schema_migrations (id) VALUES ($1)", migration.ID); err != nil {
			tx.Rollback()
			return err
		}

		if err := tx.Commit(); err != nil {
			return err
		}
	}
	return nil
}
158898
func (f *Facade) MigrateServices(ctx datastore.Context, req dao.ServiceMigrationRequest) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.MigrateServices"))
	logger := plog.WithFields(log.Fields{
		"tenantid":  req.ServiceID,
	})
	logger.Debug("Started Facade.MigrateServices")
	defer logger.Debug("Finished Facade.MigrateServices")

	var svcAll []service.Service
	// validate service updates
	for _, svc := range req.Modified {
		if _, err := f.validateServiceUpdate(ctx, svc); err != nil {
			logger.WithError(err).WithFields(log.Fields{
				"servicename": svc.Name,
				"serviceid": svc.ID,
			}).Error("Could not validate service for update")
			return err
		}
		svcAll = append(svcAll, *svc)
	}
	// validate service adds
	for _, svc := range req.Added {
		if err := f.validateServiceAdd(ctx, svc); err != nil {
			logger.WithError(err).WithFields(log.Fields{
				"servicename": svc.Name,
				"serviceid": svc.ID,
			}).Error("Could not validate service for add")
			return err
		} else if svc.ID, err = utils.NewUUID36(); err != nil {
			logger.WithError(err).WithFields(log.Fields{
				"servicename": svc.Name,
			}).Error("Could not generate id for new service")
			return err
		}
		svcAll = append(svcAll, *svc)
	}
	// validate service deployments
	for _, sdreq := range req.Deploy {
		svcs, err := f.validateServiceDeployment(ctx, sdreq.ParentID, &sdreq.Service)
		if err != nil {
			logger.WithError(err).WithFields(log.Fields{
				"servicename":  sdreq.Service.Name,
			}).Error("Could not validate service for deployment")
			return err
		}
		svcAll = append(svcAll, svcs...)
	}
	// validate service migration
	if err := f.validateServiceMigration(ctx, svcAll, req.ServiceID); err != nil {
		logger.WithError(err).Error("Could not validate migration of services")
		return err
	}
	logger.Info("Validation checks passed for service migration")

	// Do migration
	for _, filter := range req.LogFilters {
		var action string
		existingFilter, err := f.logFilterStore.Get(ctx, filter.Name, filter.Version)
		if err == nil {
			existingFilter.Filter = filter.Filter
			err = f.logFilterStore.Put(ctx, existingFilter)
			action = "update"
		} else if err != nil && datastore.IsErrNoSuchEntity(err) {
			err = f.logFilterStore.Put(ctx, &filter)
			action = "add"
		}
		if err != nil {
			logger.WithError(err).WithFields(log.Fields{
				"action": action,
				"filtername": filter.Name,
			}).Error("Failed to save log filter")
			return err
		}
		logger.WithFields(log.Fields{
			"action": action,
			"filtername": filter.Name,
			"filterversion": filter.Version,
		}).Debug("Service migration saved LogFilter")
	}
	for _, svc := range req.Modified {
		if err := f.MigrateService(ctx, *svc); err != nil {
			return err
		}
	}
	for _, svc := range req.Added {
		if err := f.AddService(ctx, *svc); err != nil {
			return err
		}
	}
	for _, sdreq := range req.Deploy {
		if _, err := f.DeployService(ctx, "", sdreq.ParentID, false, sdreq.Service); err != nil {
			logger.WithError(err).WithFields(log.Fields{
				"servicename":  sdreq.Service.Name,
			}).Error("Could not deploy service definition")
			return err
		}
	}
	logger.Info("Service migration completed successfully")

	// CC-3514 - rebuild logstash config in case the set of auditable log files has changed
	f.ReloadLogstashConfig(ctx)
	return nil
}
290514
func (g *Gormigrate) Migrate() error {
	if !g.hasMigrations() {
		return ErrNoMigrationDefined
	}
	var targetMigrationID string
	if len(g.migrations) > 0 {
		targetMigrationID = g.migrations[len(g.migrations)-1].ID
	}
	return g.migrate(targetMigrationID)
}
1067679
func (m Migrator) CreateSchemaMigrations() error {
	c := m.Connection
	mtn := c.MigrationTableName()
	err := c.Open()
	if err != nil {
		return errors.Wrap(err, "could not open connection")
	}
	_, err = c.Store.Exec(fmt.Sprintf("select * from %s", mtn))
	if err == nil {
		return nil
	}

	return c.Transaction(func(tx *Connection) error {
		schemaMigrations := newSchemaMigrations(mtn)
		smSQL, err := c.Dialect.FizzTranslator().CreateTable(schemaMigrations)
		if err != nil {
			return errors.Wrap(err, "could not build SQL for schema migration table")
		}
		err = tx.RawQuery(smSQL).Exec()
		if err != nil {
			return errors.WithStack(errors.Wrap(err, smSQL))
		}
		return nil
	})
}
1274961
func (a *MachineAgent) validateMigration(apiCaller base.APICaller) error {
	// TODO(mjs) - more extensive checks to come.
	facade := apimachiner.NewState(apiCaller)
	_, err := facade.Machine(names.NewMachineTag(a.machineId))
	return errors.Trace(err)
}
1155385
func (a *ActivityTypeMigrator) Migrate() {
	for _, d := range a.DeprecatedActivityTypes {
		if a.isDeprecated(d.Domain, d.ActivityType.Name, d.ActivityType.Version) {
			log.Printf("action=migrate at=deprecate-activity domain=%s activity=%s version=%s status=previously-deprecated", d.Domain, d.ActivityType.Name, d.ActivityType.Version)
		} else {
			a.deprecate(d)
			log.Printf("action=migrate at=depreacate-activity domain=%s activity=%s version=%s status=deprecated", d.Domain, d.ActivityType.Name, d.ActivityType.Version)
		}
	}
	for _, r := range a.RegisteredActivityTypes {
		if a.isRegisteredNotDeprecated(r) {
			log.Printf("action=migrate at=register-activity domain=%s activity=%s version=%s status=previously-registered", r.Domain, r.Name, r.Version)
		} else {
			a.register(r)
			log.Printf("action=migrate at=register-activity domain=%s activity=%s version=%s status=registered", r.Domain, r.Name, r.Version)
		}
	}
}
982995
func (pb *Publish) AutoMigrate(values ...interface{}) {
	for _, value := range values {
		tableName := pb.DB.NewScope(value).TableName()
		pb.DraftDB().Table(DraftTableName(tableName)).AutoMigrate(value)
	}
}
505933
func (t *TypesMigrator) Migrate() {
	if t.ActivityTypeMigrator == nil {
		t.ActivityTypeMigrator = new(ActivityTypeMigrator)
	}
	if t.DomainMigrator == nil {
		t.DomainMigrator = new(DomainMigrator)
	}
	if t.WorkflowTypeMigrator == nil {
		t.WorkflowTypeMigrator = new(WorkflowTypeMigrator)
	}
	if t.StreamMigrator == nil {
		t.StreamMigrator = new(StreamMigrator)
	}

	t.DomainMigrator.Migrate()
	ParallelMigrate(
		t.WorkflowTypeMigrator.Migrate,
		t.ActivityTypeMigrator.Migrate,
		t.StreamMigrator.Migrate,
	)
}
108899
func MigrateAll(client *Client) error {
	for _, m := range migrations {
		err := m.Migrate(client)

		if err != nil {
			return err
		}
	}

	return nil
}
399550
func (m *DirectoryMigratorService) Run() error {
	return m.Migrations.Run(m.Directory.GetModels())
}
761886
func (rules *ClientConfigLoadingRules) Migrate() error {
	if rules.MigrationRules == nil {
		return nil
	}

	for destination, source := range rules.MigrationRules {
		if _, err := os.Stat(destination); err == nil {
			// if the destination already exists, do nothing
			continue
		} else if os.IsPermission(err) {
			// if we can't access the file, skip it
			continue
		} else if !os.IsNotExist(err) {
			// if we had an error other than non-existence, fail
			return err
		}

		if sourceInfo, err := os.Stat(source); err != nil {
			if os.IsNotExist(err) || os.IsPermission(err) {
				// if the source file doesn't exist or we can't access it, there's no work to do.
				continue
			}

			// if we had an error other than non-existence, fail
			return err
		} else if sourceInfo.IsDir() {
			return fmt.Errorf("cannot migrate %v to %v because it is a directory", source, destination)
		}

		in, err := os.Open(source)
		if err != nil {
			return err
		}
		defer in.Close()
		out, err := os.Create(destination)
		if err != nil {
			return err
		}
		defer out.Close()

		if _, err = io.Copy(out, in); err != nil {
			return err
		}
	}

	return nil
}
11835
func (_m *FacadeInterface) MigrateServices(ctx datastore.Context, request dao.ServiceMigrationRequest) error {
	ret := _m.Called(ctx, request)

	var r0 error
	if rf, ok := ret.Get(0).(func(datastore.Context, dao.ServiceMigrationRequest) error); ok {
		r0 = rf(ctx, request)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
1085360
func (m *Migrator) Migrations(status int) []*Migration {
	// Sort all migration ids.
	ids := make([]uint64, 0)
	for id, _ := range m.migrations {
		ids = append(ids, id)
	}
	sort.Sort(uint64slice(ids))

	// Find ids for the given status.
	migrations := make([]*Migration, 0)
	for _, id := range ids {
		migration := m.migrations[id]
		if status == -1 || migration.Status == status {
			migrations = append(migrations, migration)
		}
	}
	return migrations
}
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)
}
751635
func (api *API) MigrationStatus() (params.MasterMigrationStatus, error) {
	empty := params.MasterMigrationStatus{}

	mig, err := api.backend.LatestMigration()
	if err != nil {
		return empty, errors.Annotate(err, "retrieving model migration")
	}
	target, err := mig.TargetInfo()
	if err != nil {
		return empty, errors.Annotate(err, "retrieving target info")
	}
	phase, err := mig.Phase()
	if err != nil {
		return empty, errors.Annotate(err, "retrieving phase")
	}
	macsJSON, err := json.Marshal(target.Macaroons)
	if err != nil {
		return empty, errors.Annotate(err, "marshalling macaroons")
	}
	return params.MasterMigrationStatus{
		Spec: params.MigrationSpec{
			ModelTag: names.NewModelTag(mig.ModelUUID()).String(),
			TargetInfo: params.MigrationTargetInfo{
				ControllerTag: target.ControllerTag.String(),
				Addrs:         target.Addrs,
				CACert:        target.CACert,
				AuthTag:       target.AuthTag.String(),
				Password:      target.Password,
				Macaroons:     string(macsJSON),
			},
		},
		MigrationId:      mig.Id(),
		Phase:            phase.String(),
		PhaseChangedTime: mig.PhaseChangedTime(),
	}, nil
}