Skip to content
Open
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
11 changes: 10 additions & 1 deletion agent/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,15 @@ func NewAgentEnvConfig() AgentConfig {
httpPort = p
}

webhookPort := WebhookServerPort
if webhookPortStr := os.Getenv("WEBHOOK_PORT"); webhookPortStr != "" {
p, err := strconv.Atoi(webhookPortStr)
if err != nil {
panic(err)
}
webhookPort = p
}

snykBrokerPort := 0
if snykBrokerPortStr := os.Getenv("SNYK_BROKER_PORT"); snykBrokerPortStr != "" {
p, err := strconv.Atoi(snykBrokerPortStr)
Expand Down Expand Up @@ -349,7 +358,7 @@ func NewAgentEnvConfig() AgentConfig {
InstanceId: getInstanceId(),
IntegrationAlias: identifier,
HttpServerPort: httpPort,
WebhookServerPort: WebhookServerPort,
WebhookServerPort: webhookPort,
SnykBrokerPort: snykBrokerPort,
EnableApiProxy: true,
EnablePprof: enablePprof,
Expand Down
79 changes: 79 additions & 0 deletions agent/proto/cortex-axon-agent.proto
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ service AxonAgent {
rpc GetHandlerHistory(GetHandlerHistoryRequest) returns (GetHandlerHistoryResponse);
rpc Dispatch (stream DispatchRequest) returns (stream DispatchMessage);
rpc ReportInvocation(ReportInvocationRequest) returns (ReportInvocationResponse);

// DispatchEvents sends the client every failed invocation, and the client
// answers each with what to do about it. It is its own stream so a client
// that has stopped reading Dispatch because every handler is busy still
// hears about failures. An event the client has not answered when the
// stream ends is sent again on the next one.
rpc DispatchEvents(stream DispatchEventsRequest) returns (stream DispatchEvent);
}


Expand Down Expand Up @@ -86,6 +93,9 @@ message ListHandlersResponse {
message DispatchRequest {
string dispatch_id = 1;
string client_version = 2;
// The client handles failure events. The agent only keeps them for clients
// that ask, so an older client never has events pile up for it.
bool failure_events = 3;
}

message DispatchMessage {
Expand All @@ -111,6 +121,71 @@ message DispatchHandlerInvoke{
int32 timeout_ms = 10;
HandlerInvokeType reason = 11;
map<string, string> args = 20;
// 1 for the first attempt; 0 means the agent didn't say, so treat it as 1.
int32 attempt = 30;
// When the agent stops waiting for this invocation's result and reports
// the failure itself. A client must not start a handler after it, since
// the failure has already been reported. Unset from older agents.
google.protobuf.Timestamp deadline = 31;
}

//
// Failure events
//

enum FailureReason {
FAILURE_REASON_UNSPECIFIED = 0;
// The handler returned an error or raised.
HANDLER_ERROR = 1;
// The invocation did not finish within its timeout.
TIMEOUT = 2;
// The invocation could not be dispatched: the queue was full, or it expired
// while waiting for a free handler.
NO_RESOURCES = 3;
}

enum FailureSource {
FAILURE_SOURCE_UNSPECIFIED = 0;
// The failure came from handler code.
APPLICATION = 1;
// The failure came from Axon: the agent, the SDK, or a Cortex API call.
RUNTIME = 2;
}

message InvocationFailure {
FailureReason reason = 1;
FailureSource source = 2;
string message = 3;
// Whoever submitted the invocation was told it was not accepted (e.g. a
// webhook sender got a 503), so it may be sent again.
bool caller_rejected = 4;
}

message DispatchEvent {
DispatchHandlerInvoke invoke = 1;
InvocationFailure failure = 2;
}

enum FailureAction {
// Treated as DROP.
FAILURE_ACTION_UNSPECIFIED = 0;
// Do nothing more with the invocation.
FAILURE_ACTION_DROP = 1;
// Queue the invocation again as its next attempt.
FAILURE_ACTION_RETRY = 2;
}

message FailureResolution {
string invocation_id = 1;
FailureAction action = 2;
}

message DispatchEventsRequest {
// Identifies the client on the first message of the stream.
string dispatch_id = 1;
string client_version = 2;
// The client's answer to a DispatchEvent; unset on the first message.
FailureResolution resolution = 3;
}

//
Expand All @@ -131,6 +206,10 @@ message ReportInvocationRequest {
InvokeResult result = 200;
Error error = 201;
}
// Why the invocation failed, from a client that classifies its failures.
// The agent passes it on as a failure event; an error without it is only
// recorded.
InvocationFailure failure = 202;
repeated Log logs = 300;
}

Expand Down
88 changes: 79 additions & 9 deletions agent/server/handler/handler_invoke.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package handler

import (
"context"
"errors"
"fmt"
"slices"
"sync/atomic"
"time"

Expand All @@ -19,6 +21,45 @@ type Invocable interface {
Complete(result string, err error) error
Done() <-chan struct{}
GetResult() (string, error)

// SetState moves the invocation to a new state, and reports false when
// that transition isn't allowed from where it is now.
SetState(state InvokeState) bool
State() InvokeState
}

type InvokeState int32

const (
// InvokeQueued is waiting for a client to take it.
InvokeQueued InvokeState = iota
// InvokeDispatched has been sent to a client.
InvokeDispatched
// InvokeExpired ran out of time before a client took it.
InvokeExpired
// InvokeRejected was refused because the queue was full.
InvokeRejected
)

// invokeTransitions lists the states each state may move to. A queued
// invocation leaves the queue exactly once, one way or another.
var invokeTransitions = map[InvokeState][]InvokeState{
InvokeQueued: {InvokeDispatched, InvokeExpired, InvokeRejected},
}

// FailureError completes an invocation that failed in a way its handler's
// failure hook should hear about. Every such failure, wherever it is
// detected, reaches the failure manager this one way.
type FailureError struct {
Failure *pb.InvocationFailure
}

func (e *FailureError) Error() string {
return fmt.Sprintf("%s (%s): %s", e.Failure.GetReason(), e.Failure.GetSource(), e.Failure.GetMessage())
}

func NewFailureError(reason pb.FailureReason, source pb.FailureSource, message string) *FailureError {
return &FailureError{Failure: &pb.InvocationFailure{Reason: reason, Source: source, Message: message}}
}

type HandlerInvoke struct {
Expand All @@ -28,13 +69,15 @@ type HandlerInvoke struct {
Args map[string]string
Timeout time.Duration
Timestamp time.Time
Attempt int32

result string
err error
done chan struct{}

started *atomic.Bool
finished *atomic.Bool
state *atomic.Int32
}

func NewHandlerInvoke(
Expand All @@ -49,32 +92,42 @@ func NewHandlerInvoke(
Args: args,
Timeout: entry.Timeout(),
Timestamp: time.Now(),
Attempt: 1,

done: make(chan struct{}),
started: &atomic.Bool{},
finished: &atomic.Bool{},
state: &atomic.Int32{},
}
}

func (h HandlerInvoke) GetEntry() HandlerEntry {
func (h *HandlerInvoke) GetEntry() HandlerEntry {
return h.Entry
}
func (h HandlerInvoke) GetName() string {
func (h *HandlerInvoke) GetName() string {
return h.Entry.Name()
}

func (h HandlerInvoke) GetReason() pb.HandlerInvokeType {
func (h *HandlerInvoke) GetReason() pb.HandlerInvokeType {
return h.Reason
}

// Start bounds how long the invocation may wait in the queue. Once a client
// has it, its result comes from the client's report or the agent's own
// timeout instead.
func (h *HandlerInvoke) Start(ctx context.Context) {
if h.started.CompareAndSwap(false, true) {
go func() {
select {
case <-ctx.Done():
err := ctx.Err()
if err == nil {
err = fmt.Errorf("context cancelled")
if !h.SetState(InvokeExpired) {
return
}
var err error = ctx.Err()
if errors.Is(err, context.DeadlineExceeded) {
err = NewFailureError(pb.FailureReason_NO_RESOURCES, pb.FailureSource_RUNTIME,
fmt.Sprintf("expired after %v waiting for a free handler",
time.Since(h.Timestamp).Round(time.Millisecond)))
}
h.Complete("", err)
case <-h.done:
Expand All @@ -96,18 +149,34 @@ func (h *HandlerInvoke) Complete(result string, err error) error {
return fmt.Errorf("handler already finished")
}

func (h HandlerInvoke) GetResult() (string, error) {
func (h *HandlerInvoke) GetResult() (string, error) {
if h.finished.Load() {
return h.result, h.err
}
return "", fmt.Errorf("handler not finished")
}

func (h HandlerInvoke) Done() <-chan struct{} {
func (h *HandlerInvoke) Done() <-chan struct{} {
return h.done
}

func (h HandlerInvoke) ToDispatchInvoke() *pb.DispatchHandlerInvoke {
func (h *HandlerInvoke) SetState(to InvokeState) bool {
for {
from := InvokeState(h.state.Load())
if !slices.Contains(invokeTransitions[from], to) {
return false
}
if h.state.CompareAndSwap(int32(from), int32(to)) {
return true
}
}
}

func (h *HandlerInvoke) State() InvokeState {
return InvokeState(h.state.Load())
}

func (h *HandlerInvoke) ToDispatchInvoke() *pb.DispatchHandlerInvoke {
return &pb.DispatchHandlerInvoke{
InvocationId: h.Id,
DispatchId: h.Entry.DispatchId(),
Expand All @@ -116,5 +185,6 @@ func (h HandlerInvoke) ToDispatchInvoke() *pb.DispatchHandlerInvoke {
Reason: h.Reason,
Args: h.Args,
TimeoutMs: int32(h.Entry.Timeout().Milliseconds()),
Attempt: h.Attempt,
}
}
12 changes: 6 additions & 6 deletions agent/server/handler/handler_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func TestTriggerAndDequeue(t *testing.T) {
invoke := NewScheduledHandlerInvoke(entry, pb.HandlerInvokeType_RUN_NOW)
err = mgr.Trigger(invoke)
require.NoError(t, err)
h, err := mgr.Dequeue(context.Background(), "1", 500*time.Millisecond)
h, err := dequeueWithin(mgr, 500*time.Millisecond)
require.NoError(t, err)
require.NotNil(t, h)
require.Equal(t, "handler1", h.GetEntry().Name())
Expand Down Expand Up @@ -165,7 +165,7 @@ func TestTriggerAndDequeueCustomTimeout(t *testing.T) {

err = mgr.Trigger(invoke)
require.NoError(t, err)
h, err := mgr.Dequeue(context.Background(), "1", 500*time.Millisecond)
h, err := dequeueWithin(mgr, 500*time.Millisecond)
require.NoError(t, err)
require.NotNil(t, h)
require.Equal(t, "handler1", h.GetEntry().Name())
Expand All @@ -180,8 +180,8 @@ func TestTriggerAndDequeueTimeout(t *testing.T) {
_, err := mgr.RegisterHandler("1", "handler1", defaultTimeout, FixtureHandlerOption())
require.NoError(t, err)

h, err := mgr.Dequeue(context.Background(), "1", time.Millisecond)
require.NoError(t, err)
h, err := dequeueWithin(mgr, time.Millisecond)
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Nil(t, h)
}

Expand All @@ -195,8 +195,8 @@ func TestTriggerAndDequeueTimeoutContext(t *testing.T) {

ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()
h, err := mgr.Dequeue(ctx, "1", time.Hour)
require.NoError(t, err)
h, err := mgr.Dequeue(ctx, "1")
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Nil(t, h)
}

Expand Down
Loading
Loading