// sendGroupUpdate
164360
func sendGroupUpdate() error {
	log.Debugf("Sending group SyncMessage")

	var buf bytes.Buffer

	for _, g := range groups {
		gd := &textsecure.GroupDetails{
			Id:      g.ID,
			Name:    &g.Name,
			Members: g.Members,
			// XXX add support for avatar
			// XXX add support for active?
		}

		b, err := proto.Marshal(gd)
		if err != nil {
			log.Errorf("Failed to marshal group details")
			continue
		}

		buf.Write(varint32(len(b)))
		buf.Write(b)
	}

	a, err := uploadAttachment(&buf, "application/octet-stream")
	if err != nil {
		return err
	}

	sm := &textsecure.SyncMessage{
		Groups: &textsecure.SyncMessage_Groups{
			Blob: &textsecure.AttachmentPointer{
				Id:          &a.id,
				ContentType: &a.ct,
				Key:         a.keys,
			},
		},
	}

	_, err = sendSyncMessage(sm)
	return err
}
636859
func (ac *APIController) GlobalUpdate(global, params *contivModel.Global) error {
	log.Infof("Received GlobalUpdate: %+v. Old: %+v", params, global)

	// Get the state driver
	stateDriver, err := utils.GetStateDriver()
	if err != nil {
		return err
	}

	gCfg := &gstate.Cfg{}
	gCfg.StateDriver = stateDriver
	numVlans, _ := gCfg.GetVlansInUse()
	numVxlans, _ := gCfg.GetVxlansInUse()

	// Build global config
	globalCfg := intent.ConfigGlobal{}

	// Generate helpful error message when networks exist
	errExistingNetworks := func(optionLabel string) error {
		msgs := []string{}
		if numVlans > 0 {
			msgs = append(msgs, fmt.Sprintf("%d vlans", numVlans))
		}
		if numVxlans > 0 {
			msgs = append(msgs, fmt.Sprintf("%d vxlans", numVxlans))
		}
		msg := fmt.Sprintf("Unable to update %s due to existing %s",
			optionLabel, strings.Join(msgs, " and "))
		log.Errorf(msg)
		return fmt.Errorf(msg)
	}

	//check for change in forwarding mode
	if global.FwdMode != params.FwdMode {
		//check if there exists any non default network and tenants
		if numVlans+numVxlans > 0 {
			return errExistingNetworks("forwarding mode")
		}
		if global.FwdMode == "routing" {
			//check if any bgp configurations exists.
			bgpCfgs := &mastercfg.CfgBgpState{}
			bgpCfgs.StateDriver = stateDriver
			cfgs, _ := bgpCfgs.ReadAll()
			if len(cfgs) != 0 {
				log.Errorf("Unable to change the forwarding mode due to existing bgp configs")
				return fmt.Errorf("please delete existing Bgp configs")
			}
		}
		globalCfg.FwdMode = params.FwdMode
	}
	if global.ArpMode != params.ArpMode {
		globalCfg.ArpMode = params.ArpMode
	}
	if global.Vlans != params.Vlans {
		globalCfg.VLANs = params.Vlans
	}
	if global.Vxlans != params.Vxlans {
		globalCfg.VXLANs = params.Vxlans
	}
	if global.NetworkInfraType != params.NetworkInfraType {
		globalCfg.NwInfraType = params.NetworkInfraType
	}
	if global.PvtSubnet != params.PvtSubnet {
		if (global.PvtSubnet != "" || params.PvtSubnet != defaultHostPvtNet) && numVlans+numVxlans > 0 {
			return errExistingNetworks("private subnet")
		}
		globalCfg.PvtSubnet = params.PvtSubnet
	}

	// Create the object
	err = master.UpdateGlobal(stateDriver, &globalCfg)
	if err != nil {
		log.Errorf("Error creating global config {%+v}. Err: %v", global, err)
		return err
	}

	global.NetworkInfraType = params.NetworkInfraType
	global.Vlans = params.Vlans
	global.Vxlans = params.Vxlans
	global.FwdMode = params.FwdMode
	global.ArpMode = params.ArpMode
	global.PvtSubnet = params.PvtSubnet

	return nil
}
613564
func (api *Client) UpdateUserGroup(userGroup UserGroup) (UserGroup, error) {
	return api.UpdateUserGroupContext(context.Background(), userGroup)
}
638891
func (s *VMGroupService) UpdateInstanceGroup(p *UpdateInstanceGroupParams) (*UpdateInstanceGroupResponse, error) {
	resp, err := s.cs.newRequest("updateInstanceGroup", p.toURLValues())
	if err != nil {
		return nil, err
	}

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

	return &r, nil
}
1212928
func (r *GroupService) Update(appId string, id string, group *Group) *GroupUpdateCall {
	c := &GroupUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
	c.appId = appId
	c.id = id
	c.group = group
	return c
}
1173155
func (c *Conn) sendPropertiesUpdate(unitPath dbus.ObjectPath, changedProps map[string]dbus.Variant) {
	c.propertiesSubscriber.Lock()
	defer c.propertiesSubscriber.Unlock()

	if c.propertiesSubscriber.updateCh == nil {
		return
	}

	update := &PropertiesUpdate{unitName(unitPath), changedProps}

	select {
	case c.propertiesSubscriber.updateCh <- update:
	default:
		msg := "update channel is full"
		select {
		case c.propertiesSubscriber.errCh <- errors.New(msg):
		default:
			log.Printf("full error channel while reporting: %s\n", msg)
		}
		return
	}
}
610553
func (cli *OpsGenieHeartbeatClient) Update(req heartbeat.UpdateHeartbeatRequest) (*heartbeat.UpdateHeartbeatResponse, error) {
	var response heartbeat.HeartbeatMetaResponseV2
	err := cli.sendPatchRequest(&req, &response)

	if err != nil {
		return nil, err
	}

	return convertUpdateToV1Response(&response), nil
}
632533
func (s *Stream) sendWindowUpdate() error {
	s.controlHdrLock.Lock()
	defer s.controlHdrLock.Unlock()

	// Determine the delta update
	max := s.session.config.MaxStreamWindowSize
	var bufLen uint32
	s.recvLock.Lock()
	if s.recvBuf != nil {
		bufLen = uint32(s.recvBuf.Len())
	}
	delta := (max - bufLen) - s.recvWindow

	// Determine the flags if any
	flags := s.sendFlags()

	// Check if we can omit the update
	if delta < (max/2) && flags == 0 {
		s.recvLock.Unlock()
		return nil
	}

	// Update our window
	s.recvWindow += delta
	s.recvLock.Unlock()

	// Send the header
	s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta)
	if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
		return err
	}
	return nil
}
985068
func (cli *Client) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error {
	query := url.Values{}
	query.Set("version", strconv.FormatUint(version.Index, 10))
	resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, node, nil)
	ensureReaderClosed(resp)
	return err
}
294669
func (c *RollingUpdateCluster) RollingUpdate(groups map[string]*cloudinstances.CloudInstanceGroup, cluster *api.Cluster, instanceGroups *api.InstanceGroupList) error {
	if len(groups) == 0 {
		glog.Info("Cloud Instance Group length is zero. Not doing a rolling-update.")
		return nil
	}

	var resultsMutex sync.Mutex
	results := make(map[string]error)

	masterGroups := make(map[string]*cloudinstances.CloudInstanceGroup)
	nodeGroups := make(map[string]*cloudinstances.CloudInstanceGroup)
	bastionGroups := make(map[string]*cloudinstances.CloudInstanceGroup)
	for k, group := range groups {
		switch group.InstanceGroup.Spec.Role {
		case api.InstanceGroupRoleNode:
			nodeGroups[k] = group
		case api.InstanceGroupRoleMaster:
			masterGroups[k] = group
		case api.InstanceGroupRoleBastion:
			bastionGroups[k] = group
		default:
			return fmt.Errorf("unknown group type for group %q", group.InstanceGroup.ObjectMeta.Name)
		}
	}

	// Upgrade bastions first; if these go down we can't see anything
	{
		var wg sync.WaitGroup

		for k, bastionGroup := range bastionGroups {
			wg.Add(1)
			go func(k string, group *cloudinstances.CloudInstanceGroup) {
				resultsMutex.Lock()
				results[k] = fmt.Errorf("function panic bastions")
				resultsMutex.Unlock()

				defer wg.Done()

				g, err := NewRollingUpdateInstanceGroup(c.Cloud, group)
				if err == nil {
					err = g.RollingUpdate(c, cluster, instanceGroups, true, c.BastionInterval, c.ValidationTimeout)
				}

				resultsMutex.Lock()
				results[k] = err
				resultsMutex.Unlock()
			}(k, bastionGroup)
		}

		wg.Wait()
	}

	// Do not continue update if bastion(s) failed
	for _, err := range results {
		if err != nil {
			return fmt.Errorf("bastion not healthy after update, stopping rolling-update: %q", err)
		}
	}

	// Upgrade masters next
	{
		// We run master nodes in series, even if they are in separate instance groups
		// typically they will be in separate instance groups, so we can force the zones,
		// and we don't want to roll all the masters at the same time.  See issue #284

		for _, group := range masterGroups {
			g, err := NewRollingUpdateInstanceGroup(c.Cloud, group)
			if err == nil {
				err = g.RollingUpdate(c, cluster, instanceGroups, false, c.MasterInterval, c.ValidationTimeout)
			}

			// Do not continue update if master(s) failed, cluster is potentially in an unhealthy state
			if err != nil {
				return fmt.Errorf("master not healthy after update, stopping rolling-update: %q", err)
			}
		}
	}

	// Upgrade nodes, with greater parallelism
	{
		var wg sync.WaitGroup

		// We run nodes in series, even if they are in separate instance groups
		// typically they will not being separate instance groups. If you roll the nodes in parallel
		// you can get into a scenario where you can evict multiple statefulset pods from the same
		// statefulset at the same time. Further improvements needs to be made to protect from this as
		// well.

		wg.Add(1)

		go func() {
			for k := range nodeGroups {
				resultsMutex.Lock()
				results[k] = fmt.Errorf("function panic nodes")
				resultsMutex.Unlock()
			}

			defer wg.Done()

			for k, group := range nodeGroups {
				g, err := NewRollingUpdateInstanceGroup(c.Cloud, group)
				if err == nil {
					err = g.RollingUpdate(c, cluster, instanceGroups, false, c.NodeInterval, c.ValidationTimeout)
				}

				resultsMutex.Lock()
				results[k] = err
				resultsMutex.Unlock()

				// TODO: Bail on error?
			}
		}()

		wg.Wait()
	}

	for _, err := range results {
		if err != nil {
			return err
		}
	}

	glog.Infof("Rolling update completed for cluster %q!", c.ClusterName)
	return nil
}
962043
func (r *RollingUpdateInstanceGroup) RollingUpdate(rollingUpdateData *RollingUpdateCluster, cluster *api.Cluster, instanceGroupList *api.InstanceGroupList, isBastion bool, sleepAfterTerminate time.Duration, validationTimeout time.Duration) (err error) {

	// we should not get here, but hey I am going to check.
	if rollingUpdateData == nil {
		return fmt.Errorf("rollingUpdate cannot be nil")
	}

	// Do not need a k8s client if you are doing cloudonly.
	if rollingUpdateData.K8sClient == nil && !rollingUpdateData.CloudOnly {
		return fmt.Errorf("rollingUpdate is missing a k8s client")
	}

	if instanceGroupList == nil {
		return fmt.Errorf("rollingUpdate is missing the InstanceGroupList")
	}

	update := r.CloudGroup.NeedUpdate
	if rollingUpdateData.Force {
		update = append(update, r.CloudGroup.Ready...)
	}

	if len(update) == 0 {
		return nil
	}

	if isBastion {
		glog.V(3).Info("Not validating the cluster as instance is a bastion.")
	} else if rollingUpdateData.CloudOnly {
		glog.V(3).Info("Not validating cluster as validation is turned off via the cloud-only flag.")
	} else if featureflag.DrainAndValidateRollingUpdate.Enabled() {
		if err = r.ValidateCluster(rollingUpdateData, cluster, instanceGroupList); err != nil {
			if rollingUpdateData.FailOnValidate {
				return fmt.Errorf("error validating cluster: %v", err)
			} else {
				glog.V(2).Infof("Ignoring cluster validation error: %v", err)
				glog.Info("Cluster validation failed, but proceeding since fail-on-validate-error is set to false")
			}
		}
	}

	for _, u := range update {
		instanceId := u.ID

		nodeName := ""
		if u.Node != nil {
			nodeName = u.Node.Name
		}

		if isBastion {
			// We don't want to validate for bastions - they aren't part of the cluster
		} else if rollingUpdateData.CloudOnly {

			glog.Warning("Not draining cluster nodes as 'cloudonly' flag is set.")

		} else if featureflag.DrainAndValidateRollingUpdate.Enabled() {

			if u.Node != nil {
				glog.Infof("Draining the node: %q.", nodeName)

				if err = r.DrainNode(u, rollingUpdateData); err != nil {
					if rollingUpdateData.FailOnDrainError {
						return fmt.Errorf("failed to drain node %q: %v", nodeName, err)
					} else {
						glog.Infof("Ignoring error draining node %q: %v", nodeName, err)
					}
				}
			} else {
				glog.Warningf("Skipping drain of instance %q, because it is not registered in kubernetes", instanceId)
			}
		}

		// We unregister the node before deleting it; if the replacement comes up with the same name it would otherwise still be cordoned
		// (It often seems like GCE tries to re-use names)
		if !isBastion && !rollingUpdateData.CloudOnly {
			if u.Node == nil {
				glog.Warningf("no kubernetes Node associated with %s, skipping node deletion", instanceId)
			} else {
				glog.Infof("deleting node %q from kubernetes", nodeName)
				if err := r.deleteNode(u.Node, rollingUpdateData); err != nil {
					return fmt.Errorf("error deleting node %q: %v", nodeName, err)
				}
			}
		}

		if err = r.DeleteInstance(u); err != nil {
			glog.Errorf("error deleting instance %q, node %q: %v", instanceId, nodeName, err)
			return err
		}

		// Wait for the minimum interval
		glog.Infof("waiting for %v after terminating instance", sleepAfterTerminate)
		time.Sleep(sleepAfterTerminate)

		if isBastion {
			glog.Infof("Deleted a bastion instance, %s, and continuing with rolling-update.", instanceId)

			continue
		} else if rollingUpdateData.CloudOnly {
			glog.Warningf("Not validating cluster as cloudonly flag is set.")

		} else if featureflag.DrainAndValidateRollingUpdate.Enabled() {
			glog.Info("Validating the cluster.")

			if err = r.ValidateClusterWithDuration(rollingUpdateData, cluster, instanceGroupList, validationTimeout); err != nil {

				if rollingUpdateData.FailOnValidate {
					glog.Errorf("Cluster did not validate within %s", validationTimeout)
					return fmt.Errorf("error validating cluster after removing a node: %v", err)
				}

				glog.Warningf("Cluster validation failed after removing instance, proceeding since fail-on-validate is set to false: %v", err)
			}
		}

		if rollingUpdateData.Interactive {
			stopPrompting, err := promptInteractive(u.ID, nodeName)
			if err != nil {
				return err
			}
			if stopPrompting {
				// Is a pointer to a struct, changes here push back into the original
				rollingUpdateData.Interactive = false
			}
		}
	}

	return nil
}
865176
func (g *OrganizationService) OrganizationUpdate(uri *Hyperlink,
	input OrganizationParams, URLParams M) (organization Organization,
	result *Result) {
	if uri == nil {
		uri = &OrganizationURL
	}
	url, err := uri.Expand(URLParams)
	if err != nil {
		return Organization{}, &Result{Err: err}
	}
	result = g.client.patch(url, input, &organization)
	return
}
638566
func (r *GroupService) Patch(appId string, id string, group *Group) *GroupPatchCall {
	c := &GroupPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
	c.appId = appId
	c.id = id
	c.group = group
	return c
}
237296
func (mr *MockCommonAPIClientMockRecorder) SwarmUpdate(ctx, version, swarm, flags interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwarmUpdate", reflect.TypeOf((*MockCommonAPIClient)(nil).SwarmUpdate), ctx, version, swarm, flags)
}
579867
func SendGroupAttachment(hexid string, msg string, r io.Reader) (uint64, error) {
	ct, r := MIMETypeFromReader(r)
	a, err := uploadAttachment(r, ct)
	if err != nil {
		return 0, err
	}
	return sendGroupHelper(hexid, msg, a)
}
509414
func (s *Service) FormationUpdate(ctx context.Context, appIdentity string, formationIdentity string, o FormationUpdateOpts) (*Formation, error) {
	var formation Formation
	return &formation, s.Patch(ctx, &formation, fmt.Sprintf("/apps/%v/formation/%v", appIdentity, formationIdentity), o)
}
646618
func (d *Deployments) PromoteGroups(deploymentID string, groups []string, q *WriteOptions) (*DeploymentUpdateResponse, *WriteMeta, error) {
	var resp DeploymentUpdateResponse
	req := &DeploymentPromoteRequest{
		DeploymentID: deploymentID,
		Groups:       groups,
	}
	wm, err := d.client.write("/v1/deployment/promote/"+deploymentID, req, &resp, q)
	if err != nil {
		return nil, nil, err
	}
	return &resp, wm, nil
}