common

package
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2019 License: BSD-3-Clause Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Kibibyte is 1024 Bytes.
	Kibibyte = Byte(1024)

	// Mebibyte is 1024 Kibibytes.
	Mebibyte = Byte(1024) * Kibibyte

	// Gibibyte is 1024 Mebibytes.
	Gibibyte = Byte(1024) * Mebibyte

	// Tebibyte is 1024 Gibibytes.
	Tebibyte = Byte(1024) * Gibibyte
)
View Source
const (
	// EventBegin represents the beginning of a Duration Event.
	EventBegin = "B"

	// EventClockSync represents an event that is used to synchronize different
	// clock domains. For instance, a client and a server will have clocks that
	// are not necessarily in-sync and might drift a bit from each other.
	EventClockSync = "c"

	// EventEnd represents the end of a Duration Event.
	EventEnd = "E"

	// EventComplete represents a complete Duration Event. This is logically the
	// combination of a Begin and End events, and avoids some overhead.
	EventComplete = "X"

	// EventInstant represents an event that does not have a duration associated
	// with it.
	EventInstant = "i"

	// EventMetadata represents extra information that is not necessarily an
	// Event. It is typically used to add things like process and thread names.
	EventMetadata = "M"
)

Variables

View Source
var (
	DefaultLiteralLimitSettings = LimitsSettings{
		TimeLimit:            Duration(time.Duration(10) * time.Second),
		MemoryLimit:          Gibibyte + Gibibyte/2,
		OverallWallTimeLimit: Duration(time.Duration(10) * time.Second),
		ExtraWallTime:        Duration(0),
		OutputLimit:          Byte(2) * Mebibyte,
	}

	DefaultLiteralValidatorSettings = LiteralValidatorSettings{
		Name: "token-caseless",
	}

	DefaultValidatorTolerance = 1e-6
)

Default values for some of the settings.

View Source
var (
	// DefaultValidatorLimits specifies the default limits for a validator.
	DefaultValidatorLimits = LimitsSettings{
		ExtraWallTime:        Duration(0),
		MemoryLimit:          Byte(256) * Mebibyte,
		OutputLimit:          Byte(10) * Kibibyte,
		OverallWallTimeLimit: Duration(time.Duration(5) * time.Second),
		TimeLimit:            Duration(time.Duration(1) * time.Second),
	}

	// DefaultLimits specifies the default limits for a problem.
	DefaultLimits = LimitsSettings{
		ExtraWallTime:        Duration(0),
		MemoryLimit:          Byte(32) * Mebibyte,
		OutputLimit:          Byte(10) * Kibibyte,
		OverallWallTimeLimit: Duration(time.Duration(1) * time.Minute),
		TimeLimit:            Duration(time.Duration(1) * time.Second),
	}
)

Functions

func AcceptsMimeType

func AcceptsMimeType(r *http.Request, mimeType string) bool

AcceptsMimeType returns whether the provided MIME type was mentioned in the Accept HTTP header in the http.Request.

func FloatToRational added in v1.1.0

func FloatToRational(floatVal float64) *big.Rat

FloatToRational returns a rational that's within 1e-6 of the floating-point value.

func LanguageFileExtension added in v1.1.0

func LanguageFileExtension(language string) string

LanguageFileExtension returns the file extension for a particular language.

func NewAttemptID

func NewAttemptID() uint64

NewAttemptID allocates a locally-unique AttemptID. A counter is initialized to a random 63-bit integer on startup and then atomically incremented eacn time a new ID is needed.

func NewSyncID

func NewSyncID() uint64

NewSyncID allocates a locally-unique SyncID. A counter is initialized to a random 63-bit integer on startup and then atomically incremented each time a new ID is needed.

func ParseRational added in v1.1.0

func ParseRational(str string) (*big.Rat, error)

ParseRational returns a rational that's within 1e-6 of the floating-point value that has been serialized as a string.

func RationalDiv added in v1.1.0

func RationalDiv(num, denom *big.Rat) *big.Rat

RationalDiv implements division between two rationals.

func RationalToFloat added in v1.1.0

func RationalToFloat(val *big.Rat) float64

RationalToFloat returns the closest float value to the given big.Rat.

func RunServer

func RunServer(
	tlsConfig *TLSConfig,
	handler http.Handler,
	addr string,
	insecure bool,
)

RunServer runs an http.Server with the specified http.Handler forever. It will optionally enable TLS.

func Sha1sum

func Sha1sum(filename string) ([]byte, error)

Sha1sum is an utility function that obtains the SHA1 hash of a file (as referenced to by the filename parameter).

Types

type Arg

type Arg struct {
	Name  string
	Value interface{}
}

An Arg represents a name-value pair.

type BaseInput

type BaseInput struct {
	sync.Mutex
	// contains filtered or unexported fields
}

BaseInput is an abstract struct that provides most of the functions required to implement Input.

func NewBaseInput

func NewBaseInput(hash string, mgr *InputManager) *BaseInput

NewBaseInput returns a new reference to a BaseInput.

func (*BaseInput) Acquire

func (input *BaseInput) Acquire()

Acquire increases the refcount of the Input. This makes it ineligible for garbage collection.

func (*BaseInput) Commit

func (input *BaseInput) Commit(size int64)

Commit adds the Input to the set of cached inputs, and also adds its size to the total committed size.

func (*BaseInput) Committed

func (input *BaseInput) Committed() bool

Committed returns whether the Input has been committed to disk.

func (*BaseInput) Delete

func (input *BaseInput) Delete() error

Delete deletes all the files associated with the Input.

func (*BaseInput) Hash

func (input *BaseInput) Hash() string

Hash returns the hash of the Input.

func (*BaseInput) Path

func (input *BaseInput) Path() string

Path returns the filesystem path to the Input.

func (*BaseInput) Persist

func (input *BaseInput) Persist() error

Persist writes all the files associated with the Input to disk. The files can be garbage collected later if there are no outstanding references to the input and there is disk space pressure.

func (*BaseInput) Release

func (input *BaseInput) Release(outerInput Input)

Release decreases the refcount of the Input. Once there are no outstanding references to this input, it can be garbage collected if needed.

func (*BaseInput) Reserve

func (input *BaseInput) Reserve(size int64)

Reserve ensures that there are at least size bytes available in the input cache. This might evict older, unused Inputs.

func (*BaseInput) Settings

func (input *BaseInput) Settings() *ProblemSettings

Settings returns the ProblemSettings associated with the current Input.

func (*BaseInput) Size

func (input *BaseInput) Size() int64

Size returns the total disk size used by the Input.

func (*BaseInput) Transmit

func (input *BaseInput) Transmit(w http.ResponseWriter) error

Transmit sends the input across HTTP.

func (*BaseInput) Verify

func (input *BaseInput) Verify() error

Verify ensures that the disk representation of the Input is still valid. It typically does this by computing the hash of all files.

type BroadcasterConfig

type BroadcasterConfig struct {
	ChannelLength           int
	EventsPort              uint16
	FrontendURL             string
	PingPeriod              Duration
	Port                    uint16
	Proxied                 bool
	ScoreboardUpdateSecret  string
	ScoreboardUpdateTimeout Duration
	TLS                     TLSConfig // only used if Proxied == false
	WriteDeadline           Duration
}

BroadcasterConfig represents the configuration for the Broadcaster.

type ByCaseName

type ByCaseName []CaseSettings

A ByCaseName represents a list of CaseSettings associated with a group that implements the sort.Interface.

func (ByCaseName) Len

func (c ByCaseName) Len() int

func (ByCaseName) Less

func (c ByCaseName) Less(i, j int) bool

func (ByCaseName) Swap

func (c ByCaseName) Swap(i, j int)

type ByGroupName

type ByGroupName []GroupSettings

A ByGroupName represents a list of GroupSettings associated with a problem that implements the sort.Interface.

func (ByGroupName) Len

func (g ByGroupName) Len() int

func (ByGroupName) Less

func (g ByGroupName) Less(i, j int) bool

func (ByGroupName) Swap

func (g ByGroupName) Swap(i, j int)

type Byte added in v1.1.0

type Byte int64

A Byte is a unit of digital information.

func MaxBytes added in v1.1.0

func MaxBytes(x, y Byte) Byte

MaxBytes returns the larger of x or y.

func MinBytes added in v1.1.0

func MinBytes(x, y Byte) Byte

MinBytes returns the smaller of x or y.

func (Byte) Bytes added in v1.1.0

func (b Byte) Bytes() int64

Bytes returns the Byte as an integer number of bytes.

func (Byte) Gibibytes added in v1.1.0

func (b Byte) Gibibytes() float64

Gibibytes returns the Byte as an floating point number of Gibibytes.

func (Byte) Kibibytes added in v1.1.0

func (b Byte) Kibibytes() float64

Kibibytes returns the Byte as an floating point number of Kibibytes.

func (Byte) MarshalJSON added in v1.1.0

func (b Byte) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. The result is an integer number of bytes.

func (Byte) Mebibytes added in v1.1.0

func (b Byte) Mebibytes() float64

Mebibytes returns the Byte as an floating point number of Mebibytes.

func (Byte) Tebibytes added in v1.1.0

func (b Byte) Tebibytes() float64

Tebibytes returns the Byte as an floating point number of Tebibytes.

func (*Byte) UnmarshalJSON added in v1.1.0

func (b *Byte) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The result can be an integer number of bytes, or a quoted string that MarshalJSON() can understand.

type CachedInputFactory

type CachedInputFactory interface {
	InputFactory

	// GetInputHash returns both the hash of the input for the specified
	// os.FileInfo. It returns ok = false in case the os.FileInfo does not refer
	// to an Input.
	GetInputHash(dirname string, info os.FileInfo) (hash string, ok bool)
}

CachedInputFactory is an InputFactory that also can validate Inputs that are already in the filesystem.

type CaseSettings

type CaseSettings struct {
	Name   string
	Weight *big.Rat
}

CaseSettings contains the information of a single test case.

func (*CaseSettings) MarshalJSON added in v1.1.0

func (c *CaseSettings) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*CaseSettings) UnmarshalJSON added in v1.1.0

func (c *CaseSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type CompleteEvent

type CompleteEvent struct {
	NormalEvent
	Duration int64 `json:"dur"`
}

A CompleteEvent is a NormalEvent that has a full duration associated to it.

func (*CompleteEvent) Finalize

func (e *CompleteEvent) Finalize()

Finalize computes the duration of the current CompleteEvent.

type Config

type Config struct {
	Broadcaster  BroadcasterConfig
	InputManager InputManagerConfig
	Grader       GraderConfig
	Db           DbConfig
	Logging      LoggingConfig
	Metrics      MetricsConfig
	Tracing      TracingConfig
	Runner       RunnerConfig
	TLS          TLSConfig
}

Config represents the configuration for the whole program.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default Config.

func NewConfig

func NewConfig(reader io.Reader) (*Config, error)

NewConfig creates a new Config from the specified reader.

func (*Config) String

func (config *Config) String() string

type Context

type Context struct {
	Config         Config
	Log            log15.Logger
	EventCollector EventCollector
	EventFactory   *EventFactory
	Metrics        Metrics
	// contains filtered or unexported fields
}

A Context holds data associated with a single request.

func NewContext

func NewContext(config *Config, role string) (*Context, error)

NewContext creates a new Context from the specified Config. This also creates a Logger. The role is just an arbitrary string that will be used to disambiguate process names in the tracing in case multiple roles run from the same host (e.g. grader and runner in the development VM).

func NewContextFromReader

func NewContextFromReader(reader io.Reader, role string) (*Context, error)

NewContextFromReader creates a new Context from the specified reader. This also creates a Logger.

func (*Context) AppendLogSection

func (context *Context) AppendLogSection(sectionName string, contents []byte)

AppendLogSection adds a complete section of logs to the log buffer. This typcally comes from a client.

func (*Context) Close

func (context *Context) Close()

Close releases all resources owned by the context.

func (*Context) DebugContext

func (context *Context) DebugContext(logCtx ...interface{}) *Context

DebugContext returns a new Context with an additional handler with a more verbose filter (using the Debug level) and a Buffer in which all logging statements will be (also) written to.

func (*Context) LogBuffer

func (context *Context) LogBuffer() []byte

LogBuffer returns the contents of the logging buffer for this context.

func (*Context) TraceBuffer

func (context *Context) TraceBuffer() []byte

TraceBuffer returns a JSON representation of the Trace Event stream for this Context.

type DbConfig

type DbConfig struct {
	Driver         string
	DataSourceName string
}

DbConfig represents the configuration for the database.

type Duration added in v1.1.0

type Duration time.Duration

Duration is identical to time.Duration, except it can implements the json.Marshaler interface with time.Duration.String() and time.Duration.ParseDuration().

func MaxDuration added in v1.1.0

func MaxDuration(x, y Duration) Duration

MaxDuration returns the larger of x or y.

func MinDuration added in v1.1.0

func MinDuration(x, y Duration) Duration

MinDuration returns the smaller of x or y.

func (Duration) MarshalJSON added in v1.1.0

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. The duration is a quoted string in RFC 3339 format, with sub-second precision added if present.

func (Duration) Milliseconds added in v1.1.0

func (d Duration) Milliseconds() float64

Milliseconds returns the duration as a floating point number of milliseconds.

func (Duration) Seconds added in v1.1.0

func (d Duration) Seconds() float64

Seconds returns the duration as a floating point number of seconds.

func (Duration) String added in v1.1.0

func (d Duration) String() string

String returns a string representing the duration in the form "72h3m0.5s". Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s.

func (*Duration) UnmarshalJSON added in v1.1.0

func (d *Duration) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The duration is expected to be a quoted string that time.ParseDuration() can understand.

type Event

type Event interface {
	// Finalize performs any necessary post-processing for this Event.
	Finalize()
}

An Event represents an abstract event in the system.

type EventCollector

type EventCollector interface {
	Add(Event) error
	io.Closer
}

An EventCollector aggregates events in Chromium's Trace Event Format, which is a (modified) JSON list of objects. The full documentation can be found at https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview

type EventFactory

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

An EventFactory can create events modelled after Chrome's Trace Events.

func NewEventFactory

func NewEventFactory(processName, threadName string) *EventFactory

NewEventFactory creates a new EventFactory with the provided process and thread names.

func (*EventFactory) NewCompleteEvent

func (factory *EventFactory) NewCompleteEvent(
	name string,
	args ...Arg,
) *CompleteEvent

NewCompleteEvent creates a CompleteEvent with the supplied arguments. It saves the overhead of having a start and end events.

func (*EventFactory) NewEvent

func (factory *EventFactory) NewEvent(
	name string,
	eventType string,
	args ...Arg,
) *NormalEvent

NewEvent creates a generic event.

func (*EventFactory) NewIssuerClockSyncEvent

func (factory *EventFactory) NewIssuerClockSyncEvent() *IssuerClockSyncEvent

NewIssuerClockSyncEvent creates a ClockSync event in a server context. The autogenerated SyncID can be sent to a client so that the clocks can be correlated.

func (*EventFactory) NewReceiverClockSyncEvent

func (factory *EventFactory) NewReceiverClockSyncEvent(syncID uint64) *NormalEvent

NewReceiverClockSyncEvent creates a ClockSync event in a client context. This allows to correlate the clocks of the server and client.

func (*EventFactory) Register

func (factory *EventFactory) Register(collector EventCollector) error

Register adds the supplied collector to the factory. All the events sent to the factory will be aggregated by the collector.

type GraderConfig

type GraderConfig struct {
	ChannelLength   int
	Port            uint16
	RuntimePath     string
	MaxGradeRetries int
	BroadcasterURL  string
	V1              V1Config
	Ephemeral       GraderEphemeralConfig
	WriteGradeFiles bool // TODO(lhchavez): Remove once migration is done.
}

GraderConfig represents the configuration for the Grader.

type GraderEphemeralConfig added in v1.1.0

type GraderEphemeralConfig struct {
	EphemeralSizeLimit   Byte
	CaseTimeLimit        Duration
	OverallWallTimeLimit Duration
	MemoryLimit          Byte
	PingPeriod           Duration
	Port                 uint16
	Proxied              bool
	TLS                  TLSConfig // only used if Proxied == false
	WriteDeadline        Duration
}

GraderEphemeralConfig represents the configuration for the Grader web interface.

type GroupSettings

type GroupSettings struct {
	Cases []CaseSettings
	Name  string
}

GroupSettings contains the information of the test case groups.

func (*GroupSettings) Weight

func (g *GroupSettings) Weight() *big.Rat

Weight returns the sum of the individual case weights.

type HashReader

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

HashReader is a Reader that provides a Sum function. After having completely read the Reader, the Sum function will provide the hash of the complete stream.

func NewHashReader

func NewHashReader(r io.Reader, h hash.Hash) *HashReader

NewHashReader returns a new HashReader for a given Reader and Hash.

func (*HashReader) Length

func (r *HashReader) Length() int64

Length returns the number of bytes involved in the hash computation so far.

func (*HashReader) Read

func (r *HashReader) Read(b []byte) (int, error)

Read calls the underlying Reader's Read function and updates the Hash with the read bytes.

func (*HashReader) Sum

func (r *HashReader) Sum(b []byte) []byte

Sum returns the hash of the Reader. Typically invoked after Read reaches EOF. Will consume any non-consumed data.

type IdentityInputFactory

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

IdentityInputFactory is an InputFactory that only constructs one Input.

func NewIdentityInputFactory

func NewIdentityInputFactory(input Input) *IdentityInputFactory

NewIdentityInputFactory returns an IdentityInputFactory associated with the provided Input.

func (*IdentityInputFactory) NewInput

func (factory *IdentityInputFactory) NewInput(hash string, mgr *InputManager) Input

NewInput returns the Input provided in the constructor. Panics if the requested hash does not match the one of the Input.

type Input

type Input interface {
	Lockable
	RefCounted

	// Path returns the path to the uncompressed representation of the Input
	// on-disk.
	Path() string

	// Hash is the identifier of the Input. It is typically the Git hash of the
	// tree that it represents.
	Hash() string

	// Commited returns true if the input has been verified and is committed into
	// its InputManager.
	Committed() bool

	// Size returns the number of bytes of the Input's on-disk representation.
	Size() int64

	// Verify ensures that the version of the Input stored in the filesystem
	// exists and is consistent, and commits it so that it can be added to the
	// InputManager. It is expected that Size() returns a valid size after
	// Verify() returns successfully.
	Verify() error

	// Persist stores the Input into the filesystem in a form that is
	// easily consumed and can be verified for consistency after restarting.
	Persist() error

	// Delete removes the filesystem version of the Input to free space.
	Delete() error

	// Settings returns the problem's settings for the Input. Problems can have
	// different ProblemSettings on different Inputs.
	Settings() *ProblemSettings

	// Transmit sends a serialized version of the Input over HTTP. It should be a
	// .tar.gz file with the Content-SHA1 header set to the hexadecimal
	// representation of the SHA-1 hash of the file.
	Transmit(http.ResponseWriter) error
}

Input represents a problem's input set.

Input is reference-counted, so it will keep the input in memory (and disk) while there is at least one reference to it. Once the last reference is released, it will be inserted into its associated InputManager.

type InputFactory

type InputFactory interface {
	NewInput(hash string, mgr *InputManager) Input
}

InputFactory creates Input objects for an InputManager based on a hash. The hash is just an opaque identifier that just so happens to be the SHA1 hash of the git tree representation of the Input.

InputFactory is provided so that the Grader and the Runner can have different implementations of how to create, read, and write an Input in disk.

type InputManager

type InputManager struct {
	sync.Mutex
	// contains filtered or unexported fields
}

InputManager handles a pool of recently-used input sets. The pool has a fixed maximum size with a least-recently used eviction policy.

func NewInputManager

func NewInputManager(ctx *Context) *InputManager

NewInputManager creates a new InputManager with the provided Context.

func (*InputManager) Add

func (mgr *InputManager) Add(hash string, factory InputFactory) (Input, error)

Add associates an opaque identifier (the hash) with an Input in the InputManager.

The InputFactory is responsible to create the Input if it has not yet been created. The Input will be validated if it has not been committed to the InputManager, but will still not be accounted into the size limit since there is at least one live reference to it.

func (*InputManager) Get

func (mgr *InputManager) Get(hash string) (Input, error)

Get returns the Input for a specified hash, if it is already present in the pool. If it is present, it will increment its reference-count and transfer the ownership of the reference to the caller. It is the caller's responsibility to release the ownership of the Input.

func (*InputManager) Insert

func (mgr *InputManager) Insert(input Input)

Insert adds an already-created Input to the pool, possibly evicting old entries to free enough space such that the total size of Inputs in the pool is still within the limit. This should only be called when there are no references to the Input.

func (*InputManager) MarshalJSON

func (mgr *InputManager) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of the InputManager.

func (*InputManager) PreloadInputs

func (mgr *InputManager) PreloadInputs(
	rootdir string,
	factory CachedInputFactory,
	ioLock sync.Locker,
) error

PreloadInputs reads all files in path, runs them through the specified filter, and tries to add them into the InputManager. PreloadInputs acquires the ioLock just before doing I/O in order to guarantee that the system will not be doing expensive I/O operations in the middle of a performance-sensitive operation (like running contestants' code).

func (*InputManager) Reserve

func (mgr *InputManager) Reserve(size int64)

Reserve evicts Inputs from the pool to make the specified size available.

func (*InputManager) Size

func (mgr *InputManager) Size() int64

Size returns the total size (in bytes) of cached Inputs in the InputManager. This does not count any Inputs with live references.

type InputManagerConfig

type InputManagerConfig struct {
	CacheSize Byte
}

InputManagerConfig represents the configuration for the InputManager.

type InteractiveInterface

type InteractiveInterface struct {
	MakefileRules []struct {
		Targets    []string
		Requisites []string
		Compiler   string
		Params     string
		Debug      bool
	}
	ExecutableDescription struct {
		Args []string
		Env  map[string]string
	}
	Files map[string]string
}

InteractiveInterface represents the metadata needed to compile and run libinteractive problems.

type InteractiveSettings

type InteractiveSettings struct {
	Interfaces            map[string]map[string]*InteractiveInterface
	Templates             map[string]string
	Main                  string
	ModuleName            string
	ParentLang            string
	LibinteractiveVersion string
}

InteractiveSettings contains the information needed by libinteractive to generate interactive shims.

type IssuerClockSyncEvent

type IssuerClockSyncEvent struct {
	NormalEvent
	SyncID uint64 `json:"-"`
}

IssuerClockSyncEvent is a NormalEvent that is associated with a Clock Sync Event in the server clock domain. The SyncID can be sent to the client so that the clock domains can be correlated.

func (*IssuerClockSyncEvent) Finalize

func (e *IssuerClockSyncEvent) Finalize()

Finalize records the timestamp whtn the event was issued and when the client replied that it received the event. This allows to synchronized both clock domains.

type LimitsSettings

type LimitsSettings struct {
	ExtraWallTime        Duration
	MemoryLimit          Byte
	OutputLimit          Byte
	OverallWallTimeLimit Duration
	TimeLimit            Duration
}

LimitsSettings represents runtime limits for the Input.

type LiteralCaseSettings

type LiteralCaseSettings struct {
	Input          string   `json:"in"`
	ExpectedOutput string   `json:"out"`
	Weight         *big.Rat `json:"weight"`
}

LiteralCaseSettings stores the input, expected output, and the weight of a particular test case.

func (*LiteralCaseSettings) MarshalJSON added in v1.1.0

func (c *LiteralCaseSettings) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*LiteralCaseSettings) UnmarshalJSON added in v1.1.0

func (c *LiteralCaseSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type LiteralCustomValidatorSettings

type LiteralCustomValidatorSettings struct {
	Source   string          `json:"source"`
	Language string          `json:"language"`
	Limits   *LimitsSettings `json:"limits,omitempty"`
}

LiteralCustomValidatorSettings stores the source of the program that will validate the contestant's outputs.

type LiteralInput

type LiteralInput struct {
	Cases       map[string]*LiteralCaseSettings `json:"cases"`
	Limits      *LimitsSettings                 `json:"limits,omitempty"`
	Validator   *LiteralValidatorSettings       `json:"validator,omitempty"`
	Interactive *LiteralInteractiveSettings     `json:"interactive,omitempty"`
}

LiteralInput is a standalone representation of an Input (although it cannot be used directly as an Input). It is useful for testing and to evaluate a run that doesn't have a problem associated with it.

type LiteralInputFactory

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

LiteralInputFactory is an InputFactory that will return an Input version of the specified LiteralInput when asked for an input.

func NewLiteralInputFactory

func NewLiteralInputFactory(
	input *LiteralInput,
	runtimePath string,
	persistMode LiteralPersistMode,
) (*LiteralInputFactory, error)

NewLiteralInputFactory validates the LiteralInput and stores it so it can be returned when NewInput is called.

func (*LiteralInputFactory) Hash

func (factory *LiteralInputFactory) Hash() string

Hash returns the hash of the literal input.

func (*LiteralInputFactory) NewInput

func (factory *LiteralInputFactory) NewInput(hash string, mgr *InputManager) Input

NewInput returns the LiteralInput that was specified as the LiteralInputFactory's Input in its constructor.

type LiteralInteractiveSettings

type LiteralInteractiveSettings struct {
	IDLSource  string            `json:"idl"`
	ModuleName string            `json:"module_name"`
	ParentLang string            `json:"language"`
	MainSource string            `json:"main_source"`
	Templates  map[string]string `json:"templates"`
}

LiteralInteractiveSettings stores the settings for a problem that uses libinteractive.

type LiteralPersistMode added in v1.1.0

type LiteralPersistMode int

LiteralPersistMode indicates whether the LiteralInputFactory should persist the input for the runner, grader, or neither.

const (
	// LiteralPersistNone indicates that the input should not be persisted.
	LiteralPersistNone LiteralPersistMode = iota

	// LiteralPersistGrader indicates that the input will be persisted with the
	// grader format.
	LiteralPersistGrader

	// LiteralPersistRunner indicates that the input will be persisted with the
	// runner format.
	LiteralPersistRunner
)

type LiteralRun

type LiteralRun struct {
	Source   string `json:"source"`
	Language string `json:"language"`
	Input    string `json:"input"`
}

LiteralRun is a standalone representation of a Run. It is useful for testing and to evaluate a run that doesn't have a problem associated with it.

type LiteralValidatorSettings

type LiteralValidatorSettings struct {
	Name            string                          `json:"name"`
	Tolerance       *float64                        `json:"tolerance,omitempty"`
	CustomValidator *LiteralCustomValidatorSettings `json:"custom_validator,omitempty"`
}

LiteralValidatorSettings stores the settings for the validator, that will calculate a per-case grade. Valid values for Name are "custom", "literal", "token", "token-caseless", "token-numeric". If "custom" is chosen, a valid CustomValidator must be provided. If "token-numeric" is chosen, Tolerance must contain a numeric tolerance (typically a small number).

type Lockable

type Lockable interface {
	Lock()
	Unlock()
}

Lockable is the interface that sync.Mutex implements.

type LoggingConfig

type LoggingConfig struct {
	File  string
	Level string
}

LoggingConfig represents the configuration for logging.

type MemoryEventCollector

type MemoryEventCollector struct {
	Events []Event
	// contains filtered or unexported fields
}

A MemoryEventCollector is an EventCollector that stores all the Events in an in-memory queue. It uses a sync.Mutex to synchonize access to the queue so that all the writes are thread-safe.

func NewMemoryEventCollector

func NewMemoryEventCollector() *MemoryEventCollector

NewMemoryEventCollector returns a MemoryEventCollector.

func (*MemoryEventCollector) Add

func (collector *MemoryEventCollector) Add(e Event) error

Add adds the specified Event to the in-memory queue of Events.

func (*MemoryEventCollector) Close added in v1.1.0

func (collector *MemoryEventCollector) Close() error

Close is a no-op.

func (*MemoryEventCollector) MarshalJSON

func (collector *MemoryEventCollector) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of the tracing events.

func (*MemoryEventCollector) UnmarshalJSON

func (collector *MemoryEventCollector) UnmarshalJSON(buf []byte) error

UnmarshalJSON reads the serialized JSON in buf and converts it into an in-memory representation.

type Metrics added in v1.1.0

type Metrics interface {
	// GaugeAdd increments a gauge. A gauge is a metric that represents a single
	// numerical value that can arbitrarily go up and down.
	GaugeAdd(name string, value float64)

	// CounterAdd increments a counter. A counter is a metric that represents a
	// single numerical value that only ever goes up.
	CounterAdd(name string, value float64)

	// SummaryObserve adds an observation to a summary. A summary is an aggregate
	// metric that supports querying percentiles.
	SummaryObserve(name string, value float64)
}

Metrics is an interface that supports updating different kinds of metrics. All its functions are thread-safe.

type MetricsConfig

type MetricsConfig struct {
	Port uint16
}

MetricsConfig represents the configuration for metrics.

type MultiEventCollector

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

A MultiEventCollector is an EventCollector that can broadcast Events to multiple EventCollectors.

func NewMultiEventCollector

func NewMultiEventCollector(collectors ...EventCollector) *MultiEventCollector

NewMultiEventCollector returns a new MultiEventCollector with all the specified collectors.

func (*MultiEventCollector) Add

func (collector *MultiEventCollector) Add(e Event) error

Add broadcasts the specified Event to all the EventCollectors.

func (*MultiEventCollector) Close added in v1.1.0

func (collector *MultiEventCollector) Close() error

Close closes all underlying collectors.

type NoOpMetrics added in v1.1.0

type NoOpMetrics struct {
}

NoOpMetrics is an implementation of Metrics that does nothing.

func (*NoOpMetrics) CounterAdd added in v1.1.0

func (n *NoOpMetrics) CounterAdd(name string, value float64)

CounterAdd adds the specified value to a counter of the specified name. Value should be non-negative.

func (*NoOpMetrics) GaugeAdd added in v1.1.0

func (n *NoOpMetrics) GaugeAdd(name string, value float64)

GaugeAdd adds the specified value to a gauge of the specified name.

func (*NoOpMetrics) SummaryObserve added in v1.1.0

func (n *NoOpMetrics) SummaryObserve(name string, value float64)

SummaryObserve adds the specified value to a summary of the specified name.

type NormalEvent

type NormalEvent struct {
	Name      string                 `json:"name"`
	Type      string                 `json:"ph"`
	Timestamp int64                  `json:"ts"`
	PID       int                    `json:"pid"`
	TID       int                    `json:"tid"`
	Args      map[string]interface{} `json:"args,omitempty"`
	// contains filtered or unexported fields
}

A NormalEvent is the base class of all other Events.

func (*NormalEvent) Finalize

func (e *NormalEvent) Finalize()

Finalize marks this Event as having all its post-processing done.

type NullEventCollector

type NullEventCollector struct {
}

A NullEventCollector is an EventCollector that discards all the collected objects.

func (*NullEventCollector) Add

func (collector *NullEventCollector) Add(e Event) error

Add does nothing.

func (*NullEventCollector) Close added in v1.1.0

func (collector *NullEventCollector) Close() error

Close does nothing.

type ProblemSettings

type ProblemSettings struct {
	Cases       []GroupSettings      `json:"Cases"`
	Interactive *InteractiveSettings `json:"Interactive,omitempty"`
	Limits      LimitsSettings       `json:"Limits"`
	Slow        bool                 `json:"Slow"`
	Validator   ValidatorSettings    `json:"Validator"`
}

ProblemSettings represents the settings of a problem for a particular Input set.

type RefCounted

type RefCounted interface {
	Acquire()

	// Unfortunately, Go always invokes the methods of an embedded type with the
	// embedded type as the receiver (rather than the outer type), effectively
	// upcasting the pointer and losing the actual type. In order to avoid that,
	// we need to pass the Input again as a parameter.
	Release(Input)
}

RefCounted is the interface that provides reference-counted semantics.

Once the final reference has been released, the object is expected to release all resources.

type Run

type Run struct {
	AttemptID uint64   `json:"attempt_id"`
	Source    string   `json:"source"`
	Language  string   `json:"language"`
	InputHash string   `json:"input_hash"`
	MaxScore  *big.Rat `json:"max_score"`
	Debug     bool     `json:"debug"`
}

A Run represents an omegaUp run.

func (*Run) MarshalJSON added in v1.1.0

func (r *Run) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Run) String

func (r *Run) String() string

func (*Run) UnmarshalJSON added in v1.1.0

func (r *Run) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Run) UpdateAttemptID

func (r *Run) UpdateAttemptID() uint64

UpdateAttemptID assigns a new AttemptID to a run.

type RunnerConfig

type RunnerConfig struct {
	GraderURL           string
	RuntimePath         string
	CompileTimeLimit    Duration
	CompileOutputLimit  Byte
	ClrVMEstimatedSize  Byte
	JavaVMEstimatedSize Byte
	PreserveFiles       bool
}

RunnerConfig represents the configuration for the Runner.

type TLSConfig

type TLSConfig struct {
	CertFile string
	KeyFile  string
}

TLSConfig represents the configuration for TLS.

type TracingConfig

type TracingConfig struct {
	Enabled bool
	File    string
}

TracingConfig represents the configuration for tracing.

type V1Config

type V1Config struct {
	Enabled          bool
	Port             uint16
	RuntimeGradePath string
	RuntimePath      string
	SendBroadcast    bool
	UpdateDatabase   bool
}

V1Config represents the configuration for the V1-compatibility shim for the Grader.

type ValidatorSettings

type ValidatorSettings struct {
	Lang      *string         `json:"Lang,omitempty"`
	Name      string          `json:"Name"`
	Tolerance *float64        `json:"Tolerance,omitempty"`
	Limits    *LimitsSettings `json:"Limits,omitempty"`
}

ValidatorSettings represents the options used to validate outputs.

type WriterEventCollector

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

A WriterEventCollector is an EventCollector that writes its output to an io.Writer. It uses a sync.Mutex to synchronize events so that all writes are thread-safe.

func NewWriterEventCollector

func NewWriterEventCollector(output io.WriteCloser) *WriterEventCollector

NewWriterEventCollector returns a WriterEventCollector for a specified io.WriteCloser.

func (*WriterEventCollector) Add

func (collector *WriterEventCollector) Add(e Event) error

Add writes the specified event to the stream.

func (*WriterEventCollector) Close added in v1.1.0

func (collector *WriterEventCollector) Close() error

Close closes the underlying writer.

Jump to

Keyboard shortcuts

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