Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions app/cli/cmd/attestation_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@
package cmd

import (
"errors"
"fmt"
"strconv"
"strings"

"github.com/chainloop-dev/chainloop/app/cli/pkg/action"
pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1"
"github.com/spf13/cobra"
)

func newAttestationEventCmd() *cobra.Command {
var step, status, message string
var step, status, message, current, total string

cmd := &cobra.Command{
Use: "event",
Expand All @@ -35,12 +38,17 @@ The step shows in "chainloop workflow run describe" while the attestation is in
Events are progress information only. They are not part of the signed attestation.
The step uses letters, digits, "_" and "-", up to 64 characters. Events with the same step are one step of the timeline.
To show a material in the step that adds it, use the same step in "chainloop attestation add --step".
A long step can report its progress with --current and --total, for example 240 of 500 commits, in repeated started events.
If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline.`,
Example: ` # Record the start and the end of a step
chainloop attestation event --step sast-scan --status started --message "Semgrep, ruleset p/ci"
chainloop attestation add --name sast-report --value report.sarif --step sast-scan
chainloop attestation event --step sast-scan --status succeeded

# Report the progress of a long step with repeated started events
chainloop attestation event --step classify-commits --status started --current 0 --total 500
chainloop attestation event --step classify-commits --status started --current 240 --total 500

# Record a step that did not run
chainloop attestation event --step dast-scan --status skipped --message "no web target"`,
// the arguments are checked in RunE, so that a wrong call is a warning too
Expand Down Expand Up @@ -69,8 +77,14 @@ If the event cannot be recorded, the command shows a warning and exits with succ
return nil
}

progress, err := parseRunEventProgress(cmd.Flags().Changed("current"), cmd.Flags().Changed("total"), current, total)
if err != nil {
logger.Warn().Err(err).Msg("the event was not recorded")
return nil
}

a := action.NewAttestationEvent(&action.AttestationEventOpts{ActionsOpts: ActionOpts, LocalStatePath: attestationLocalStatePath})
recorded, err := a.Run(cmd.Context(), attestationID, step, st, message)
recorded, err := a.Run(cmd.Context(), attestationID, step, st, message, progress)
switch {
case err != nil:
logger.Warn().Err(err).Msg("the event was not recorded")
Expand All @@ -87,7 +101,33 @@ If the event cannot be recorded, the command shows a warning and exits with succ
cmd.Flags().StringVar(&step, "step", "", "key of the step (required), with letters, digits, _ and -, up to 64 characters")
cmd.Flags().StringVar(&status, "status", "", fmt.Sprintf("status of the step (required), valid options are %s", strings.Join(action.RunEventStatuses, ", ")))
cmd.Flags().StringVar(&message, "message", "", "message of the event, up to 1 KB")
// string flags, so that a value that is not a number is a warning and not a failure
cmd.Flags().StringVar(&current, "current", "", "progress of the step: the work done so far, from 0 to --total. Requires --total")
cmd.Flags().StringVar(&total, "total", "", "progress of the step: the total work, more than 0. Requires --current")
flagAttestationID(cmd)

return cmd
}

// parseRunEventProgress returns the progress of the flags, or nil when neither is set. A flag
// that is set with an empty value is set, so its value is wrong. The action checks the values
// with the rules of the control plane.
func parseRunEventProgress(currentSet, totalSet bool, current, total string) (*pb.WorkflowRunEvent_Progress, error) {
if !currentSet && !totalSet {
return nil, nil
}
if !currentSet || !totalSet {
return nil, errors.New("set both --current and --total, or neither")
}

c, err := strconv.ParseInt(current, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid --current %q: %w", current, err)
}
t, err := strconv.ParseInt(total, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid --total %q: %w", total, err)
}

return &pb.WorkflowRunEvent_Progress{Current: c, Total: t}, nil
}
35 changes: 32 additions & 3 deletions app/cli/cmd/attestation_event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ func TestAttestationEventCmd(t *testing.T) {
statusFlag = "--status"
started = "started"
sastScan = "sast-scan"
currentFlag = "--current"
totalFlag = "--total"
bothFlags = "set both --current and --total, or neither"
)
// remote selects remote state, so no local state is needed
remote := func(args ...string) []string { return append(args, "--attestation-id", runID) }
Expand All @@ -80,9 +83,11 @@ func TestAttestationEventCmd(t *testing.T) {
cpErr error
wantSent bool
wantKey string
wantWarn string
wantInfo string
wantErr string
// wantProgress is the current and total of the sent event, nil for no progress
wantProgress []int64
wantWarn string
wantInfo string
wantErr string
}{
{
name: "recorded", args: remote(stepFlag, sastScan, statusFlag, started, "--message", "Semgrep"),
Expand All @@ -102,6 +107,22 @@ func TestAttestationEventCmd(t *testing.T) {
{name: "missing step", args: remote(statusFlag, started), wantWarn: "--step is required"},
{name: "the removed --name flag", args: remote("--name", sastScan, statusFlag, started), wantErr: "unknown flag: --name"},
{name: "positional argument", args: remote(sastScan, statusFlag, started), wantWarn: "unexpected arguments"},
{
name: "progress", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "240", totalFlag, "500"),
wantSent: true, wantKey: sastScan, wantProgress: []int64{240, 500}, wantInfo: "event recorded",
},
{
name: "progress at zero", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "0", totalFlag, "500"),
wantSent: true, wantKey: sastScan, wantProgress: []int64{0, 500}, wantInfo: "event recorded",
},
{name: "empty current and total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag+"=", totalFlag+"="), wantWarn: "invalid --current"},
{name: "current with no total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "240"), wantWarn: bothFlags},
{name: "total with no current", args: remote(stepFlag, sastScan, statusFlag, started, totalFlag, "500"), wantWarn: bothFlags},
{name: "current that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "many", totalFlag, "500"), wantWarn: "invalid --current"},
{name: "total that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "1", totalFlag, "1.5"), wantWarn: "invalid --total"},
{name: "current over total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "501", totalFlag, "500"), wantWarn: "current must not be greater than total"},
{name: "zero total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "0", totalFlag, "0"), wantWarn: "invalid progress"},
{name: "negative current", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "-1", totalFlag, "500"), wantWarn: "invalid progress"},
}

for _, tc := range testCases {
Expand Down Expand Up @@ -129,6 +150,14 @@ func TestAttestationEventCmd(t *testing.T) {
assert.Equal(t, runID, got[0].GetWorkflowRunId())
assert.Equal(t, pb.WorkflowRunEvent_TYPE_CUSTOM, got[0].GetEvent().GetType())
assert.Equal(t, tc.wantKey, got[0].GetEvent().GetKey())
assert.Nil(t, got[0].GetEvent().GetAttributes())
if tc.wantProgress == nil {
assert.Nil(t, got[0].GetEvent().GetProgress())
} else {
p := got[0].GetEvent().GetProgress()
require.NotNil(t, p)
assert.Equal(t, tc.wantProgress, []int64{p.GetCurrent(), p.GetTotal()})
}
}

if tc.wantWarn != "" {
Expand Down
49 changes: 47 additions & 2 deletions app/cli/cmd/workflow_run_timeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,11 @@ func timelineCustomStep(key string, evs []*action.RunEvent, materials []timedNod
node.details = append(node.details, "took "+timelineDuration(*first.CreatedAt, *last.CreatedAt))
}

if p := timelineProgress(last); p != "" {
node.details = append(node.details, p)
}

evs = timelineFoldProgressUpdates(evs)
if len(materials) == 0 {
timelineFoldEvents(node, evs)
return node
Expand Down Expand Up @@ -378,9 +383,49 @@ func timelineFoldEvents(node *timelineNode, evs []*action.RunEvent) {
}
}

// timelineEventNode is the line of one event of a step
// timelineEventNode is the line of one event of a step: its message and its progress, or its
// status when it has neither
func timelineEventNode(e *action.RunEvent) *timelineNode {
return &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: timelineMessage(e)}
var parts []string
if e.Message != "" {
parts = append(parts, timelineMessage(e))
}
if p := timelineProgress(e); p != "" {
parts = append(parts, p)
}
if len(parts) == 0 {
parts = append(parts, e.Status)
}

return &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: strings.Join(parts, " · ")}
}

// timelineProgress is the progress of an event as "current/total", or empty
func timelineProgress(e *action.RunEvent) string {
if e.Progress == nil {
return ""
}

return fmt.Sprintf("%d/%d", e.Progress.Current, e.Progress.Total)
}

// timelineFoldProgressUpdates keeps the last of each series of progress updates of a step.
// A progress update is a started event with progress that is not the first event of the step.
// A long step sends one every few seconds, so a step can have hundreds of them.
func timelineFoldProgressUpdates(evs []*action.RunEvent) []*action.RunEvent {
isUpdate := func(i int) bool {
return i > 0 && evs[i].Status == timelineStarted && evs[i].Progress != nil
}

out := make([]*action.RunEvent, 0, len(evs))
for i, e := range evs {
if isUpdate(i) && i+1 < len(evs) && isUpdate(i+1) {
continue
}
out = append(out, e)
}

return out
}

func timelineDuration(from, to time.Time) string {
Expand Down
31 changes: 31 additions & 0 deletions app/cli/cmd/workflow_run_timeline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ func TestRenderRunTimeline(t *testing.T) {
e.Material.Step = step
return e
}
withProgress := func(e *action.RunEvent, current, total int64) *action.RunEvent {
e.Progress = &action.RunEventProgress{Current: current, Total: total}
return e
}

testCases := []struct {
name string
Expand Down Expand Up @@ -185,6 +189,33 @@ func TestRenderRunTimeline(t *testing.T) {
"├─ 10:01:22 ✓ added evidence `sbom`\n" +
"└─ 10:02:02 ✓ pushed and stored\n",
},
{
// spec issue-3825 R-015: the step row shows the progress of its last event, and the
// progress updates in a row fold into the last one
name: "run in progress, with progress of custom steps",
events: []*action.RunEvent{
started,
withProgress(custom(60*time.Second, "classify-commits", "started", "Classifying 500 commits"), 0, 500),
withProgress(custom(70*time.Second, "classify-commits", "started", ""), 120, 500),
withProgress(custom(80*time.Second, "classify-commits", "started", ""), 240, 500),
withProgress(custom(90*time.Second, "single", "started", ""), 3, 10),
withProgress(custom(100*time.Second, "analyze", "started", ""), 0, 10),
withProgress(custom(110*time.Second, "analyze", "started", ""), 10, 10),
custom(120*time.Second, "analyze", "succeeded", ""),
},
progress: &action.RunProgress{},
want: "Timeline (reported progress) · started 10:00:02 · running for 5m43s · 0 of 0 required provided\n" +
"├─ 10:00:02 ✓ initialized policies: 2 passed\n" +
"├─ 10:01:02 ● step `classify-commits` running for 4m43s · 240/500\n" +
"│ ├─ 10:01:02 ● Classifying 500 commits · 0/500\n" +
"│ └─ 10:01:22 ● 240/500\n" +
"├─ 10:01:32 ● step `single` running for 4m13s · 3/10\n" +
"├─ 10:01:42 ✓ step `analyze` took 20s\n" +
"│ ├─ 10:01:42 ● 0/10\n" +
"│ ├─ 10:01:52 ● 10/10\n" +
"│ └─ 10:02:02 ✓ succeeded\n" +
"└─ ● waiting for push\n",
},
{
name: "stored run, with a custom step that never ended",
events: []*action.RunEvent{
Expand Down
7 changes: 7 additions & 0 deletions app/cli/documentation/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ The step shows in "chainloop workflow run describe" while the attestation is in
Events are progress information only. They are not part of the signed attestation.
The step uses letters, digits, "_" and "-", up to 64 characters. Events with the same step are one step of the timeline.
To show a material in the step that adds it, use the same step in "chainloop attestation add --step".
A long step can report its progress with --current and --total, for example 240 of 500 commits, in repeated started events.
If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline.

```
Expand All @@ -333,6 +334,10 @@ chainloop attestation event --step sast-scan --status started --message "Semgrep
chainloop attestation add --name sast-report --value report.sarif --step sast-scan
chainloop attestation event --step sast-scan --status succeeded

Report the progress of a long step with repeated started events
chainloop attestation event --step classify-commits --status started --current 0 --total 500
chainloop attestation event --step classify-commits --status started --current 240 --total 500

Record a step that did not run
chainloop attestation event --step dast-scan --status skipped --message "no web target"
```
Expand All @@ -341,10 +346,12 @@ Options

```
--attestation-id string Unique identifier of the in-progress attestation
--current string progress of the step: the work done so far, from 0 to --total. Requires --total
-h, --help[=true|false] help for event
--message string message of the event, up to 1 KB
--status string status of the step (required), valid options are started, succeeded, failed, canceled, skipped
--step string key of the step (required), with letters, digits, _ and -, up to 64 characters
--total string progress of the step: the total work, more than 0. Requires --current
```

Options inherited from parent commands
Expand Down
29 changes: 19 additions & 10 deletions app/cli/pkg/action/attestation_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,24 @@ func NewAttestationEvent(cfg *AttestationEventOpts) *AttestationEvent {
return &AttestationEvent{ActionsOpts: cfg.ActionsOpts, localStatePath: cfg.LocalStatePath}
}

// Run records the event. It returns false, with no error, when the attestation is a dry run,
// which has no run in the control plane. The event is informational only: the caller must
// not fail the pipeline on its error.
func (action *AttestationEvent) Run(ctx context.Context, attestationID, key string, st pb.WorkflowRunEvent_Status, message string) (bool, error) {
// Run records the event, with the progress of the step when it is not nil. It returns false,
// with no error, when the attestation is a dry run, which has no run in the control plane.
// The event is informational only: the caller must not fail the pipeline on its error.
func (action *AttestationEvent) Run(ctx context.Context, attestationID, key string, st pb.WorkflowRunEvent_Status, message string, progress *pb.WorkflowRunEvent_Progress) (bool, error) {
event := &pb.WorkflowRunEvent{
Type: pb.WorkflowRunEvent_TYPE_CUSTOM,
Key: key,
Status: st,
Message: message,
}
if progress != nil {
// check the values before anything else, with the rules of the control plane
if err := validateRunEventProgress(progress); err != nil {
return false, err
}
event.Progress = progress
}

// the caller reports the error, so the recorder does not log it again
var recorder *runEventRecorder
if attestationID != "" {
Expand All @@ -96,12 +110,7 @@ func (action *AttestationEvent) Run(ctx context.Context, attestationID, key stri
recorder = newRunEventRecorderFromState(action.CPConnection, state, zerolog.Nop())
}

if err := recorder.Record(ctx, &pb.WorkflowRunEvent{
Type: pb.WorkflowRunEvent_TYPE_CUSTOM,
Key: key,
Status: st,
Message: message,
}); err != nil {
if err := recorder.Record(ctx, event); err != nil {
return false, err
}

Expand Down
Loading
Loading