// computeChanges computes the changes that need to be made to the KVMs in the database.
545034
func (t *KVMsTable) computeChanges(c context.Context, datacenters []*config.Datacenter) error {
	cfgs := make(map[string]*KVM, len(datacenters))
	for _, dc := range datacenters {
		for _, cfg := range dc.Kvm {
			ipv4, err := common.ParseIPv4(cfg.Ipv4)
			if err != nil {
				return errors.Reason("failed to determine IP address for KVM %q: invalid IPv4 address %q", cfg.Name, cfg.Ipv4).Err()
			}
			mac48, err := common.ParseMAC48(cfg.MacAddress)
			if err != nil {
				return errors.Reason("failed to determine MAC address for KVM %q: invalid MAC-48 address %q", cfg.Name, cfg.MacAddress).Err()
			}
			pId, ok := t.platforms[cfg.Platform]
			if !ok {
				return errors.Reason("failed to determine platform ID for KVM %q: platform %q does not exist", cfg.Name, cfg.Platform).Err()
			}
			rId, ok := t.racks[cfg.Rack]
			if !ok {
				return errors.Reason("failed to determine rack ID for KVM %q: rack %q does not exist", cfg.Name, cfg.Rack).Err()
			}
			cfgs[cfg.Name] = &KVM{
				KVM: config.KVM{
					Name:        cfg.Name,
					Description: cfg.Description,
					State:       cfg.State,
				},
				IPv4:       ipv4,
				MacAddress: mac48,
				PlatformId: pId,
				RackId:     rId,
			}
		}
	}

	for _, kvm := range t.current {
		if cfg, ok := cfgs[kvm.Name]; ok {
			// KVM found in the config.
			if t.needsUpdate(kvm, cfg) {
				// KVM doesn't match the config.
				cfg.Id = kvm.Id
				t.updates = append(t.updates, cfg)
			}
			// Record that the KVM config has been seen.
			delete(cfgs, cfg.Name)
		} else {
			// KVM not found in the config.
			t.removals = append(t.removals, kvm)
		}
	}

	// KVMs remaining in the map are present in the config but not the database.
	// Iterate deterministically over the slices to determine which KVMs need to be added.
	for _, dc := range datacenters {
		for _, cfg := range dc.Kvm {
			if kvm, ok := cfgs[cfg.Name]; ok {
				t.additions = append(t.additions, kvm)
			}
		}
	}
	return nil
}
307870
func HashChange(listener func(*vecty.Event)) *vecty.EventListener {
	return &vecty.EventListener{Name: "hashchange", Listener: listener}
}
1172172
func EnsureSwitches(c context.Context, cfgs []*config.Datacenter, rackIds map[string]int64) error {
	t := &SwitchesTable{}
	t.racks = rackIds
	if err := t.fetch(c); err != nil {
		return errors.Annotate(err, "failed to fetch switches").Err()
	}
	if err := t.computeChanges(c, cfgs); err != nil {
		return errors.Annotate(err, "failed to compute changes").Err()
	}
	if err := t.add(c); err != nil {
		return errors.Annotate(err, "failed to add switches").Err()
	}
	if err := t.remove(c); err != nil {
		return errors.Annotate(err, "failed to remove switches").Err()
	}
	if err := t.update(c); err != nil {
		return errors.Annotate(err, "failed to update switches").Err()
	}
	return nil
}
1337223
func (p *ProvisionerAPI) HostChangesForContainers(args params.Entities) (params.HostNetworkChangeResults, error) {
	ctx := &hostChangesContext{
		result: params.HostNetworkChangeResults{
			Results: make([]params.HostNetworkChange, len(args.Entities)),
		},
	}
	if err := p.processEachContainer(args, ctx); err != nil {
		return ctx.result, errors.Trace(err)
	}
	return ctx.result, nil
}
1008604
func (ic *IngressIPController) processChange(change *serviceChange) error {
	service := ic.getCachedService(change.key)

	ic.clearOldAllocation(service, change.oldService)

	if service == nil {
		// Service was deleted - no further processing required
		return nil
	}

	typeLoadBalancer := service.Spec.Type == v1.ServiceTypeLoadBalancer
	hasAllocation := len(service.Status.LoadBalancer.Ingress) > 0
	switch {
	case typeLoadBalancer && hasAllocation:
		return ic.recordAllocation(service, change.key)
	case typeLoadBalancer && !hasAllocation:
		return ic.allocate(service, change.key)
	case !typeLoadBalancer && hasAllocation:
		return ic.deallocate(service, change.key)
	default:
		return nil
	}
}
996570
func (n *Node) handleChanges(changes []Change) {
	n.disseminator.AdjustMaxPropagations()
	for _, change := range changes {
		n.disseminator.RecordChange(change)

		switch change.Status {
		case Alive:
			n.stateTransitions.Cancel(change)

		case Suspect:
			n.stateTransitions.ScheduleSuspectToFaulty(change)

		case Faulty:
			n.stateTransitions.ScheduleFaultyToTombstone(change)

		case Leave:
			// XXX: should this also reap?
			n.stateTransitions.Cancel(change)

		case Tombstone:
			n.stateTransitions.ScheduleTombstoneToEvict(change)
		}
	}
}
1134319
func (s *HTTPServer) syncChanges() {
	if err := s.agent.State.SyncChanges(); err != nil {
		s.agent.logger.Printf("[ERR] agent: failed to sync changes: %v", err)
	}
}
661786
func (s *DataMsgServiceServer) DataChanges(stream msg.DataMsgService_DataChangesServer) error {
	for {
		chng, err := stream.Recv()

		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}

		for _, sub := range s.adapter.base.Subscriptions() {
			for _, keyPrefix := range sub.KeyPrefixes {
				if strings.HasPrefix(chng.Key, keyPrefix) {
					sub.ChangeChan <- msg.NewChangeWatchResp(context.Background(), chng, func(err2 error) {
						err = stream.Send(&msg.DataChangeReply{Key: chng.Key, OperationType: chng.OperationType,
							Result: 0 /*TODO VPP Result*/})
						if err != nil {
							logrus.DefaultLogger().Error(err) //Not able to propagate it somewhere else
						}
					})
				}
			}
		}
	}
}
856864
func (f *Folder) BatchChanges(
	ctx context.Context, changes []libkbfs.NodeChange, _ []libkbfs.NodeID) {
	if !f.fs.conn.Protocol().HasInvalidate() {
		// OSXFUSE 2.x does not support notifications
		return
	}
	if origin, ok := ctx.Value(libfs.CtxAppIDKey).(*FS); ok && origin == f.fs {
		return
	}
	if v := ctx.Value(libkbfs.CtxBackgroundSyncKey); v != nil {
		return
	}

	// Handle in the background because we shouldn't lock during the
	// notification.
	f.fs.queueNotification(func() { f.batchChangesInvalidate(ctx, changes) })
}
1190568
func (s *Settings) applyChanges(changes settings.ItemChanges) {
	for _, ch := range changes {
		switch {
		case ch.IsAddition(), ch.IsModification():
			s.Set(ch.Key, ch.NewValue)
		case ch.IsDeletion():
			s.Delete(ch.Key)
		}
	}
}
997776
func (r *HashRing) ProcessMembershipChanges(changes []membership.MemberChange) {
	r.Lock()
	changed := false
	var added, updated, removed []string
	for _, change := range changes {
		if change.Before == nil && change.After != nil {
			// new member
			if r.addMemberNoLock(change.After) {
				added = append(added, change.After.GetAddress())
				changed = true
			}
		} else if change.Before != nil && change.After == nil {
			// remove member
			if r.removeMemberNoLock(change.Before) {
				removed = append(removed, change.Before.GetAddress())
				changed = true
			}
		} else {
			if change.Before.Identity() != change.After.Identity() {
				// identity has changed, member needs to be removed and readded
				r.removeMemberNoLock(change.Before)
				r.addMemberNoLock(change.After)
				updated = append(updated, change.After.GetAddress())
				changed = true
			}
		}
	}

	// recompute checksums on changes
	if changed {
		r.computeChecksumsNoLock()
		r.EmitEvent(events.RingChangedEvent{
			ServersAdded:   added,
			ServersUpdated: updated,
			ServersRemoved: removed,
		})
	}

	r.Unlock()
}
1320769
func (_ *AttachISO) CheckChanges(a, e, changes *AttachISO) error {
	glog.Info("AttachISO.CheckChanges invoked!")
	return nil
}
400935
func (rdb RethinkDB) GetChanges(changeID string, pageSize int, filterName string) ([]Change, error) {
	var (
		lower, upper, bound []interface{}
		idx                 = "rdb_created_at_id"
		max                 = []interface{}{gorethink.Now().Sub(blackoutTime), gorethink.MaxVal}
		min                 = []interface{}{gorethink.MinVal, gorethink.MinVal}
		order               gorethink.OrderByOpts
		reversed            bool
	)
	if filterName != "" {
		idx = "rdb_gun_created_at_id"
		max = append([]interface{}{filterName}, max...)
		min = append([]interface{}{filterName}, min...)
	}

	switch changeID {
	case "0", "-1":
		lower = min
		upper = max
	default:
		bound, idx = rdb.bound(changeID, filterName)
		if pageSize < 0 {
			lower = min
			upper = bound
		} else {
			lower = bound
			upper = max
		}
	}

	if changeID == "-1" || pageSize < 0 {
		reversed = true
		order = gorethink.OrderByOpts{Index: gorethink.Desc(idx)}
	} else {
		order = gorethink.OrderByOpts{Index: gorethink.Asc(idx)}
	}

	if pageSize < 0 {
		pageSize = pageSize * -1
	}

	changes := make([]Change, 0, pageSize)

	// Between returns a slice of results from the rethinkdb table.
	// The results are ordered using BetweenOpts.Index, which will
	// default to the index of the immediately preceding OrderBy.
	// The lower and upper are the start and end points for the slice
	// and the Left/RightBound values determine whether the lower and
	// upper values are included in the result per normal set semantics
	// of "open" and "closed"
	res, err := gorethink.DB(rdb.dbName).
		Table(Change{}.TableName(), gorethink.TableOpts{ReadMode: "majority"}).
		OrderBy(order).
		Between(
			lower,
			upper,
			gorethink.BetweenOpts{
				LeftBound:  "open",
				RightBound: "open",
			},
		).Limit(pageSize).Run(rdb.sess)
	if err != nil {
		return nil, err
	}
	defer res.Close()

	defer func() {
		if reversed {
			// results are currently newest to oldest, should be oldest to newest
			for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 {
				changes[i], changes[j] = changes[j], changes[i]
			}
		}
	}()

	return changes, res.All(&changes)
}
651787
func OverlayChanges(layers []string, rw string) ([]Change, error) {
	return changes(layers, rw, overlayDeletedFile, nil)
}
228356
func PgLogicalSlotPeekChanges(db XODB, v0 pgtypes.Name, v1 pgtypes.PgLsn, v2 int, v3 StringSlice) ([]pgtypes.Record, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.pg_logical_slot_peek_changes($1, $2, $3, $4)`

	// run query
	var ret []pgtypes.Record
	XOLog(sqlstr, v0, v1, v2, v3)
	err = db.QueryRow(sqlstr, v0, v1, v2, v3).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
112395
func (api *CrossModelRelationsAPI) PublishRelationChanges(
	changes params.RemoteRelationsChanges,
) (params.ErrorResults, error) {
	results := params.ErrorResults{
		Results: make([]params.ErrorResult, len(changes.Changes)),
	}
	for i, change := range changes.Changes {
		relationTag, err := api.st.GetRemoteEntity(change.RelationToken)
		if err != nil {
			if errors.IsNotFound(err) {
				logger.Debugf("no relation tag %+v in model %v, exit early", change.RelationToken, api.st.ModelUUID())
				continue
			}
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		logger.Debugf("relation tag for token %+v is %v", change.RelationToken, relationTag)
		if err := api.checkMacaroonsForRelation(relationTag, change.Macaroons); err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		if err := commoncrossmodel.PublishRelationChange(api.st, relationTag, change); err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		if change.Life != params.Alive {
			delete(api.relationToOffer, relationTag.Id())
		}
	}
	return results, nil
}
286675
func (_ *ElasticIP) CheckChanges(a, e, changes *ElasticIP) error {
	// This is a new EIP
	if a == nil {
		// No logic for EIPs - they are just created
	}

	// This is an existing EIP
	// We should never be changing this
	if a != nil {
		if changes.PublicIP != nil {
			return fi.CannotChangeField("PublicIP")
		}
		if changes.TagOnSubnet != nil {
			return fi.CannotChangeField("TagOnSubnet")
		}
		if changes.ID != nil {
			return fi.CannotChangeField("ID")
		}
	}
	return nil
}