// StartFSMWorkflowInput should be used to construct the input for any StartWorkflowExecutionRequests.
// This panics on errors cause really this should never err.
334255
func StartFSMWorkflowInput(serializer Serialization, data interface{}) *string {
	ss := new(SerializedState)
	stateData := serializer.Serialize(data)
	ss.StateData = stateData
	serialized := serializer.Serialize(ss)
	return aws.String(serialized)
}
1127528
func TerminateWorkflow(wfClient v1alpha1.WorkflowInterface, name string) error {
	patchObj := map[string]interface{}{
		"spec": map[string]interface{}{
			"activeDeadlineSeconds": 0,
		},
	}
	var err error
	patch, err := json.Marshal(patchObj)
	if err != nil {
		return errors.InternalWrapError(err)
	}
	for attempt := 0; attempt < 10; attempt++ {
		_, err = wfClient.Patch(name, types.MergePatchType, patch)
		if err != nil {
			if !apierr.IsConflict(err) {
				return err
			}
		} else {
			break
		}
		time.Sleep(100 * time.Millisecond)
	}
	return err
}
886691
func IsWorkflowSuspended(wf *wfv1.Workflow) bool {
	if wf.Spec.Suspend != nil && *wf.Spec.Suspend {
		return true
	}
	for _, node := range wf.Status.Nodes {
		if node.Type == wfv1.NodeTypeSuspend && node.Phase == wfv1.NodeRunning {
			return true
		}
	}
	return false
}
893458
func (fw *Firewaller) startMachine(tag names.MachineTag) error {
	machined := &machineData{
		fw:           fw,
		tag:          tag,
		unitds:       make(map[names.UnitTag]*unitData),
		ingressRules: make([]network.IngressRule, 0),
		definedPorts: make(map[names.UnitTag]portRanges),
	}
	m, err := machined.machine()
	if params.IsCodeNotFound(err) {
		logger.Debugf("not watching %q", tag)
		return nil
	} else if err != nil {
		return errors.Annotate(err, "cannot watch machine units")
	}
	manual, err := m.IsManual()
	if err != nil {
		return errors.Trace(err)
	}
	if manual {
		// Don't track manual machines, we can't change their ports.
		logger.Debugf("not watching manual %q", tag)
		return nil
	}
	unitw, err := m.WatchUnits()
	if err != nil {
		return errors.Trace(err)
	}
	// XXX(fwereade): this is the best of a bunch of bad options. We've started
	// the watch, so we're responsible for it; but we (probably?) need to do this
	// little dance below to update the machined data on the fw loop goroutine,
	// whence it's usually accessed, before we start the machined watchLoop
	// below. That catacomb *should* be the only one responsible -- and it *is*
	// responsible -- but having it in the main fw catacomb as well does no harm,
	// and greatly simplifies the code below (which would otherwise have to
	// manage unitw lifetime and errors manually).
	if err := fw.catacomb.Add(unitw); err != nil {
		return errors.Trace(err)
	}
	select {
	case <-fw.catacomb.Dying():
		return fw.catacomb.ErrDying()
	case change, ok := <-unitw.Changes():
		if !ok {
			return errors.New("machine units watcher closed")
		}
		fw.machineds[tag] = machined
		err = fw.unitsChanged(&unitsChange{machined, change})
		if err != nil {
			delete(fw.machineds, tag)
			return errors.Annotatef(err, "cannot respond to units changes for %q", tag)
		}
	}

	err = catacomb.Invoke(catacomb.Plan{
		Site: &machined.catacomb,
		Work: func() error {
			return machined.watchLoop(unitw)
		},
	})
	if err != nil {
		delete(fw.machineds, tag)
		return errors.Trace(err)
	}

	// register the machined with the firewaller's catacomb.
	err = fw.catacomb.Add(machined)
	if err == nil {
		logger.Debugf("started watching %q", tag)
	}
	return err
}
47984
func (a *Client) PutWorkflows(params *PutWorkflowsParams, authInfo runtime.ClientAuthInfoWriter) (*PutWorkflowsOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewPutWorkflowsParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "PutWorkflows",
		Method:             "PUT",
		PathPattern:        "/workflows",
		ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &PutWorkflowsReader{formats: a.formats},
		AuthInfo:           authInfo,
	})
	if err != nil {
		return nil, err
	}
	return result.(*PutWorkflowsOK), nil
}
1104011
func (a *Client) PutWorkflowsTasks(params *PutWorkflowsTasksParams, authInfo runtime.ClientAuthInfoWriter) (*PutWorkflowsTasksOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewPutWorkflowsTasksParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "PutWorkflowsTasks",
		Method:             "PUT",
		PathPattern:        "/workflows/tasks",
		ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &PutWorkflowsTasksReader{formats: a.formats},
		AuthInfo:           authInfo,
	})
	if err != nil {
		return nil, err
	}
	return result.(*PutWorkflowsTasksOK), nil
}
1251343
func (s *HistoryEvent) SetWorkflowExecutionSignaledEventAttributes(v *WorkflowExecutionSignaledEventAttributes) *HistoryEvent {
	s.WorkflowExecutionSignaledEventAttributes = v
	return s
}
1271932
func CancelWorkflow(details *string) Decider {
	return func(ctx *FSMContext, h *swf.HistoryEvent, data interface{}) Outcome {
		Log.Printf("at=cancel-workflow workflowId=%s", LS(ctx.WorkflowId))
		return ctx.CancelWorkflow(data, details)
	}
}
982256
func RetryWorkflow(kubeClient kubernetes.Interface, wfClient v1alpha1.WorkflowInterface, wf *wfv1.Workflow) (*wfv1.Workflow, error) {
	switch wf.Status.Phase {
	case wfv1.NodeFailed, wfv1.NodeError:
	default:
		return nil, errors.Errorf(errors.CodeBadRequest, "workflow must be Failed/Error to retry")
	}
	newWF := wf.DeepCopy()
	podIf := kubeClient.CoreV1().Pods(wf.ObjectMeta.Namespace)

	// Delete/reset fields which indicate workflow completed
	delete(newWF.Labels, common.LabelKeyCompleted)
	newWF.ObjectMeta.Labels[common.LabelKeyPhase] = string(wfv1.NodeRunning)
	newWF.Status.Phase = wfv1.NodeRunning
	newWF.Status.Message = ""
	newWF.Status.FinishedAt = metav1.Time{}
	if newWF.Spec.ActiveDeadlineSeconds != nil && *newWF.Spec.ActiveDeadlineSeconds == 0 {
		// if it was terminated, unset the deadline
		newWF.Spec.ActiveDeadlineSeconds = nil
	}

	// Iterate the previous nodes. If it was successful Pod carry it forward
	newWF.Status.Nodes = make(map[string]wfv1.NodeStatus)
	onExitNodeName := wf.ObjectMeta.Name + ".onExit"
	for _, node := range wf.Status.Nodes {
		switch node.Phase {
		case wfv1.NodeSucceeded, wfv1.NodeSkipped:
			if !strings.HasPrefix(node.Name, onExitNodeName) {
				newWF.Status.Nodes[node.ID] = node
				continue
			}
		case wfv1.NodeError, wfv1.NodeFailed:
			// do not add this status to the node. pretend as if this node never existed.
		default:
			// Do not allow retry of workflows with pods in Running/Pending phase
			return nil, errors.InternalErrorf("Workflow cannot be retried with node %s in %s phase", node, node.Phase)
		}
		if node.Type == wfv1.NodeTypePod {
			log.Infof("Deleting pod: %s", node.ID)
			err := podIf.Delete(node.ID, &metav1.DeleteOptions{})
			if err != nil && !apierr.IsNotFound(err) {
				return nil, errors.InternalWrapError(err)
			}
		}
	}
	return wfClient.Update(newWF)
}
875357
func (a *Client) GetWorkflowsInstanceID(params *GetWorkflowsInstanceIDParams, authInfo runtime.ClientAuthInfoWriter) (*GetWorkflowsInstanceIDOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetWorkflowsInstanceIDParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "GetWorkflowsInstanceID",
		Method:             "GET",
		PathPattern:        "/workflows/{instanceId}",
		ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &GetWorkflowsInstanceIDReader{formats: a.formats},
		AuthInfo:           authInfo,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetWorkflowsInstanceIDOK), nil
}
240164
func (m *Manager) runningWorkflow(uuid string) (*runningWorkflow, error) {
	m.mu.Lock()
	defer m.mu.Unlock()

	rw, ok := m.workflows[uuid]
	if !ok {
		return nil, fmt.Errorf("no running workflow with uuid %v", uuid)
	}
	return rw, nil
}
441431
func startFunc(config ManifoldConfig) dependency.StartFunc {
	return func(context dependency.Context) (worker.Worker, error) {
		if config.Clock == nil {
			return nil, errors.NotValidf("missing Clock")
		}
		var agent agent.Agent
		if err := context.Get(config.AgentName, &agent); err != nil {
			return nil, err
		}
		var apiCaller base.APICaller
		if err := context.Get(config.APICallerName, &apiCaller); err != nil {
			return nil, err
		}
		return NewManifoldWorker(agent, apiCaller, config.Clock, config.LeadershipGuarantee)
	}
}
249777
func (a *Agent) startServiceInputs(
	ctx context.Context,
	dst chan<- telegraf.Metric,
) error {
	started := []telegraf.ServiceInput{}

	for _, input := range a.Config.Inputs {
		if si, ok := input.Input.(telegraf.ServiceInput); ok {
			// Service input plugins are not subject to timestamp rounding.
			// This only applies to the accumulator passed to Start(), the
			// Gather() accumulator does apply rounding according to the
			// precision agent setting.
			acc := NewAccumulator(input, dst)
			acc.SetPrecision(time.Nanosecond)

			err := si.Start(acc)
			if err != nil {
				log.Printf("E! [agent] Service for input %s failed to start: %v",
					input.Name(), err)

				for _, si := range started {
					si.Stop()
				}

				return err
			}

			started = append(started, si)
		}
	}

	return nil
}
1036738
func ExecuteStart(ctx context.Context, fw FirewallSSOInt, info map[string]string, timeout int) (bool, error) {
	ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS)

	if !fw.CheckStatus(ctx, info) {
		return false, nil
	}
	log.LoggerWContext(ctx).Info("Processing SSO Start")
	if !fw.MatchesRole(ctx, info) {
		log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for user device %s since it doesn't match the role", info["role"]))
		return false, nil
	}

	if !fw.MatchesNetwork(ctx, info) {
		log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"]))
		return false, nil
	}

	// We change the username with the way it is expected given the format of this firewall
	info["username"] = fw.FormatUsername(ctx, info)

	parentResult, err := fw.GetFirewallSSO(ctx).Start(ctx, info, timeout)

	if err != nil {
		return false, err
	}

	childResult, err := fw.Start(ctx, info, timeout)
	return parentResult && childResult, err
}
384905
func (config ManifoldConfig) startFunc() dependency.StartFunc {
	return func(context dependency.Context) (worker.Worker, error) {
		var agent agent.Agent
		if err := context.Get(config.AgentName, &agent); err != nil {
			return nil, err
		}

		conn, err := config.NewConnection(agent, config.APIOpen)
		if errors.Cause(err) == ErrChangedPassword {
			return nil, dependency.ErrBounce
		} else if err != nil {
			cfg := agent.CurrentConfig()
			return nil, errors.Annotatef(err, "[%s] %q cannot open api",
				shortModelUUID(cfg.Model()), cfg.Tag().String())
		}
		return newAPIConnWorker(conn), nil
	}
}
498114
func (f *FSMContext) CancelWorkflow(data interface{}, details *string) Outcome {
	d := &swf.Decision{
		DecisionType: S(swf.DecisionTypeCancelWorkflowExecution),
		CancelWorkflowExecutionDecisionAttributes: &swf.CancelWorkflowExecutionDecisionAttributes{
			Details: details,
		},
	}
	return Outcome{
		State:     CanceledState,
		Data:      data,
		Decisions: f.Decision(d),
	}
}
1352140
func (c *Client) DescribeWorkflowExecution(request DescribeWorkflowExecutionRequest) (*DescribeWorkflowExecutionResponse, error) {
	resp := &DescribeWorkflowExecutionResponse{}
	err := c.swfReqWithResponse("DescribeWorkflowExecution", request, resp)
	return resp, err
}