// MigrateIfExists mocks base method
183448
func (m *MockLegacyDeploymentStateMigrator) MigrateIfExists(arg0 string) (bool, error) {
	ret := m.ctrl.Call(m, "MigrateIfExists", arg0)
	ret0, _ := ret[0].(bool)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
1137199
func (f *Facade) validateServiceMigration(ctx datastore.Context, svcs []service.Service, tenantID string) error {
	svcParentMapNameMap := make(map[string]map[string]struct{})
	endpointMap := make(map[string]string)
	for _, svc := range svcs {
		// check for name uniqueness within the set of new/modified/deployed services
		if svcNameMap, ok := svcParentMapNameMap[svc.ParentServiceID]; ok {
			if _, ok := svcNameMap[svc.Name]; ok {
				glog.Errorf("Found a collision for service name %s and parent %s", svc.Name, svc.ParentServiceID)
				return ErrServiceCollision
			}
			svcParentMapNameMap[svc.ParentServiceID][svc.Name] = struct{}{}
		} else {
			svcParentMapNameMap[svc.ParentServiceID] = make(map[string]struct{})
		}

		// check for endpoint name uniqueness within the set of new/modified/deployed services
		for _, ep := range svc.Endpoints {
			if ep.Purpose == "export" {
				if _, ok := endpointMap[ep.Application]; ok {
					glog.Errorf("Endpoint %s in migrated service %s is a duplicate of an endpoint in one of the other migrated services", ep.Application, svc.Name)
					return ErrServiceDuplicateEndpoint
				}
				endpointMap[ep.Application] = svc.ID
			}
		}
	}

	// check for endpoint name uniqueness btwn the migrated service and the services already defined in
	// the parent application.
	alleps, err := f.GetServiceExportedEndpoints(ctx, tenantID, true)
	if err != nil {
		glog.Errorf("Error looking up exported endpoints for tenant %s: %s", tenantID, err)
		return err
	}
	for _, ep := range alleps {
		if _, ok := endpointMap[ep.Application]; ok {
			if ep.ServiceID != endpointMap[ep.Application] {
				glog.Errorf("Endpoint %s in migrated service is a duplicate of an endpoint already in the application", ep.Application)
				return ErrServiceDuplicateEndpoint
			}
		}
	}

	return nil
}
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,
	)
}
1249557
func (wr *Wrangler) MigrateServedFrom(ctx context.Context, keyspace, shard string, servedType topodatapb.TabletType, cells []string, reverse bool, filteredReplicationWaitTime time.Duration) (err error) {
	// read the destination keyspace, check it
	ki, err := wr.ts.GetKeyspace(ctx, keyspace)
	if err != nil {
		return err
	}
	if len(ki.ServedFroms) == 0 {
		return fmt.Errorf("destination keyspace %v is not a vertical split target", keyspace)
	}

	// read the destination shard, check it
	si, err := wr.ts.GetShard(ctx, keyspace, shard)
	if err != nil {
		return err
	}
	if len(si.SourceShards) != 1 || len(si.SourceShards[0].Tables) == 0 {
		return fmt.Errorf("destination shard %v/%v is not a vertical split target", keyspace, shard)
	}

	// check the migration is valid before locking (will also be checked
	// after locking to be sure)
	sourceKeyspace := si.SourceShards[0].Keyspace
	if err := ki.CheckServedFromMigration(servedType, cells, sourceKeyspace, !reverse); err != nil {
		return err
	}

	// lock the keyspaces, source first.
	ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, sourceKeyspace, fmt.Sprintf("MigrateServedFrom(%v)", servedType))
	if lockErr != nil {
		return lockErr
	}
	defer unlock(&err)
	ctx, unlock, lockErr = wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("MigrateServedFrom(%v)", servedType))
	if lockErr != nil {
		return lockErr
	}
	defer unlock(&err)

	// execute the migration
	err = wr.migrateServedFromLocked(ctx, ki, si, servedType, cells, reverse, filteredReplicationWaitTime)

	// rebuild the keyspace serving graph if there was no error
	if err == nil {
		err = topotools.RebuildKeyspaceLocked(ctx, wr.logger, wr.ts, keyspace, cells)
	}

	return err
}
1112268
func migrate(name string, port uint64, peerListenUrls string, peerAdvertiseUrls string, binPath string, dataDirPath string, etcdDataPrefix string, ttlKeysDirectory string,
	initialCluster string, target *EtcdVersionPair, bundledVersions SupportedVersions, etcdServerArgs string) {

	dataDir, err := OpenOrCreateDataDirectory(dataDirPath)
	if err != nil {
		klog.Errorf("Error opening or creating data directory %s: %v", dataDirPath, err)
		os.Exit(1)
	}

	cfg := &EtcdMigrateCfg{
		binPath:           binPath,
		name:              name,
		port:              port,
		peerListenUrls:    peerListenUrls,
		peerAdvertiseUrls: peerAdvertiseUrls,
		etcdDataPrefix:    etcdDataPrefix,
		ttlKeysDirectory:  ttlKeysDirectory,
		initialCluster:    initialCluster,
		supportedVersions: bundledVersions,
		dataDirectory:     dataDirPath,
		etcdServerArgs:    etcdServerArgs,
	}
	client, err := NewEtcdMigrateClient(cfg)
	if err != nil {
		klog.Errorf("Migration failed: %v", err)
		os.Exit(1)
	}
	defer client.Close()

	migrator := &Migrator{cfg, dataDir, client}

	err = migrator.MigrateIfNeeded(target)
	if err != nil {
		klog.Errorf("Migration failed: %v", err)
		os.Exit(1)
	}
}
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
}
269957
func MigrateReset(currpath, driver, connStr, dir string) {
	migrate("reset", currpath, driver, connStr, dir)
}
381062
func InstallExtensions(schema, migrationsDir string, db *sqlx.DB) error {
	extensions, err := getExtensions(migrationsDir)
	if err != nil {
		return err
	}
	for _, extension := range extensions {
		_, err := db.Exec(fmt.Sprintf("CREATE EXTENSION IF NOT EXISTS %v WITH SCHEMA %v", extension, schema))
		if err != nil {
			return err
		}
	}
	return nil
}
1073090
func (c *Client) FindStoragePoolsForMigration(p *FindStoragePoolsForMigrationParameter) (*StoragePool, error) {
	obj, err := c.Request("findStoragePoolsForMigration", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}
18331
func (m *Migrator) Migrate() error {
	for _, migration := range m.Migrations(Inactive) {
		if err := m.ApplyMigration(migration, upMigration); err != nil {
			return err
		}
	}
	return nil
}
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
}
593557
func migrateIngests(tx *bolt.Tx) error {
	v1bkt := tx.Bucket(bucketKeyVersion)
	if v1bkt == nil {
		return nil
	}

	// iterate through each namespace
	v1c := v1bkt.Cursor()

	for k, v := v1c.First(); k != nil; k, v = v1c.Next() {
		if v != nil {
			continue
		}
		bkt := v1bkt.Bucket(k).Bucket(bucketKeyObjectContent)
		if bkt == nil {
			continue
		}

		dbkt := bkt.Bucket(deprecatedBucketKeyObjectIngest)
		if dbkt == nil {
			continue
		}

		// Create new ingests bucket
		nbkt, err := bkt.CreateBucketIfNotExists(bucketKeyObjectIngests)
		if err != nil {
			return err
		}

		if err := dbkt.ForEach(func(ref, bref []byte) error {
			ibkt, err := nbkt.CreateBucketIfNotExists(ref)
			if err != nil {
				return err
			}
			return ibkt.Put(bucketKeyRef, bref)
		}); err != nil {
			return err
		}

		if err := bkt.DeleteBucket(deprecatedBucketKeyObjectIngest); 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,
	)
}
1345169
func (g *Gormigrate) MigrateTo(migrationID string) error {
	if err := g.checkIDExist(migrationID); err != nil {
		return err
	}
	return g.migrate(migrationID)
}
453096
func AnnouncementMigrations(prefix string) map[string]storage.MigrateFunction {
	funcs := make(map[string]storage.MigrateFunction)
	for v, f := range announcementMigrations {
		funcs[v] = f(prefix)
	}
	return funcs
}
540803
func (f *TranslatorFactory) LocaleExists(localeCode string) (exists bool, errs []error) {
	for _, p := range f.messagesPaths {
		p = strings.TrimRight(p, pathSeparator)
		_, err := os.Stat(p + pathSeparator + localeCode + ".yaml")
		if err == nil {
			exists = true
			return
		} else if !os.IsNotExist(err) {
			errs = append(errs, translatorError{message: "error getting file info: " + err.Error()})
		}

		info, err := os.Stat(p + pathSeparator + localeCode)
		if err == nil && info.IsDir() {
			files, _ := filepath.Glob(p + pathSeparator + localeCode + pathSeparator + "*.yaml")
			for _, file := range files {
				_, err := os.Stat(file)
				if err == nil {
					exists = true
					return
				} else if !os.IsNotExist(err) {
					errs = append(errs, translatorError{message: "error getting file info: " + err.Error()})
				}
			}
		}
	}

	return
}
575536
func MigrateGatewayStats(p *redis.Pool, db sqlx.Queryer) error {
	log.Info("migrating gateway stats")

	var row struct {
		GatewayID           lorawan.EUI64               `db:"gateway_id"`
		Timestamp           time.Time                   `db:"timestamp"`
		Interval            storage.AggregationInterval `db:"interval"`
		RXPacketsReceived   int                         `db:"rx_packets_received"`
		RXPacketsReceivedOK int                         `db:"rx_packets_received_ok"`
		TXPacketsReceived   int                         `db:"tx_packets_received"`
		TXPacketsEmitted    int                         `db:"tx_packets_emitted"`
	}

	rows, err := db.Queryx(`
		select
			gateway_id,
			timestamp,
			interval,
			rx_packets_received,
			rx_packets_received_ok,
			tx_packets_received,
			tx_packets_emitted
		from
			gateway_stats
		where
			(interval = 'MINUTE' and timestamp >= (now() - interval '65 minutes')) or
			(interval = 'HOUR' and timestamp >= (now() - interval '25 hours')) or
			(interval = 'DAY' and timestamp >= (now() - interval '32 days')) or
			(interval = 'MONTH' and timestamp >= (now() - interval '13 months'))
	`)
	if err != nil {
		return errors.Wrap(err, "select error")
	}
	defer rows.Close()

	for rows.Next() {
		if err := rows.StructScan(&row); err != nil {
			return errors.Wrap(err, "scan error")
		}

		switch row.Interval {
		case storage.AggregationMinute, storage.AggregationHour, storage.AggregationDay, storage.AggregationMonth:
			err = storage.SaveMetricsForInterval(p, row.Interval, "gw:"+row.GatewayID.String(), storage.MetricsRecord{
				Time: row.Timestamp,
				Metrics: map[string]float64{
					"rx_count":    float64(row.RXPacketsReceived),
					"rx_ok_count": float64(row.RXPacketsReceivedOK),
					"tx_count":    float64(row.TXPacketsReceived),
					"tx_ok_count": float64(row.TXPacketsEmitted),
				},
			})
			if err != nil {
				return errors.Wrap(err, "save metrics error")
			}
		}
	}

	log.Info("gateway stats migrated")
	return nil
}