Something went wrong. Try again.
Monorepo for Tangled tangled.org
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337package nsapi
import ( "errors" "fmt" "regexp" "strings"
computepb "buf.build/gen/go/namespace/cloud/protocolbuffers/go/proto/namespace/cloud/compute/v1beta" "google.golang.org/grpc/codes" "google.golang.org/grpc/status")
// ExchangeReason says why namespace refused an oidc tokentype ExchangeReason uint8
const ( ExchangeUntrusted ExchangeReason = iota + 1 ExchangeWorkspaceNotFound ExchangeInvalid)
// ExchangeError is a refused Client.ExchangeOIDCtype ExchangeError struct { Reason ExchangeReason err error}
func (e *ExchangeError) Error() string { switch e.Reason { case ExchangeUntrusted: return fmt.Sprintf("The workspace rejected the run's ID token: %s", Said(e.err)) case ExchangeWorkspaceNotFound: return fmt.Sprintf("The workspace does not exist: %s", Said(e.err)) } return fmt.Sprintf("Namespace rejected the sign-in: %s", Said(e.err))}
func (e *ExchangeError) Unwrap() error { return e.err }
// CapacityKind says which limit a workspace hittype CapacityKind uint8
const ( CapacityUnknown CapacityKind = iota CapacityCPUMemory CapacityInstanceCount)
// Resources is an amount of compute in a workspacetype Resources struct { VCPU int32 MemoryMiB int32 Instances int32}
// CapacityError is a workspace with no room for an instancetype CapacityError struct { Kind CapacityKind Requested, Used, Limit Resources Description string err error}
func (e *CapacityError) Error() string { return "The workspace is out of capacity: " + e.Said()}
func (e *CapacityError) Unwrap() error { return e.err }
// Said gives namespace's own words for the errorfunc (e *CapacityError) Said() string { if e.Description != "" { return sentence(e.Description) } return Said(e.err)}
// Retryable reports if the instance can fit once others end, a request above// the limit never fitsfunc (e *CapacityError) Retryable() bool { switch e.Kind { case CapacityCPUMemory: return e.Requested.VCPU <= e.Limit.VCPU && e.Requested.MemoryMiB <= e.Limit.MemoryMiB case CapacityInstanceCount: return e.Limit.Instances > 0 } return false}
// UsageLimitError is a workspace that used all its compute minutestype UsageLimitError struct { UsedComputeUnitMinutes, LimitComputeUnitMinutes int64 err error}
func (e *UsageLimitError) Error() string { return fmt.Sprintf("The workspace has used %d of its %d compute unit minutes.", e.UsedComputeUnitMinutes, e.LimitComputeUnitMinutes)}
func (e *UsageLimitError) Unwrap() error { return e.err }
// PlatformNotAllowedError is a workspace that does not allow the requested// os and archtype PlatformNotAllowedError struct { Requested string Allowed []string err error}
func (e *PlatformNotAllowedError) Error() string { return fmt.Sprintf("The workspace doesn't allow `%s` machines, only %s.", e.Requested, strings.Join(e.Allowed, ", "))}
func (e *PlatformNotAllowedError) Unwrap() error { return e.err }
// NoRegionError is a platform that no region can run for the workspacetype NoRegionError struct { Platform string err error}
func (e *NoRegionError) Error() string { return fmt.Sprintf("No region can run `%s` machines for the workspace.", e.Platform)}
func (e *NoRegionError) Unwrap() error { return e.err }
// InstanceFailedError is an instance that stopped before it was readytype InstanceFailedError struct { ID InstanceID Reasons []ShutdownReason}
func (e *InstanceFailedError) Error() string { if len(e.Reasons) == 0 { return fmt.Sprintf("Instance `%s` failed.", e.ID) } msgs := make([]string, len(e.Reasons)) for i, r := range e.Reasons { msgs[i] = r.String() } return fmt.Sprintf("Instance `%s` failed: %s.", e.ID, strings.Join(msgs, "; "))}
// Container reports if the named container is one of the reasonsfunc (e *InstanceFailedError) Container(name ContainerName) bool { for _, r := range e.Reasons { if r.Container == name { return true } } return false}
func (r ShutdownReason) String() string { var parts []string if r.Container != "" { parts = append(parts, "container "+string(r.Container)) } if r.ContainerFailedReason != "" { parts = append(parts, r.ContainerFailedReason) } if r.Message != "" { parts = append(parts, r.Message) } if r.ErrorCode != 0 { parts = append(parts, fmt.Sprintf("code %d", r.ErrorCode)) } if len(parts) == 0 { return "no reason given" } return strings.Join(parts, ": ")}
// ShapeNotOfferedError is a machine size that namespace does not offer//// namespace gives either the vcpu counts and memory sizes it offers, or a list// of whole sizestype ShapeNotOfferedError struct { VCPUs, MemoryGB []string Sizes []string err error}
func (e *ShapeNotOfferedError) Error() string { return "Namespace doesn't offer the machine: " + Said(e.err)}
func (e *ShapeNotOfferedError) Unwrap() error { return e.err }
// BaseImageNotFoundError is a set of selectors that no base image matchestype BaseImageNotFoundError struct{ err error }
func (e *BaseImageNotFoundError) Error() string { return "Namespace has no base image for the machine: " + Said(e.err)}
func (e *BaseImageNotFoundError) Unwrap() error { return e.err }
// ImagePullError is a container image that namespace could not pulltype ImagePullError struct{ err error }
func (e *ImagePullError) Error() string { return "The image couldn't be pulled: " + Said(e.err) }
func (e *ImagePullError) Unwrap() error { return e.err }
var ( rangeShapes = regexp.MustCompile(`invalid cpu/mem .* expected in range \(\[([0-9 ]+)\] / \[([0-9 ]+)\]\)`) listShapes = regexp.MustCompile(`invalid cpu/mem .* expected one of ([0-9x, ]+)`))
func shapeNotOffered(msg string, err error) (*ShapeNotOfferedError, bool) { if m := rangeShapes.FindStringSubmatch(msg); m != nil { return &ShapeNotOfferedError{VCPUs: strings.Fields(m[1]), MemoryGB: strings.Fields(m[2]), err: err}, true } if m := listShapes.FindStringSubmatch(msg); m != nil { return &ShapeNotOfferedError{Sizes: strings.FieldsFunc(m[1], func(r rune) bool { return r == ',' || r == ' ' }), err: err}, true } return nil, false}
// Said gives the message of a grpc error as a sentence, without the codefunc Said(err error) string { msg := err.Error() var st interface{ GRPCStatus() *status.Status } if errors.As(err, &st) { msg = st.GRPCStatus().Message() } for strings.HasPrefix(msg, "rpc error: ") { _, rest, ok := strings.Cut(msg, "desc = ") if !ok { break } msg = rest } return sentence(msg)}
func sentence(s string) string { s = strings.TrimSpace(s) if s == "" || strings.HasSuffix(s, ".") { return s } return s + "."}
var exchangeRetry = []codes.Code{codes.Unavailable, codes.DeadlineExceeded, codes.Internal}
// PermissionError is a token without a grant the call needstype PermissionError struct{ err error }
func (e *PermissionError) Error() string { return fmt.Sprintf("The workspace token is missing a permission: %s", Said(e.err))}
func (e *PermissionError) Unwrap() error { return e.err }
func computeError(err error) error { switch status.Code(err) { case codes.PermissionDenied, codes.Unauthenticated: return &PermissionError{err: err} } return err}
func exchangeError(err error) error { switch status.Code(err) { case codes.Unauthenticated, codes.PermissionDenied: return &ExchangeError{Reason: ExchangeUntrusted, err: err} case codes.NotFound: return &ExchangeError{Reason: ExchangeWorkspaceNotFound, err: err} case codes.InvalidArgument, codes.FailedPrecondition: return &ExchangeError{Reason: ExchangeInvalid, err: err} } return err}
func createError(err error) error { st, ok := status.FromError(err) if !ok { return err } for _, d := range st.Details() { switch d := d.(type) { case *computepb.ResourceLimitsError: return &CapacityError{ Kind: capacityKind(d.GetKind()), Requested: resources(d.GetRequested()), Used: resources(d.GetUsed()), Limit: resources(d.GetLimits()), Description: d.GetDescription(), err: err, } case *computepb.UsageLimitsError: return &UsageLimitError{ UsedComputeUnitMinutes: d.GetUsed().GetComputeUnitMinutes(), LimitComputeUnitMinutes: d.GetLimits().GetComputeUnitMinutes(), err: err, } case *computepb.PlatformNotAllowedError: return &PlatformNotAllowedError{Requested: d.GetRequestedPlatform(), Allowed: d.GetAllowedPlatforms(), err: err} case *computepb.NoEligibleRegionError: return &NoRegionError{Platform: d.GetRequestedPlatform(), err: err} } } msg := Said(err) switch { case st.Code() == codes.InvalidArgument: if e, ok := shapeNotOffered(msg, err); ok { return e } case st.Code() == codes.NotFound && strings.Contains(msg, "image not found"): return &BaseImageNotFoundError{err: err} case strings.Contains(msg, "failed to resolve image"): return &ImagePullError{err: err} } if st.Code() == codes.ResourceExhausted { return &CapacityError{Kind: CapacityUnknown, err: err} } return computeError(err)}
func capacityKind(k computepb.ResourceLimitsError_LimitKind) CapacityKind { switch k { case computepb.ResourceLimitsError_CPU_MEMORY_LIMIT: return CapacityCPUMemory case computepb.ResourceLimitsError_INSTANCE_COUNT_LIMIT: return CapacityInstanceCount } return CapacityUnknown}
func resources(r *computepb.ResourceLimitsError_Resource) Resources { return Resources{VCPU: r.GetVirtualCpu(), MemoryMiB: r.GetMemoryMegabytes(), Instances: r.GetInstanceCount()}}