// PrintWorkflowLogs prints logs for all workflow pods
183480
func (p *logPrinter) PrintWorkflowLogs(workflow string) error {
	wfClient := InitWorkflowClient()
	wf, err := wfClient.Get(workflow, metav1.GetOptions{})
	if err != nil {
		return err
	}
	timeByPod := p.printRecentWorkflowLogs(wf)
	if p.follow {
		p.printLiveWorkflowLogs(wf.Name, wfClient, timeByPod)
	}
	return nil
}
1021756
func (c *Cluster) ServiceLogs(ctx context.Context, selector *backend.LogSelector, config *apitypes.ContainerLogsOptions) (<-chan *backend.LogMessage, error) {
	c.mu.RLock()
	defer c.mu.RUnlock()

	state := c.currentNodeState()
	if !state.IsActiveManager() {
		return nil, c.errNoManager(state)
	}

	swarmSelector, err := convertSelector(ctx, state.controlClient, selector)
	if err != nil {
		return nil, errors.Wrap(err, "error making log selector")
	}

	// set the streams we'll use
	stdStreams := []swarmapi.LogStream{}
	if config.ShowStdout {
		stdStreams = append(stdStreams, swarmapi.LogStreamStdout)
	}
	if config.ShowStderr {
		stdStreams = append(stdStreams, swarmapi.LogStreamStderr)
	}

	// Get tail value squared away - the number of previous log lines we look at
	var tail int64
	// in ContainerLogs, if the tail value is ANYTHING non-integer, we just set
	// it to -1 (all). i don't agree with that, but i also think no tail value
	// should be legitimate. if you don't pass tail, we assume you want "all"
	if config.Tail == "all" || config.Tail == "" {
		// tail of 0 means send all logs on the swarmkit side
		tail = 0
	} else {
		t, err := strconv.Atoi(config.Tail)
		if err != nil {
			return nil, errors.New("tail value must be a positive integer or \"all\"")
		}
		if t < 0 {
			return nil, errors.New("negative tail values not supported")
		}
		// we actually use negative tail in swarmkit to represent messages
		// backwards starting from the beginning. also, -1 means no logs. so,
		// basically, for api compat with docker container logs, add one and
		// flip the sign. we error above if you try to negative tail, which
		// isn't supported by docker (and would error deeper in the stack
		// anyway)
		//
		// See the logs protobuf for more information
		tail = int64(-(t + 1))
	}

	// get the since value - the time in the past we're looking at logs starting from
	var sinceProto *gogotypes.Timestamp
	if config.Since != "" {
		s, n, err := timetypes.ParseTimestamps(config.Since, 0)
		if err != nil {
			return nil, errors.Wrap(err, "could not parse since timestamp")
		}
		since := time.Unix(s, n)
		sinceProto, err = gogotypes.TimestampProto(since)
		if err != nil {
			return nil, errors.Wrap(err, "could not parse timestamp to proto")
		}
	}

	stream, err := state.logsClient.SubscribeLogs(ctx, &swarmapi.SubscribeLogsRequest{
		Selector: swarmSelector,
		Options: &swarmapi.LogSubscriptionOptions{
			Follow:  config.Follow,
			Streams: stdStreams,
			Tail:    tail,
			Since:   sinceProto,
		},
	})
	if err != nil {
		return nil, err
	}

	messageChan := make(chan *backend.LogMessage, 1)
	go func() {
		defer close(messageChan)
		for {
			// Check the context before doing anything.
			select {
			case <-ctx.Done():
				return
			default:
			}
			subscribeMsg, err := stream.Recv()
			if err == io.EOF {
				return
			}
			// if we're not io.EOF, push the message in and return
			if err != nil {
				select {
				case <-ctx.Done():
				case messageChan <- &backend.LogMessage{Err: err}:
				}
				return
			}

			for _, msg := range subscribeMsg.Messages {
				// make a new message
				m := new(backend.LogMessage)
				m.Attrs = make([]backend.LogAttr, 0, len(msg.Attrs)+3)
				// add the timestamp, adding the error if it fails
				m.Timestamp, err = gogotypes.TimestampFromProto(msg.Timestamp)
				if err != nil {
					m.Err = err
				}

				nodeKey := contextPrefix + ".node.id"
				serviceKey := contextPrefix + ".service.id"
				taskKey := contextPrefix + ".task.id"

				// copy over all of the details
				for _, d := range msg.Attrs {
					switch d.Key {
					case nodeKey, serviceKey, taskKey:
						// we have the final say over context details (in case there
						// is a conflict (if the user added a detail with a context's
						// key for some reason))
					default:
						m.Attrs = append(m.Attrs, backend.LogAttr{Key: d.Key, Value: d.Value})
					}
				}
				m.Attrs = append(m.Attrs,
					backend.LogAttr{Key: nodeKey, Value: msg.Context.NodeID},
					backend.LogAttr{Key: serviceKey, Value: msg.Context.ServiceID},
					backend.LogAttr{Key: taskKey, Value: msg.Context.TaskID},
				)

				switch msg.Stream {
				case swarmapi.LogStreamStdout:
					m.Source = "stdout"
				case swarmapi.LogStreamStderr:
					m.Source = "stderr"
				}
				m.Line = msg.Data

				// there could be a case where the reader stops accepting
				// messages and the context is canceled. we need to check that
				// here, or otherwise we risk blocking forever on the message
				// send.
				select {
				case <-ctx.Done():
					return
				case messageChan <- m:
				}
			}
		}
	}()
	return messageChan, nil
}
1285494
func (c *Client) ListWorkflowTypes(request ListWorkflowTypesRequest) (*ListWorkflowTypesResponse, error) {
	resp := &ListWorkflowTypesResponse{}
	err := c.swfReqWithResponse("ListWorkflowTypes", request, resp)
	return resp, err
}
1203477
func (uow *UnitOfWork) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) {
	uow.Targeted().Logs(follow, timestamps, tail, colorize, since)
}
458080
func (o *LogsOptions) RunLog() error {
	podLogOptions := o.KubeLogOptions.Options.(*corev1.PodLogOptions)
	infos, err := o.Builder().
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		NamespaceParam(o.Namespace).DefaultNamespace().
		ResourceNames("pods", o.Resources...).
		SingleResourceType().RequireObject(false).
		Do().Infos()
	if err != nil {
		return err
	}
	if len(infos) != 1 {
		return errors.New("expected a resource")
	}

	// TODO: podLogOptions should be included in our own logOptions objects.
	switch gr := infos[0].Mapping.Resource.GroupResource(); gr {
	case buildv1.Resource("builds"),
		buildv1.Resource("buildconfigs"):
		bopts := &buildv1.BuildLogOptions{
			Follow:       podLogOptions.Follow,
			Previous:     podLogOptions.Previous,
			SinceSeconds: podLogOptions.SinceSeconds,
			SinceTime:    podLogOptions.SinceTime,
			Timestamps:   podLogOptions.Timestamps,
			TailLines:    podLogOptions.TailLines,
			LimitBytes:   podLogOptions.LimitBytes,
		}
		if o.Version != 0 {
			bopts.Version = &o.Version
		}
		o.Options = bopts

	case appsv1.Resource("deploymentconfigs"):
		dopts := &appsv1.DeploymentLogOptions{
			Container:    podLogOptions.Container,
			Follow:       podLogOptions.Follow,
			Previous:     podLogOptions.Previous,
			SinceSeconds: podLogOptions.SinceSeconds,
			SinceTime:    podLogOptions.SinceTime,
			Timestamps:   podLogOptions.Timestamps,
			TailLines:    podLogOptions.TailLines,
			LimitBytes:   podLogOptions.LimitBytes,
		}
		if o.Version != 0 {
			dopts.Version = &o.Version
		}
		o.Options = dopts
	default:
		o.Options = nil
	}

	return o.runLogPipeline()
}
1299334
func (s *IssueService) AddWorklogRecord(issueID string, record *WorklogRecord) (*WorklogRecord, *Response, error) {
	apiEndpoint := fmt.Sprintf("rest/api/2/issue/%s/worklog", issueID)
	req, err := s.client.NewRequest("POST", apiEndpoint, record)
	if err != nil {
		return nil, nil, err
	}

	responseRecord := new(WorklogRecord)
	resp, err := s.client.Do(req, responseRecord)
	if err != nil {
		jerr := NewJiraError(resp, err)
		return nil, resp, jerr
	}

	return responseRecord, resp, nil
}
972134
func (o *TriggersOptions) printTriggers(infos []*resource.Info) error {
	w := tabwriter.NewWriter(o.Out, 0, 2, 2, ' ', 0)
	defer w.Flush()
	fmt.Fprintf(w, "NAME\tTYPE\tVALUE\tAUTO\n")
	for _, info := range infos {
		_, err := UpdateTriggersForObject(info.Object, func(triggers *TriggerDefinition) error {
			fmt.Fprintf(w, "%s/%s\t%s\t%s\t%t\n", info.Mapping.Resource.Resource, info.Name, "config", "", triggers.ConfigChange)
			for _, image := range triggers.ImageChange {
				var details string
				switch {
				case len(image.Names) > 0:
					if len(image.Namespace) > 0 {
						details = fmt.Sprintf("%s/%s (%s)", image.Namespace, image.From, strings.Join(image.Names, ", "))
					} else {
						details = fmt.Sprintf("%s (%s)", image.From, strings.Join(image.Names, ", "))
					}
				case len(image.Namespace) > 0:
					details = fmt.Sprintf("%s/%s", image.Namespace, image.From)
				default:
					details = image.From
				}
				fmt.Fprintf(w, "%s/%s\t%s\t%s\t%t\n", info.Mapping.Resource.Resource, info.Name, "image", details, image.Auto)
			}
			for _, s := range triggers.GenericWebHooks {
				val := "<secret>"
				if s.AllowEnv {
					val += ", allowenv"
				}
				fmt.Fprintf(w, "%s/%s\t%s\t%s\t%s\n", info.Mapping.Resource.Resource, info.Name, "webhook", val, "")
			}
			for range triggers.GitHubWebHooks {
				fmt.Fprintf(w, "%s/%s\t%s\t%s\t%s\n", info.Mapping.Resource.Resource, info.Name, "github", "<secret>", "")
			}
			for range triggers.GitLabWebHooks {
				fmt.Fprintf(w, "%s/%s\t%s\t%s\t%s\n", info.Mapping.Resource.Resource, info.Name, "gitlab", "<secret>", "")
			}
			for range triggers.BitbucketWebHooks {
				fmt.Fprintf(w, "%s/%s\t%s\t%s\t%s\n", info.Mapping.Resource.Resource, info.Name, "bitbucket", "<secret>", "")
			}
			return nil
		})
		if err != nil {
			klog.V(2).Infof("Unable to calculate trigger for %s: %v", info.Name, err)
			fmt.Fprintf(w, "%s/%s\t%s\t%s\t%t\n", info.Mapping.Resource.Resource, info.Name, "<error>", "", false)
		}
	}
	return nil
}
562767
func (c *Client) StreamAppLog(appID string, opts *logagg.LogOpts, output chan<- *ct.SSELogChunk) (stream.Stream, error) {
	path := fmt.Sprintf("/apps/%s/log", appID)
	if opts != nil {
		if encodedQuery := opts.EncodedQuery(); encodedQuery != "" {
			path = fmt.Sprintf("%s?%s", path, encodedQuery)
		}
	}
	return c.Stream("GET", path, nil, output)
}
1114790
func callWorkflowHook(hookPhase string,
	hook WorkflowHook,
	hooks []WorkflowHookHandler,
	ctx *workflowContext) error {

	if hook != nil {
		ctx.logger.Warn(fmt.Sprintf("DEPRECATED: Single %s hook superseded by %ss slice",
			hookPhase,
			hookPhase))
		hooks = append(hooks, WorkflowHookFunc(hook))
	}
	for _, eachHook := range hooks {
		// Run the hook
		ctx.logger.WithFields(logrus.Fields{
			"Phase":               hookPhase,
			"WorkflowHookContext": ctx.context.workflowHooksContext,
		}).Info("Calling WorkflowHook")

		hookErr := eachHook.DecorateWorkflow(ctx.context.workflowHooksContext,
			ctx.userdata.serviceName,
			ctx.userdata.s3Bucket,
			ctx.userdata.buildID,
			ctx.context.awsSession,
			ctx.userdata.noop,
			ctx.logger)
		if hookErr != nil {
			return errors.Wrapf(hookErr, "DecorateWorkflow returned an error")
		}
	}
	return nil
}
490051
func WriteLogs(writer io.Writer, logs []*types.Log) {
	for _, log := range logs {
		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)

		for i, topic := range log.Topics {
			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
		}

		fmt.Fprint(writer, hex.Dump(log.Data))
		fmt.Fprintln(writer)
	}
}
541051
func (woc *wfOperationCtx) getAllWorkflowPods() (*apiv1.PodList, error) {
	options := metav1.ListOptions{
		LabelSelector: fmt.Sprintf("%s=%s",
			common.LabelKeyWorkflow,
			woc.wf.ObjectMeta.Name),
	}
	podList, err := woc.controller.kubeclientset.CoreV1().Pods(woc.wf.Namespace).List(options)
	if err != nil {
		return nil, errors.InternalWrapError(err)
	}
	return podList, nil
}
1033929
func (t WorklogType) String() string {
	switch t {
	case SecretRotateWorklogType:
		return "secret"
	case MissingKeypairsWorklogType:
		return "keypairs"
	case InviteApproveWorklogType:
		return "invite"
	case UserKeyringMembersWorklogType:
		fallthrough
	case MachineKeyringMembersWorklogType:
		return "secret"
	default:
		return "n/a"
	}
}
429685
func debugStackPrinter(out io.Writer) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGUSR2)
	for range c {
		pprof.Lookup("goroutine").WriteTo(out, 1)
	}
}
389140
func (lb *LogBroker) PublishLogs(stream api.LogBroker_PublishLogsServer) (err error) {
	remote, err := ca.RemoteNode(stream.Context())
	if err != nil {
		return err
	}

	var currentSubscription *subscription
	defer func() {
		if currentSubscription != nil {
			lb.markDone(currentSubscription, remote.NodeID, err)
		}
	}()

	for {
		logMsg, err := stream.Recv()
		if err == io.EOF {
			return stream.SendAndClose(&api.PublishLogsResponse{})
		}
		if err != nil {
			return err
		}

		if logMsg.SubscriptionID == "" {
			return status.Errorf(codes.InvalidArgument, "missing subscription ID")
		}

		if currentSubscription == nil {
			currentSubscription = lb.getSubscription(logMsg.SubscriptionID)
			if currentSubscription == nil {
				return status.Errorf(codes.NotFound, "unknown subscription ID")
			}
		} else {
			if logMsg.SubscriptionID != currentSubscription.message.ID {
				return status.Errorf(codes.InvalidArgument, "different subscription IDs in the same session")
			}
		}

		// if we have a close message, close out the subscription
		if logMsg.Close {
			// Mark done and then set to nil so if we error after this point,
			// we don't try to close again in the defer
			lb.markDone(currentSubscription, remote.NodeID, err)
			currentSubscription = nil
			return nil
		}

		// Make sure logs are emitted using the right Node ID to avoid impersonation.
		for _, msg := range logMsg.Messages {
			if msg.Context.NodeID != remote.NodeID {
				return status.Errorf(codes.PermissionDenied, "invalid NodeID: expected=%s;received=%s", remote.NodeID, msg.Context.NodeID)
			}
		}

		lb.publish(logMsg)
	}
}
360546
func (r *logRun) printLogs(ctx context.Context, logs []*pb.Step_Log) error {
	if len(logs) == 0 {
		return nil
	}

	// Parse Log URLs.
	addrs := make([]*types.StreamAddr, len(logs))
	for i, l := range logs {
		var err error
		addrs[i], err = types.ParseURL(l.Url)
		if err != nil {
			return fmt.Errorf("log %q has unsupported URL %q", l.Name, l.Url)
		}

		if addrs[0].Host != addrs[i].Host {
			// unrealistic
			return fmt.Errorf("multiple different logdog hosts are not supported")
		}
	}

	// Create a client.
	client := coordinator.NewClient(&prpc.Client{
		C:    r.httpClient,
		Host: addrs[0].Host,
	})

	// Fetch descriptors and create fetchers.
	fetchers := make([]*fetcher.Fetcher, len(addrs))
	m := logMultiplexer{Chans: make([]logChan, len(addrs))}
	err := parallel.FanOutIn(func(work chan<- func() error) {
		for i, addr := range addrs {
			i := i
			stream := client.Stream(addr.Project, addr.Path)
			fetchers[i] = stream.Fetcher(ctx, nil)
			work <- func() error {
				s, err := stream.State(ctx)
				if err != nil {
					return err
				}
				if s.Desc.StreamType != logpb.StreamType_TEXT {
					return fmt.Errorf("log %q is not a text stream; only text streams are currently supported", logs[i].Name)
				}
				m.Chans[i].start, err = ptypes.Timestamp(s.Desc.Timestamp)
				return err
			}
		}
	})
	if err != nil {
		return err
	}

	// Start fetching.
	for i := range m.Chans {
		i := i
		c := make(chan logAndErr, 256)
		m.Chans[i].c = c
		go func() {
			defer close(c)
			for {
				log, err := fetchers[i].NextLogEntry()
				c <- logAndErr{log, err}
				if err != nil {
					break
				}
			}
		}()
	}

	stdout, stderr := newStdioPrinters(r.noColor)
	for {
		chanIndex, entry, err := m.Next()
		out := stdout
		switch {
		case err == io.EOF:
			return nil
		case err != nil:
			return err
		case logs[chanIndex].Name == "stderr":
			out = stderr
		}

		for _, line := range entry.GetText().GetLines() {
			out.f("%s%s", line.Value, line.Delimiter)
		}
		if out.Err != nil {
			return out.Err
		}
	}
}
778106
func (v *version) Workflows() WorkflowInformer {
	return &workflowInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}
533139
func printLogs(logs string) error {
	for _, log := range strings.Split(logs, "\n") {
		category := "unknown"
		parts := strings.Split(strings.Split(log, ": ")[0], " ")
		if len(parts) >= 2 {
			category = parts[1]
		}
		colorVars := map[string]string{
			"Color": chooseColor(category),
			"Log":   log,
		}
		fmt.Println(prettyprint.ColorizeVars("{{.V.Color}}{{.V.Log}}{{.C.Default}}", colorVars))
	}

	return nil
}