model

package
Version: v0.0.0-...-1bdc99b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 21, 2022 License: Apache-2.0 Imports: 27 Imported by: 1

Documentation

Overview

Package model contains datastore model implementation.

Index

Constants

View Source
const (
	// BucketKind is a bucket entity's kind in the datastore.
	BucketKind = "BucketV2"
)
View Source
const (
	// BuildKind is a Build entity's kind in the datastore.
	BuildKind = "Build"
)
View Source
const BuildStepsMaxBytes = 1e6

BuildStepsMaxBytes is the maximum length of BuildSteps.Bytes. If Bytes exceeds this maximum, this package will try to compress it, setting IsZipped accordingly, but if this length is still exceeded it's an error to write such entities to the datastore. Use FromProto to ensure this maximum is respected.

View Source
const BuilderExpirationDuration = 4 * 7 * 24 * time.Hour // 4 weeks

BuilderExpirationDuration is the maximum duration a builder can go without having a build scheduled before its BuilderStat may be deleted.

View Source
const BuilderKind = "Bucket.Builder"

BuilderKind is the kind of the Builder entity.

View Source
const BuilderStatKind = "Builder"

BuilderStatKind is the kind of the BuilderStat entity.

View Source
const MaxTagIndexEntries = 1000

MaxTagIndexEntries is the maximum number of entries that may be associated with a single TagIndex entity.

View Source
const TagIndexShardCount = 16

TagIndexShardCount is the number of shards used by the TagIndex.

Variables

View Source
var DefaultBuildMask = HardcodedBuildMask(defaultFieldMask.Paths...)

DefaultBuildMask is the default mask to use for read requests.

View Source
var LegacyCancelationReason_name = []string{
	0:                  "UNSET",
	ExplicitlyCanceled: "CANCELED_EXPLICITLY",
	TimeoutCanceled:    "TIMEOUT",
}
View Source
var LegacyFailureReason_name = []string{
	0:                      "UNSET",
	BuildFailure:           "BUILD_FAILURE",
	BuildbucketFailure:     "BUILDBUCKET_FAILURE",
	InfraFailure:           "INFRA_FAILURE",
	InvalidBuildDefinition: "INVALID_BUILD_DEFINITION",
}
View Source
var LegacyResult_name = []string{
	0:        "UNSET",
	Success:  "SUCCESS",
	Failure:  "FAILURE",
	Canceled: "CANCELED",
}
View Source
var LegacyStatus_name = []string{
	0:         "UNSET",
	Scheduled: "SCHEDULED",
	Started:   "STARTED",
	Completed: "COMPLETED",
}
View Source
var NoopBuildMask = &BuildMask{m: mask.All(&buildPrototype)}

NoopBuildMask selects all fields.

View Source
var TagIndexIncomplete = errors.BoolTag{Key: errors.NewTagKey("tag index incomplete")}

TagIndexIncomplete means the tag index is incomplete and thus cannot be searched.

Functions

func BucketKey

func BucketKey(ctx context.Context, project, bucket string) *datastore.Key

BucketKey returns a datastore key of a bucket.

func BuilderKey

func BuilderKey(ctx context.Context, project, bucket, builder string) *datastore.Key

BuilderKey returns a datastore key of a builder.

func GenerateSequenceNumbers

func GenerateSequenceNumbers(ctx context.Context, name string, n int) (int32, error)

GenerateSequenceNumbers generates n numbers for the given sequence name, returning the smallest number the caller may use. For a returned number i, the caller may use [i, i+n).

func GetIgnoreMissing

func GetIgnoreMissing(ctx context.Context, dst ...interface{}) error

GetIgnoreMissing fetches the given entities from the datastore, ignoring datastore.ErrNoSuchEntity errors. All other errors are returned. For valid values of dst, see datastore.Get.

func LoadBuildDetails

func LoadBuildDetails(ctx context.Context, m *BuildMask, builds ...*pb.Build) error

LoadBuildDetails loads the details of the given builds, trimming them according to the mask.

func ProjectKey

func ProjectKey(ctx context.Context, project string) *datastore.Key

ProjectKey returns a datastore key of a project.

func UpdateBuilderStat

func UpdateBuilderStat(ctx context.Context, builds []*Build, scheduledTime time.Time) error

UpdateBuilderStat updates or creates datastore BuilderStat entities.

func UpdateTagIndex

func UpdateTagIndex(ctx context.Context, tag string, ents []TagIndexEntry) error

UpdateTagIndex updates the tag index for the given tag.

Types

type Bucket

type Bucket struct {

	// ID is the bucket in v2 format.
	// e.g. try (never luci.chromium.try).
	ID     string         `gae:"$id"`
	Parent *datastore.Key `gae:"$parent"`

	// Bucket is the bucket in v2 format.
	// e.g. try (never luci.chromium.try).
	Bucket string `gae:"bucket_name"`
	// Proto is the pb.Bucket proto representation of the bucket.
	//
	// acl_sets is zeroed by inlining acls. swarming.builders is
	// zeroed and stored in separate Builder datastore entities due to
	// potentially large size.
	Proto *pb.Bucket `gae:"config,legacy"`
	// Revision is the config revision this entity was created from.
	// TODO(crbug/1042991): Switch to noindex.
	Revision string `gae:"revision"`
	// Schema is this entity's schema version.
	// TODO(crbug/1042991): Switch to noindex.
	Schema int32 `gae:"entity_schema_version"`
	// contains filtered or unexported fields
}

Bucket is a representation of a bucket in the datastore.

type Build

type Build struct {
	ID int64 `gae:"$id"`

	// LegacyProperties are properties set for v1 legacy builds.
	LegacyProperties
	// UnusedProperties are properties set previously but currently unused.
	UnusedProperties

	// Proto is the pb.Build proto representation of the build.
	//
	// infra, input.properties, output.properties, and steps
	// are zeroed and stored in separate datastore entities
	// due to their potentially large size (see details.go).
	// tags are given their own field so they can be indexed.
	//
	// noindex is not respected here, it's set in pb.Build.ToProperty.
	Proto *pb.Build `gae:"proto,legacy"`

	Project string `gae:"project"`
	// <project>/<bucket>. Bucket is in v2 format.
	// e.g. chromium/try (never chromium/luci.chromium.try).
	BucketID string `gae:"bucket_id"`
	// <project>/<bucket>/<builder>. Bucket is in v2 format.
	// e.g. chromium/try/linux-rel.
	BuilderID string `gae:"builder_id"`

	Canary bool `gae:"canary"`

	CreatedBy identity.Identity `gae:"created_by"`
	// TODO(nodir): Replace reliance on create_time indices with id.
	CreateTime time.Time `gae:"create_time"`
	// Experimental, if true, means to exclude from monitoring and search results
	// (unless specifically requested in search results).
	Experimental bool `gae:"experimental"`
	// Experiments is a slice of experiments enabled or disabled on this build.
	// Each element should look like "[-+]$experiment_name".
	//
	// Special case:
	//   "-luci.non_production" is not kept here as a storage/index
	//   optimization.
	//
	//   Notably, all search/query implementations on the Build model
	//   apply this filter in post by checking that
	//   `b.ExperimentStatus("luci.non_production") == pb.Trinary_YES`.
	//
	//   This is because directly including this value in the datastore query
	//   results in bad performance due to excessive zig-zag join overhead
	//   in the datastore, since 99%+ of the builds in Buildbucket are production
	//   builds.
	Experiments []string `gae:"experiments"`
	Incomplete  bool     `gae:"incomplete"`

	// Deprecated; remove after v1 api turndown
	IsLuci bool `gae:"is_luci"`

	ResultDBUpdateToken string    `gae:"resultdb_update_token,noindex"`
	Status              pb.Status `gae:"status_v2"`
	StatusChangedTime   time.Time `gae:"status_changed_time"`
	// Tags is a slice of "<key>:<value>" strings taken from Proto.Tags.
	// Stored separately in order to index.
	Tags []string `gae:"tags"`

	// UpdateToken is set at the build creation time, and UpdateBuild requests are required
	// to have it in the header.
	UpdateToken string `gae:"update_token,noindex"`

	// PubSubCallback, if set, creates notifications for build status changes.
	PubSubCallback PubSubCallback `gae:"pubsub_callback,noindex"`
	// contains filtered or unexported fields
}

Build is a representation of a build in the datastore. Implements datastore.PropertyLoadSaver.

func (*Build) ExperimentStatus

func (b *Build) ExperimentStatus(expname string) (ret pb.Trinary)

ExperimentStatus scans the experiments attached to this Build and returns:

* YES - The experiment was known at schedule time and enabled.
* NO - The experiment was known at schedule time and disabled.
* UNSET - The experiment was unknown at schedule time.

Malformed Experiment filters are treated as UNSET.

func (*Build) ExperimentsString

func (b *Build) ExperimentsString() string

ExperimentsString sorts, joins, and returns the enabled experiments with "|".

Returns "None" if no experiments were enabled in the build.

func (*Build) IterExperiments

func (b *Build) IterExperiments(cb func(enabled bool, exp string) bool)

IterExperiments parses all experiments and calls `cb` for each.

This will always include a call with bb.ExperimentNonProduction, even if '-'+bb.ExperimentNonProduction isn't recorded in the underlying Experiments field.

func (*Build) Load

func (b *Build) Load(p datastore.PropertyMap) error

Load overwrites this representation of a build by reading the given datastore.PropertyMap. Mutates this entity.

func (*Build) Realm

func (b *Build) Realm() string

Realm returns this build's auth realm, or an empty string if not opted into the realms experiment.

func (*Build) Save

func (b *Build) Save(withMeta bool) (datastore.PropertyMap, error)

Save returns the datastore.PropertyMap representation of this build. Mutates this entity to reflect computed datastore fields in the returned PropertyMap.

func (*Build) ToProto

func (b *Build) ToProto(ctx context.Context, m *BuildMask) (*pb.Build, error)

ToProto returns the *pb.Build representation of this build.

func (*Build) ToSimpleBuildProto

func (b *Build) ToSimpleBuildProto(ctx context.Context) *pb.Build

ToSimpleBuildProto returns the *pb.Build without loading steps, infra, input/output properties.

type BuildInfra

type BuildInfra struct {

	// ID is always 1 because only one such entity exists.
	ID int `gae:"$id,1"`
	// Build is the key for the build this entity belongs to.
	Build *datastore.Key `gae:"$parent"`
	// Proto is the pb.BuildInfra proto representation of the infra field.
	Proto *pb.BuildInfra `gae:"infra,legacy"`
	// contains filtered or unexported fields
}

BuildInfra is a representation of a build proto's infra field in the datastore.

func (*BuildInfra) Load

func (bi *BuildInfra) Load(pm datastore.PropertyMap) error

Load implements datastore.PropertyLoadSaver in order to apply defaultStructValues to bi.Proto.

func (*BuildInfra) Save

func (bi *BuildInfra) Save(withMeta bool) (datastore.PropertyMap, error)

Save implements datastore.PropertyLoadSaver

type BuildInputProperties

type BuildInputProperties struct {

	// ID is always 1 because only one such entity exists.
	ID int `gae:"$id,1"`
	// Build is the key for the build this entity belongs to.
	Build *datastore.Key `gae:"$parent"`
	// Proto is the structpb.Struct representation of the properties field.
	Proto DSStruct `gae:"properties,noindex"`
	// contains filtered or unexported fields
}

BuildInputProperties is a representation of a build proto's input field's properties field in the datastore.

type BuildMask

type BuildMask struct {
	// contains filtered or unexported fields
}

BuildMask knows how to filter pb.Build proto messages.

func HardcodedBuildMask

func HardcodedBuildMask(fields ...string) *BuildMask

HardcodedBuildMask returns a build mask with given fields.

Panics if some of them are invalid. Intended to be used to initialize constants or in tests.

func NewBuildMask

func NewBuildMask(legacyPrefix string, legacy *fieldmaskpb.FieldMask, bm *pb.BuildMask) (*BuildMask, error)

NewBuildMask constructs a build mask either using a legacy `fields` FieldMask or new `mask` BuildMask (but not both at the same time, pick one).

legacyPrefix is usually "", but can be "builds" to trim "builds." from the legacy field mask (used by SearchBuilds API).

If the mask is empty, returns DefaultBuildMask.

func (*BuildMask) Includes

func (m *BuildMask) Includes(fieldPath string) bool

Includes returns true if the given field path is included in the mask (either partially or entirely).

Panics if the fieldPath is invalid.

func (*BuildMask) Trim

func (m *BuildMask) Trim(b *pb.Build) error

Trim applies the mask to the build in-place.

type BuildOutputProperties

type BuildOutputProperties struct {

	// ID is always 1 because only one such entity exists.
	ID int `gae:"$id,1"`
	// Build is the key for the build this entity belongs to.
	Build *datastore.Key `gae:"$parent"`
	// Proto is the structpb.Struct representation of the properties field.
	Proto DSStruct `gae:"properties,noindex"`
	// contains filtered or unexported fields
}

BuildOutputProperties is a representation of a build proto's output field's properties field in the datastore.

type BuildSteps

type BuildSteps struct {

	// ID is always 1 because only one such entity exists.
	ID int `gae:"$id,1"`
	// Build is the key for the build this entity belongs to.
	Build *datastore.Key `gae:"$parent"`
	// IsZipped indicates whether or not Bytes is zlib compressed.
	// Use ToProto to ensure this compression is respected.
	IsZipped bool `gae:"step_container_bytes_zipped,noindex"`
	// Bytes is the pb.Build proto representation of the build proto where only steps is set.
	// IsZipped determines whether this value is compressed or not.
	Bytes []byte `gae:"steps,noindex"`
	// contains filtered or unexported fields
}

BuildSteps is a representation of a build proto's steps field in the datastore.

func (*BuildSteps) CancelIncomplete

func (s *BuildSteps) CancelIncomplete(ctx context.Context, now *timestamppb.Timestamp) (bool, error)

CancelIncomplete marks any incomplete steps as cancelled, returning whether at least one step was cancelled. The caller is responsible for writing the entity to the datastore if any steps were cancelled. This entity will not be mutated if an error occurs.

func (*BuildSteps) FromProto

func (s *BuildSteps) FromProto(stp []*pb.Step) error

FromProto overwrites the current []*pb.Step representation of these steps. The caller is responsible for writing the entity to the datastore. This entity will not be mutated if an error occurs.

func (*BuildSteps) ToProto

func (s *BuildSteps) ToProto(ctx context.Context) ([]*pb.Step, error)

ToProto returns the []*pb.Step representation of these steps.

type Builder

type Builder struct {

	// ID is the builder name, e.g. "linux-rel".
	ID string `gae:"$id"`

	// Parent is the key of the parent Bucket.
	Parent *datastore.Key `gae:"$parent"`

	// Config is the builder configuration feched from luci-config.
	Config *pb.Builder `gae:"config,legacy"`

	// ConfigHash is used for fast deduplication of configs.
	ConfigHash string `gae:"config_hash"`
	// contains filtered or unexported fields
}

Builder is a Datastore entity that stores builder configuration. It is a child of Bucket entity.

Builder entities are updated together with their parents, in a cron job.

type BuilderStat

type BuilderStat struct {

	// ID is a string with format "{project}:{bucket}:{builder}".
	ID string `gae:"$id"`

	// LastScheduled is the last time we received a valid build scheduling request
	// for this builder. Probabilistically update when scheduling a build.
	LastScheduled time.Time `gae:"last_scheduled"`
	// contains filtered or unexported fields
}

BuilderStat represents a builder Datastore entity which is used internally for metrics.

The builder will be registered automatically by scheduling a build, and unregistered automatically by not scheduling builds for BuilderExpirationDuration.

Note: due to the historical reason, the entity kind is Builder.

type DSStruct

type DSStruct struct {
	structpb.Struct
}

DSStruct is a wrapper around structpb.Struct. Implements datastore.PropertyConverter, allowing reads from and writes to the datastore.

func (*DSStruct) FromProperty

func (s *DSStruct) FromProperty(p datastore.Property) error

FromProperty deserializes structpb.Struct protos from the datastore. Implements datastore.PropertyConverter.

func (*DSStruct) ToProperty

func (s *DSStruct) ToProperty() (datastore.Property, error)

ToProperty serializes structpb.Struct protos to datastore format. Implements datastore.PropertyConverter.

type LeaseProperties

type LeaseProperties struct {
	IsLeased bool `gae:"is_leased"`
	// TODO(crbug/1042991): Create datastore.PropertyConverter in server/auth.
	Leasee              []byte    `gae:"leasee"`
	LeaseExpirationDate time.Time `gae:"lease_expiration_date"`
	// LeaseKey is a random value used to verify the leaseholder's identity.
	LeaseKey    int  `gae:"lease_key"`
	NeverLeased bool `gae:"never_leased"`
}

LeaseProperties are properties associated with the legacy leasing API.

type LegacyCancelationReason

type LegacyCancelationReason int

LegacyCancelationReason is the reason for a canceled legacy build.

const (

	// ExplicitlyCanceled means the build was canceled (likely via API call).
	ExplicitlyCanceled LegacyCancelationReason
	// TimeoutCanceled means Buildbucket timed the build out.
	TimeoutCanceled
)

func (LegacyCancelationReason) String

func (r LegacyCancelationReason) String() string

type LegacyFailureReason

type LegacyFailureReason int

LegacyFailureReason is the reason for a legacy build failure.

const (

	// BuildFailure means the build itself failed.
	BuildFailure LegacyFailureReason
	// BuildbucketFailure means something went wrong within Buildbucket.
	BuildbucketFailure
	// InfraFailure means something went wrong outside the build and Buildbucket.
	InfraFailure
	// InvalidBuildDefinition means the build system rejected the build definition.
	InvalidBuildDefinition
)

func (LegacyFailureReason) String

func (r LegacyFailureReason) String() string

type LegacyProperties

type LegacyProperties struct {
	LeaseProperties

	CancelationReason LegacyCancelationReason `gae:"cancelation_reason"`
	FailureReason     LegacyFailureReason     `gae:"failure_reason"`
	Parameters        []byte                  `gae:"parameters"`
	Result            LegacyResult            `gae:"result"`
	ResultDetails     []byte                  `gae:"result_details"`
	// ID of the Build this is a retry of.
	RetryOf int          `gae:"retry_of"`
	Status  LegacyStatus `gae:"status"`
	URL     string       `gae:"url,noindex"`
}

LegacyProperties are properties of legacy builds.

Parameters and ResultDetails are byte slices interpretable as JSON. TODO(crbug/1042991): Create datastore.PropertyConverter for JSON properties.

type LegacyResult

type LegacyResult int

LegacyResult is the result of a completed legacy build.

const (

	// Success means the build completed successfully.
	Success LegacyResult
	// Failure means the build failed and has an associated LegacyFailureReason.
	Failure
	// Canceled means the build was canceled
	// and has an associated LegacyCancelationReason.
	Canceled
)

func (LegacyResult) String

func (r LegacyResult) String() string

type LegacyStatus

type LegacyStatus int

LegacyStatus is the status of a legacy build request.

const (

	// Scheduled builds may be leased and started.
	Scheduled LegacyStatus
	// Started builds are leased and marked as started.
	Started
	// Completed builds are finished and have an associated LegacyResult.
	Completed
)

func (LegacyStatus) String

func (r LegacyStatus) String() string

type NumberSequence

type NumberSequence struct {
	ID string `gae:"$id"`

	Next int32 `gae:"next_number,noindex"`
	// contains filtered or unexported fields
}

NumberSequence stores the next number in a named sequence of numbers.

type Project

type Project struct {
	ID string `gae:"$id"`
}

Project is the parent entity of buckets in the datastore. Entities of this kind don't exist in the datastore.

type PubSubCallback

type PubSubCallback struct {
	AuthToken string `gae:"auth_token,noindex"`
	Topic     string `gae:"topic,noindex"`
	UserData  []byte `gae:"user_data,noindex"`
}

PubSubCallback encapsulates parameters for a Pub/Sub callback.

type RequestID

type RequestID struct {

	// ID is a string of the form "<auth.Identity>:<request ID string>" encoded
	// as a hex string using SHA-256 for a well-distributed key space.
	ID string `gae:"$id"`

	// BuildID is the ID of the Build entity this entity refers to.
	BuildID    int64             `gae:"build_id,noindex"`
	CreatedBy  identity.Identity `gae:"created_by,noindex"`
	CreateTime time.Time         `gae:"create_time,noindex"`
	// RequestID is the original request ID string this entity was created from.
	RequestID string `gae:"request_id,noindex"`
	// contains filtered or unexported fields
}

RequestID stores request IDs for request deduplication.

func NewRequestID

func NewRequestID(ctx context.Context, buildID int64, now time.Time, requestID string) *RequestID

NewRequestID returns a request ID with the entity ID filled in.

type TagIndex

type TagIndex struct {

	// ID is a "<key>:<value>" or ":<index>:<key>:<value>" string for index > 0.
	ID string `gae:"$id"`
	// Incomplete means there are more than MaxTagIndexEntries entities
	// with the same ID, and therefore the index is incomplete and cannot be
	// searched.
	Incomplete bool `gae:"permanently_incomplete,noindex"`
	// Entries is a slice of TagIndexEntries matching this ID.
	Entries []TagIndexEntry `gae:"entries,noindex"`
	// contains filtered or unexported fields
}

TagIndex is an index used to search Build entities by tag.

type TagIndexEntry

type TagIndexEntry struct {
	// BuildID is the ID of the Build entity this entry refers to.
	BuildID int64 `json:"build_id"`
	// <project>/<bucket>. Bucket is in v2 format.
	// e.g. chromium/try (never chromium/luci.chromium.try).
	BucketID string `json:"bucket_id"`
	// CreatedTime is the time this entry was created.
	CreatedTime time.Time `json:"created_time"`
}

TagIndexEntry refers to a particular Build entity.

func SearchTagIndex

func SearchTagIndex(ctx context.Context, key, val string) ([]*TagIndexEntry, error)

SearchTagIndex searches the tag index for the given tag. Returns an error tagged with TagIndexIncomplete if the tag index is incomplete and thus cannot be searched.

func (*TagIndexEntry) FromProperty

func (e *TagIndexEntry) FromProperty(p datastore.Property) error

FromProperty deserializes TagIndexEntries from the datastore. Implements datastore.PropertyConverter.

func (*TagIndexEntry) ToProperty

func (e *TagIndexEntry) ToProperty() (datastore.Property, error)

ToProperty serializes TagIndexEntries to datastore format. Implements datastore.PropertyConverter.

type UnusedProperties

type UnusedProperties struct {
	// PubSubCallback is normally a struct (see build.go), which translates into datastore
	// fields pubsub_callback.auth_token, pubsub_callback.topic, pubsub_callback.user_data
	// with no actual field called pubsub_callback. However, nil values in the datastore
	// may exist for pubsub_callback (should instead be represented by having all three
	// pubsub_callback.* fields nil, but isn't). Capture such nil values here.
	// TODO(crbug/1042991): Support this case properly in gae datastore package.
	PubSubCallback []byte `gae:"pubsub_callback,noindex"`
}

UnusedProperties are properties previously set but currently unused.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL