// masterMigrateServedType operates with the keyspace locked
182906
func (wr *Wrangler) masterMigrateServedType(ctx context.Context, keyspace string, sourceShards, destinationShards []*topo.ShardInfo, filteredReplicationWaitTime time.Duration, reverseReplication bool) (err error) {
	// Ensure other served types have migrated.
	srvKeyspaces, err := wr.ts.GetSrvKeyspaceAllCells(ctx, keyspace)
	if err != nil {
		return err
	}

	si := sourceShards[0]
	for _, srvKeyspace := range srvKeyspaces {
		var shardServedTypes []string
		for _, partition := range srvKeyspace.GetPartitions() {
			if partition.GetServedType() != topodatapb.TabletType_MASTER {
				for _, shardReference := range partition.GetShardReferences() {
					if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
						shardServedTypes = append(shardServedTypes, partition.GetServedType().String())
					}
				}
			}
		}
		if len(shardServedTypes) > 0 {
			return fmt.Errorf("cannot migrate MASTER away from %v/%v until everything else is migrated. Make sure that the following types are migrated first: %v", si.Keyspace(), si.ShardName(), strings.Join(shardServedTypes, ", "))
		}
	}

	ev := &events.MigrateServedTypes{
		KeyspaceName:      keyspace,
		SourceShards:      sourceShards,
		DestinationShards: destinationShards,
		ServedType:        topodatapb.TabletType_MASTER,
	}
	event.DispatchUpdate(ev, "start")
	defer func() {
		if err != nil {
			event.DispatchUpdate(ev, "failed: "+err.Error())
		}
	}()

	// Phase 1
	// - switch the source shards to read-only by disabling query service
	// - gather all replication points
	// - wait for filtered replication to catch up
	// - mark source shards as frozen
	event.DispatchUpdate(ev, "disabling query service on all source masters")
	if err := wr.updateShardRecords(ctx, keyspace, sourceShards, nil, topodatapb.TabletType_MASTER, true, false); err != nil {
		wr.cancelMasterMigrateServedTypes(ctx, keyspace, sourceShards)
		return err
	}
	if err := wr.refreshMasters(ctx, sourceShards); err != nil {
		wr.cancelMasterMigrateServedTypes(ctx, keyspace, sourceShards)
		return err
	}

	event.DispatchUpdate(ev, "getting positions of source masters")
	masterPositions, err := wr.getMastersPosition(ctx, sourceShards)
	if err != nil {
		wr.cancelMasterMigrateServedTypes(ctx, keyspace, sourceShards)
		return err
	}

	event.DispatchUpdate(ev, "waiting for destination masters to catch up")
	if err := wr.waitForFilteredReplication(ctx, masterPositions, destinationShards, filteredReplicationWaitTime); err != nil {
		wr.cancelMasterMigrateServedTypes(ctx, keyspace, sourceShards)
		return err
	}

	// We've reached the point of no return. Freeze the tablet control records in the source masters.
	if err := wr.updateFrozenFlag(ctx, sourceShards, true); err != nil {
		wr.cancelMasterMigrateServedTypes(ctx, keyspace, sourceShards)
		return err
	}

	// Phase 2
	// Always setup reverse replication. We'll start it later if reverseReplication was specified.
	// This will allow someone to reverse the replication later if they change their mind.
	if err := wr.setupReverseReplication(ctx, sourceShards, destinationShards); err != nil {
		// It's safe to unfreeze if reverse replication setup fails.
		wr.cancelMasterMigrateServedTypes(ctx, keyspace, sourceShards)
		unfreezeErr := wr.updateFrozenFlag(ctx, sourceShards, false)
		if unfreezeErr != nil {
			wr.Logger().Errorf("Problem recovering for failed reverse replication: %v", unfreezeErr)
		}

		return err
	}

	// Destination shards need different handling than what updateShardRecords does.
	event.DispatchUpdate(ev, "updating destination shards")

	// Enable query service
	err = wr.ts.UpdateDisableQueryService(ctx, keyspace, destinationShards, topodatapb.TabletType_MASTER, nil, false)
	if err != nil {
		return err
	}

	for i, si := range destinationShards {
		ti, err := wr.ts.GetTablet(ctx, si.MasterAlias)
		if err != nil {
			return err
		}
		// Stop VReplication streams.
		for _, sourceShard := range si.SourceShards {
			if _, err := wr.tmc.VReplicationExec(ctx, ti.Tablet, binlogplayer.DeleteVReplication(sourceShard.Uid)); err != nil {
				return err
			}
		}
		// Similar to updateShardRecords, but we also remove SourceShards.
		destinationShards[i], err = wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error {
			si.SourceShards = nil
			si.IsMasterServing = true
			return nil
		})
		if err != nil {
			return err
		}
	}

	event.DispatchUpdate(ev, "setting destination masters read-write")
	if err := wr.refreshMasters(ctx, destinationShards); err != nil {
		return err
	}

	// Update srvKeyspace now
	if err = wr.ts.MigrateServedType(ctx, keyspace, destinationShards, sourceShards, topodatapb.TabletType_MASTER, nil); err != nil {
		return err
	}

	// Make sure that from now on source shards have IsMasterServing set to false
	for _, si := range sourceShards {
		_, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error {
			si.IsMasterServing = false
			return nil
		})
		if err != nil {
			return err
		}
	}

	if reverseReplication {
		if err := wr.startReverseReplication(ctx, sourceShards); err != nil {
			return err
		}
		// We also have to remove the frozen flag as final step.
		if err := wr.updateFrozenFlag(ctx, sourceShards, false); err != nil {
			return err
		}
	}

	event.DispatchUpdate(ev, "finished")
	return nil
}
1163680
func MigrateAddModelPermissions(pool *StatePool) error {
	st := pool.SystemState()
	controllerInfo, err := st.ControllerInfo()
	if err != nil {
		return errors.Trace(err)
	}
	coll, closer := st.db().GetRawCollection(permissionsC)
	defer closer()

	query := bson.M{
		"_id":    bson.M{"$regex": "^" + controllerKey(st.ControllerUUID()) + "#us#.*"},
		"access": "add-model",
	}
	iter := coll.Find(query).Iter()

	var doc struct {
		DocId            string `bson:"_id"`
		ObjectGlobalKey  string `bson:"object-global-key"`
		SubjectGlobalKey string `bson:"subject-global-key"`
		Access           string `bson:"access"`
	}
	var ops []txn.Op

	// Set all the existng controller add-model permissions back to login.
	// Create a new cloud permission for add-model.
	for iter.Next(&doc) {
		ops = append(ops, txn.Op{
			C:      permissionsC,
			Id:     doc.DocId,
			Assert: txn.DocExists,
			Update: bson.M{"$set": bson.M{"access": "login"}},
		})
		ops = append(ops,
			createPermissionOp(cloudGlobalKey(controllerInfo.CloudName), doc.SubjectGlobalKey, permission.AddModelAccess))
	}

	if err := iter.Close(); err != nil {
		return errors.Trace(err)
	}
	if len(ops) > 0 {
		return errors.Trace(st.runRawTransaction(ops))
	}
	return nil
}
1098297
func (s *CreateReplicationTaskInput) SetMigrationType(v string) *CreateReplicationTaskInput {
	s.MigrationType = &v
	return s
}
1096823
func (s *ModifyReplicationTaskInput) SetMigrationType(v string) *ModifyReplicationTaskInput {
	s.MigrationType = &v
	return s
}
843829
func (op *CaasOperatorAgent) validateMigration(apiCaller base.APICaller) error {
	// TODO(wallyworld) - more extensive checks to come.
	facade := apicaasoperator.NewClient(apiCaller)
	_, err := facade.Life(op.ApplicationName)
	if err != nil {
		return errors.Trace(err)
	}
	model, err := facade.Model()
	if err != nil {
		return errors.Trace(err)
	}
	curModelUUID := op.CurrentConfig().Model().Id()
	newModelUUID := model.UUID
	if newModelUUID != curModelUUID {
		return errors.Errorf("model mismatch when validating: got %q, expected %q",
			newModelUUID, curModelUUID)
	}
	return nil
}
957592
func RegisterOpenStorageMigrateHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
	return RegisterOpenStorageMigrateHandlerClient(ctx, mux, NewOpenStorageMigrateClient(conn))
}
742952
func (s *VolumeService) NewMigrateVolumeParams(storageid string, volumeid string) *MigrateVolumeParams {
	p := &MigrateVolumeParams{}
	p.p = make(map[string]interface{})
	p.p["storageid"] = storageid
	p.p["volumeid"] = volumeid
	return p
}
305570
func (md *RootMetadataV3) ClearForV4Migration() {
	md.WriterMetadata.WKeyBundleID = TLFWriterKeyBundleID{}
	md.RKeyBundleID = TLFReaderKeyBundleID{}
}
1237608
func (d *Domain) MigrateSetMaxSpeed(speed uint64, flags DomainMigrateMaxSpeedFlags) error {
	var err C.virError
	ret := C.virDomainMigrateSetMaxSpeedWrapper(d.ptr, C.ulong(speed), C.uint(flags), &err)
	if ret == -1 {
		return makeError(&err)
	}

	return nil
}
159990
func (f *Field) ServiceType(m *Model) *Type {
	return m.TypeWithTypeName(f.NativeType)
}
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
}
669342
func NewMigrationContext(ctx context.Context) context.Context {
	req := &http.Request{Host: "localhost"}
	params := url.Values{}
	ctx = goa.NewContext(ctx, nil, req, params)
	// set a random request ID for the context
	var reqID string
	ctx, reqID = client.ContextWithRequestID(ctx)

	log.Debug(ctx, nil, "Initialized the migration context with Request ID: %v", reqID)

	return ctx
}
796230
func (v delegatingStrategy) MergeType(diff apply.TypeElement) (apply.Result, error) {
	switch diff.GetFieldMergeType() {
	case apply.MergeStrategy:
		return v.merge.MergeType(diff)
	case apply.ReplaceStrategy:
		return v.replace.MergeType(diff)
	case apply.RetainKeysStrategy:
		return v.retainKeys.MergeType(diff)
	default:
		return v.merge.MergeType(diff)
	}
}
952820
func (s FieldSort) UnmappedType(typ string) FieldSort {
	s.unmappedType = &typ
	return s
}
224740
func (wr *Wrangler) replicaMigrateServedFrom(ctx context.Context, ki *topo.KeyspaceInfo, sourceShard *topo.ShardInfo, destinationShard *topo.ShardInfo, servedType topodatapb.TabletType, cells []string, reverse bool, tables []string, ev *events.MigrateServedFrom) error {
	// Save the destination keyspace (its ServedFrom has been changed)
	event.DispatchUpdate(ev, "updating keyspace")
	if err := wr.ts.UpdateKeyspace(ctx, ki); err != nil {
		return err
	}

	// Save the source shard (its blacklisted tables field has changed)
	event.DispatchUpdate(ev, "updating source shard")
	if _, err := wr.ts.UpdateShardFields(ctx, sourceShard.Keyspace(), sourceShard.ShardName(), func(si *topo.ShardInfo) error {
		return si.UpdateSourceBlacklistedTables(ctx, servedType, cells, reverse, tables)
	}); err != nil {
		return err
	}

	// Now refresh the source servers so they reload their
	// blacklisted table list
	event.DispatchUpdate(ev, "refreshing sources tablets state so they update their blacklisted tables")
	return wr.RefreshTabletsByShard(ctx, sourceShard, []topodatapb.TabletType{servedType}, cells)
}
679898
func (v retainKeysStrategy) MergeType(e apply.TypeElement) (apply.Result, error) {
	// No merge logic if adding or deleting a field
	if result, done := v.merge.doAddOrDelete(&e); done {
		return result, nil
	}

	elem := map[string]apply.Element{}
	for key := range e.GetLocalMap() {
		elem[key] = e.GetValues()[key]
	}
	return v.merge.doMergeMap(elem)
}
1053543
func NewTfaRemoveSecurityKeyType(Description string) *TfaRemoveSecurityKeyType {
	s := new(TfaRemoveSecurityKeyType)
	s.Description = Description
	return s
}