simulations

package
v0.0.0-...-70b330c Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2022 License: Apache-2.0 Imports: 76 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AWSErrCodeDryRunOperation is request when a request was a successful dry run that attempted to validate an
	// operation.
	AWSErrCodeDryRunOperation = "DryRunOperation"
	// AWSErrCodeRequestLimitExceeded is returned when too many requests sent to AWS in a short period of time.
	AWSErrCodeRequestLimitExceeded = "RequestLimitExceeded"
	// AWSErrCodeInsufficientInstanceCapacity is returned when not enough instances are available to fulfill the
	// request.
	AWSErrCodeInsufficientInstanceCapacity = "InsufficientInstanceCapacity"
	// AWSErrCodeServiceUnavailable is returned when the request has failed due to a temporary failure of the server.
	AWSErrCodeServiceUnavailable = "ServiceUnavailable"
	// AWSErrCodeUnavailable is returned when the  server is overloaded and can't handle the request.
	AWSErrCodeUnavailable = "Unavailable"
	// AWSErrCodeInternalFailure is returned when the request processing has failed because of an unknown error,
	// exception, or failure.
	AWSErrCodeInternalFailure = "InternalFailure"
	// AWSErrCodeInternalError is returned when an internal error has occurred.
	AWSErrCodeInternalError = "InternalError"
	// AWSErrCodeInsufficientReservedInstanceCapacity is returned when there are not enough available Reserved Instances
	// to satisfy your minimum request.
	AWSErrCodeInsufficientReservedInstanceCapacity = "InsufficientReservedInstanceCapacity"
	// AWSErrCodeInsufficientHostCapacity is returned when there is not enough capacity to fulfill your Dedicated Host request.
	AWSErrCodeInsufficientHostCapacity = "InsufficientHostCapacity"
	// AWSErrCodeInsufficientCapacity is returned when there is not enough capacity to fulfill your import instance request.
	AWSErrCodeInsufficientCapacity = "InsufficientCapacity"
	// AWSErrCodeInsufficientAddressCapacity is returned when not enough available addresses to satisfy your minimum request.
	AWSErrCodeInsufficientAddressCapacity = "InsufficientAddressCapacity"
)
View Source
const (
	CircuitNIOSHSRConfigA                 string = "NIOSH SR Config A"
	CircuitNIOSHSRConfigB                 string = "NIOSH SR Config B"
	CircuitNIOSHEXConfigA                 string = "NIOSH EX Config A"
	CircuitNIOSHEXConfigB                 string = "NIOSH EX Config B"
	CircuitVirtualStix                    string = "Virtual Stix"
	CircuitTunnelCircuit                  string = "Tunnel Circuit"
	CircuitTunnelPractice1                string = "Tunnel Practice 1"
	CircuitTunnelPractice2                string = "Tunnel Practice 2"
	CircuitTunnelPractice3                string = "Tunnel Practice 3"
	CircuitSimpleTunnel1                  string = "Simple Tunnel 1"
	CircuitSimpleTunnel2                  string = "Simple Tunnel 2"
	CircuitSimpleTunnel3                  string = "Simple Tunnel 3"
	CircuitTunnelCircuitWorld1            string = "Tunnel Circuit World 1"
	CircuitTunnelCircuitWorld2            string = "Tunnel Circuit World 2"
	CircuitTunnelCircuitWorld3            string = "Tunnel Circuit World 3"
	CircuitTunnelCircuitWorld4            string = "Tunnel Circuit World 4"
	CircuitTunnelCircuitWorld5            string = "Tunnel Circuit World 5"
	CircuitUrbanQual                      string = "Urban Qualification"
	CircuitUrbanSimple1                   string = "Urban Simple 1"
	CircuitUrbanSimple2                   string = "Urban Simple 2"
	CircuitUrbanSimple3                   string = "Urban Simple 3"
	CircuitUrbanPractice1                 string = "Urban Practice 1"
	CircuitUrbanPractice2                 string = "Urban Practice 2"
	CircuitUrbanPractice3                 string = "Urban Practice 3"
	CircuitUrbanCircuit                   string = "Urban Circuit"
	CircuitUrbanCircuitWorld1             string = "Urban Circuit World 1"
	CircuitUrbanCircuitWorld2             string = "Urban Circuit World 2"
	CircuitUrbanCircuitWorld3             string = "Urban Circuit World 3"
	CircuitUrbanCircuitWorld4             string = "Urban Circuit World 4"
	CircuitUrbanCircuitWorld5             string = "Urban Circuit World 5"
	CircuitUrbanCircuitWorld6             string = "Urban Circuit World 6"
	CircuitUrbanCircuitWorld7             string = "Urban Circuit World 7"
	CircuitUrbanCircuitWorld8             string = "Urban Circuit World 8"
	CircuitCaveSimple1                    string = "Cave Simple 1"
	CircuitCaveSimple2                    string = "Cave Simple 2"
	CircuitCaveSimple3                    string = "Cave Simple 3"
	CircuitCaveQual                       string = "Cave Qualification"
	CircuitCavePractice1                  string = "Cave Practice 1"
	CircuitCavePractice2                  string = "Cave Practice 2"
	CircuitCavePractice3                  string = "Cave Practice 3"
	CircuitCaveCircuit                    string = "Cave Circuit"
	CircuitCaveCircuitWorld1              string = "Cave Circuit World 1"
	CircuitCaveCircuitWorld2              string = "Cave Circuit World 2"
	CircuitCaveCircuitWorld3              string = "Cave Circuit World 3"
	CircuitCaveCircuitWorld4              string = "Cave Circuit World 4"
	CircuitCaveCircuitWorld5              string = "Cave Circuit World 5"
	CircuitCaveCircuitWorld6              string = "Cave Circuit World 6"
	CircuitCaveCircuitWorld7              string = "Cave Circuit World 7"
	CircuitCaveCircuitWorld8              string = "Cave Circuit World 8"
	CircuitFinalsQual                     string = "Finals Qualification"
	CircuitFinalsPractice1                string = "Finals Practice 1"
	CircuitFinalsPractice2                string = "Finals Practice 2"
	CircuitFinalsPractice3                string = "Finals Practice 3"
	CircuitVirtualStixCircuit             string = "Virtual Stix Circuit"
	CircuitVirtualStixCircuit2            string = "Virtual Stix Circuit 2"
	CircuitFinalsPreliminaryRound         string = "Finals Preliminary Round"
	CircuitFinalsPreliminaryRoundWorld1   string = "Finals Preliminary Round World 1"
	CircuitFinalsPreliminaryRoundWorld2   string = "Finals Preliminary Round World 2"
	CircuitFinalsPreliminaryRoundWorld3   string = "Finals Preliminary Round World 3"
	CircuitFinals                         string = "Final Prize Round"
	CircuitFinalsWorld1                   string = "Finals Prize Round World 1"
	CircuitFinalsWorld2                   string = "Finals Prize Round World 2"
	CircuitFinalsWorld3                   string = "Finals Prize Round World 3"
	CircuitFinalsWorld4                   string = "Finals Prize Round World 4"
	CircuitFinalsWorld5                   string = "Finals Prize Round World 5"
	CircuitFinalsWorld6                   string = "Finals Prize Round World 6"
	CircuitFinalsWorld7                   string = "Finals Prize Round World 7"
	CircuitFinalsWorld8                   string = "Finals Prize Round World 8"
	CircuitSystemsFinalsPreliminaryRound1 string = "Systems Finals Preliminary World 1"
	CircuitSystemsFinalsPreliminaryRound2 string = "Systems Finals Preliminary World 2"
	CircuitSystemsFinalsPrizeRound        string = "Systems Finals Prize Round"
	CircuitSubTPortalAccess               string = "SubT Portal Access"

	// Container names
	GazeboServerContainerName    string = "gzserver-container"
	CommsBridgeContainerName     string = "comms-bridge"
	FieldComputerContainerName   string = "field-computer"
	CopyToS3SidecarContainerName string = "copy-to-s3"
)

SubT Specifics constants

Variables

View Source
var (
	// ErrInvalidSeedID is returned when an invalid seed id is provided
	ErrInvalidSeedID = errors.New("invalid seed id")
	// ErrInvalidWorldID is returned when an invalid world id is provided
	ErrInvalidWorldID = errors.New("invalid world id")
)
View Source
var BillingRoutes = ign.Routes{
	ign.Route{
		Name:        "Get credits balance",
		Description: "Get credits balance of the current user",
		URI:         "/billing/credits",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "GET",
				Description: "Get credits balance",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(GetCreditsBalance)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Create payment session",
		Description: "Start a payment session",
		URI:         "/billing/session",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "POST",
				Description: "Create a payment session",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(CreateSession)),
					},
				},
			},
		},
	},
}

BillingRoutes contains the different routes for billing operations.

View Source
var (
	// CircuitSets contains a mapping between specific circuits and sets of circuits. Circuits in this map will pick
	// a single circuit from the set at random when launching the simulation.
	CircuitSets = map[string][]string{
		CircuitSubTPortalAccess: {
			CircuitUrbanQual,
			CircuitCaveQual,
			CircuitFinalsQual,
		},
	}
)
View Source
var CustomRuleTypes = []CustomRuleType{
	MaxSubmissions,
}

CustomRuleTypes contains the list of available rule types

View Source
var LaunchSimulation = func(s *Service, ctx context.Context,
	tx *gorm.DB, dep *SimulationDeployment) *ign.ErrMsg {

	if em := s.applications[*dep.Application].ValidateSimulationLaunch(ctx, tx, dep); em != nil {
		return em
	}

	groupID := *dep.GroupID
	s.queueLaunchRequest(groupID)
	return nil
}

LaunchSimulation receives a simulation deployment as an argument and pushes it to the launch queue.

View Source
var MonitoringRoutes = ign.Routes{

	ign.Route{
		Name:        "Cloudsim healthcheck",
		Description: "Get cloudsim status",
		URI:         "/healthz",
		Headers:     nil,
		Methods: ign.Methods{
			ign.Method{
				Type:        "GET",
				Description: "Get cloudsim status",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(Healthz),
					},
				},
			},
		},
		SecureMethods: ign.SecureMethods{},
	},
}

MonitoringRoutes contains the different routes used for service monitoring.

View Source
var ProfileRoutes = ign.Routes{
	ign.Route{
		Name:        "CPU Profile",
		Description: "Get cloudsim CPU profile data",
		URI:         "/profile",
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "GET",
				Description: "Get cloudsim CPU profile data",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   http.HandlerFunc(pprof.Profile),
					},
				},
			},
		},
	},
}

ProfileRoutes contains the different routes to perform CPU profiling.

View Source
var RegisterSchedulableTasks = func(s *Service, ctx context.Context, tx *gorm.DB) {
	for app := range s.GetApplications() {
		for _, task := range s.applications[app].GetSchedulableTasks(ctx, s, tx) {
			s.scheduler.DoAt(task.Fn, task.Date)
		}
	}
}

RegisterSchedulableTasks gets the tasks from each application and schedules them on the internal scheduler.

View Source
var Routes = ign.Routes{

	ign.Route{
		Name:        "Simulations",
		Description: "Information about all simulations",
		URI:         "/simulations",
		Headers:     ign.AuthHeadersRequired,
		Methods: ign.Methods{

			ign.Method{
				Type:        "GET",
				Description: "Get all simulations",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Extension: ".json", Handler: ign.JSONResult(WithUserOrAnonymous(CloudsimSimulationList))},
					ign.FormatHandler{Handler: ign.JSONResult(WithUserOrAnonymous(CloudsimSimulationList))},
				},
			},
		},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "POST",
				Description: "Starts a simulation, creating all needed resources",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResultNoTx(WithUser(CloudsimSimulationCreate))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Works with a single simulation based on its groupID",
		Description: "Single simulation based on its groupID",
		URI:         "/simulations/{group}",
		Headers:     ign.AuthHeadersRequired,
		Methods: ign.Methods{

			ign.Method{
				Type:        "GET",
				Description: "Get a single simulation based on its groupID",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResultNoTx(WithUserOrAnonymous(GetCloudsimSimulation))},
				},
			},
		},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "DELETE",
				Description: "shutdowns a simulation, removing all associated resources",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResultNoTx(WithUser(CloudsimSimulationDelete))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Launches a held simulation based on its groupID",
		Description: "Launches a held simulation based on its groupID",
		URI:         "/simulations/{group}/launch",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "POST",
				Description: "Launch a simulation that is being held",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(CloudsimSimulationLaunch))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Restarts a failed simulation based on its groupID",
		Description: "Restarts a failed simulation based on its groupID",
		URI:         "/simulations/{group}/restart",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "POST",
				Description: "Restart a failed simulation based on its groupID",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResult(WithUser(CloudsimSimulationRestart))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Get logs depending on the simulation status",
		Description: "Get file logs or live logs depending on the simulation status",
		URI:         "/simulations/{group}/logs",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "GET",
				Description: "Get logs from a simulation",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(SimulationLogGateway)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Live logs of a single simulation",
		Description: "Live logs of a single simulation",
		URI:         "/simulations/{group}/logs/live",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "GET",
				Description: "Get a live log",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResult(WithUser(SimulationLogLive))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Download the logs of a single simulation",
		Description: "Download the logs of a single simulation",
		URI:         "/simulations/{group}/logs/file",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "GET",
				Description: "Get a log file",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResultNoTx(WithUser(SimulationLogFileDownload))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Gets a simulation's websocket server address",
		Description: "Gets a simulation's websocket server address",
		URI:         "/simulations/{group}/websocket",
		Headers:     ign.AuthHeadersRequired,
		Methods: ign.Methods{

			ign.Method{
				Type:        "GET",
				Description: "Get a simulation's websocket server address and authorization token",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResultNoTx(WithUserOrAnonymous(SimulationWebsocketAddress))},
				},
			},
		},
		SecureMethods: ign.SecureMethods{},
	},

	ign.Route{
		Name:        "Reconnect websocket",
		Description: "Allow admins to reconnect a specific simulation to its respective websocket server",
		URI:         "/simulations/{group}/reconnect",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "POST",
				Description: "Reconnect websocket",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(ReconnectWebsocket)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Machines",
		Description: "Information about machines",
		URI:         "/machines",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "GET",
				Description: "Get all machines",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Extension: ".json", Handler: ign.JSONResult(WithUser(CloudMachineList))},
					ign.FormatHandler{Handler: ign.JSONResult(WithUser(CloudMachineList))},
				},
			},
		},
	},

	ign.Route{
		Name:        "RemainingSubmissions",
		Description: "Returns the number of remaining submissions for an owner in a circuit",
		URI:         "/{circuit}/remaining_submissions/{owner}",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "GET",
				Description: "Gets the number of remaining submissions in a circuit for an owner ",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResultNoTx(WithUser(GetRemainingSubmissions))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Rules",
		Description: "Gets the list of all circuit custom rules.",
		URI:         "/rules",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "GET",
				Description: "Gets the list of all circuit custom rules.",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResult(WithUser(CustomRuleList))},
					ign.FormatHandler{Extension: ".json", Handler: ign.JSONResult(WithUser(CustomRuleList))},
				},
			},
		},
	},

	ign.Route{
		Name:        "SetRule",
		Description: "Creates or updates a custom rule for an owner in a circuit.",
		URI:         "/rules/{circuit}/{owner}/{rule}/{value}",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "PUT",
				Description: "Creates or updates a custom rule for an owner in a circuit.",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResult(WithUser(SetCustomRule))},
				},
			},
		},
	},

	ign.Route{
		Name:        "DeleteRule",
		Description: "Deletes a custom rule for an owner in a circuit.",
		URI:         "/rules/{circuit}/{owner}/{rule}",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{

			ign.Method{
				Type:        "DELETE",
				Description: "Deletes a custom rule for an owner in a circuit.",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResult(WithUser(DeleteCustomRule))},
				},
			},
		},
	},

	ign.Route{
		Name:        "Competition robots",
		Description: "Gets the list of robots from the competition",
		URI:         "/competition/robots",
		Headers:     ign.AuthHeadersRequired,
		Methods: ign.Methods{

			ign.Method{
				Type:        "GET",
				Description: "Gets the list of robots from the competition",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{Handler: ign.JSONResult(WithUserOrAnonymous(GetCompetitionRobots))},
					ign.FormatHandler{Extension: ".json", Handler: ign.JSONResult(WithUserOrAnonymous(GetCompetitionRobots))},
				},
			},
		},
		SecureMethods: ign.SecureMethods{},
	},

	ign.Route{
		Name:        "Get all elements from queue",
		Description: "Get all elements from queue. This route should optionally be able to handle pagination parameters.",
		URI:         "/queue",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "GET",
				Description: "Get all elements from queue. This route should optionally be able to handle pagination parameters",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(QueueGet)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Count elements in the queue",
		Description: "Get the amount of elements in the queue",
		URI:         "/queue/count",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "GET",
				Description: "Get the amount of elements in the queue",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(QueueCount)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Swap queue elements moving A to B and vice versa",
		Description: "Swap queue elements moving A to B and vice versa",
		URI:         "/queue/{groupIDA}/swap/{groupIDB}",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "PATCH",
				Description: "Swap queue elements moving A to B and vice versa",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(QueueSwap)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Move an element to the front of the queue",
		Description: "Move an element to the front of the queue",
		URI:         "/queue/{groupID}/move/front",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "PATCH",
				Description: "Move an element to the front of the queue",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(QueueMoveToFront)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Move an element to the back of the queue",
		Description: "Move an element to the back of the queue",
		URI:         "/queue/{groupID}/move/back",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "PATCH",
				Description: "Move an element to the back of the queue",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(QueueMoveToBack)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Remove an element from the queue",
		Description: "Remove an element from the queue",
		URI:         "/queue/{groupID}",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "DELETE",
				Description: "Remove an element from the queue",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(QueueRemove)),
					},
				},
			},
		},
	},

	ign.Route{
		Name:        "Debug",
		Description: "Debug multi region support",
		URI:         "/debug/{groupID}",
		Headers:     ign.AuthHeadersRequired,
		Methods:     ign.Methods{},
		SecureMethods: ign.SecureMethods{
			ign.Method{
				Type:        "GET",
				Description: "Debug websocket messages",
				Handlers: ign.FormatHandlers{
					ign.FormatHandler{
						Extension: "",
						Handler:   ign.JSONResult(WithUser(Debug)),
					},
				},
			},
		},
	},
}

Routes declares the routes related to simulations. See also IGN's router.go

View Source
var Sleep = func(d time.Duration) {
	time.Sleep(d)
}

Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately. Dev note: we redefine the Sleep function here to allow mocking during testing.

View Source
var SubTCircuits = []string{
	CircuitNIOSHSRConfigA,
	CircuitNIOSHSRConfigB,
	CircuitNIOSHEXConfigA,
	CircuitNIOSHEXConfigB,
	CircuitVirtualStix,
	CircuitTunnelPractice1,
	CircuitTunnelPractice2,
	CircuitTunnelPractice3,
	CircuitSimpleTunnel1,
	CircuitSimpleTunnel2,
	CircuitSimpleTunnel3,
	CircuitTunnelCircuitWorld1,
	CircuitTunnelCircuitWorld2,
	CircuitTunnelCircuitWorld3,
	CircuitTunnelCircuitWorld4,
	CircuitTunnelCircuitWorld5,
	CircuitUrbanQual,
	CircuitUrbanSimple1,
	CircuitUrbanSimple2,
	CircuitUrbanSimple3,
	CircuitUrbanPractice1,
	CircuitUrbanPractice2,
	CircuitUrbanPractice3,
	CircuitUrbanCircuitWorld1,
	CircuitUrbanCircuitWorld2,
	CircuitUrbanCircuitWorld3,
	CircuitUrbanCircuitWorld4,
	CircuitUrbanCircuitWorld5,
	CircuitUrbanCircuitWorld6,
	CircuitUrbanCircuitWorld7,
	CircuitUrbanCircuitWorld8,
	CircuitCaveSimple1,
	CircuitCaveSimple2,
	CircuitCaveSimple3,
	CircuitCaveQual,
	CircuitCavePractice1,
	CircuitCavePractice2,
	CircuitCavePractice3,
	CircuitCaveCircuit,
	CircuitCaveCircuitWorld1,
	CircuitCaveCircuitWorld2,
	CircuitCaveCircuitWorld3,
	CircuitCaveCircuitWorld4,
	CircuitCaveCircuitWorld5,
	CircuitCaveCircuitWorld6,
	CircuitCaveCircuitWorld7,
	CircuitCaveCircuitWorld8,
	CircuitFinalsQual,
	CircuitFinalsPractice1,
	CircuitFinalsPractice2,
	CircuitFinalsPractice3,
	CircuitVirtualStixCircuit,
	CircuitVirtualStixCircuit2,
	CircuitFinalsPreliminaryRound,
	CircuitFinalsPreliminaryRoundWorld1,
	CircuitFinalsPreliminaryRoundWorld2,
	CircuitFinalsPreliminaryRoundWorld3,
	CircuitFinals,
	CircuitFinalsWorld1,
	CircuitFinalsWorld2,
	CircuitFinalsWorld3,
	CircuitFinalsWorld4,
	CircuitFinalsWorld5,
	CircuitFinalsWorld6,
	CircuitFinalsWorld7,
	CircuitFinalsWorld8,
	CircuitSystemsFinalsPreliminaryRound1,
	CircuitSystemsFinalsPreliminaryRound2,
	CircuitSystemsFinalsPrizeRound,
	CircuitSubTPortalAccess,
}

SubTCircuits holds the list of available circuits in SubT.

SubTCompetitionCircuits is the list of circuits that are used for competitions.

View Source
var SubTRobotTypes map[string]SubTRobotType

SubTRobotTypes holds the list of available robot types

Functions

func AWSErrorIsRetryable

func AWSErrorIsRetryable(err awserr.Error) bool

AWSErrorIsRetryable checks that an error returned by an AWS operation is non-fatal and can be retried. This is related to operations requesting limited resources on AWS.

func CloudMachineList

func CloudMachineList(user *users.User, tx *gorm.DB,
	w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CloudMachineList returns a list with cloud machines (eg. ec2 instances). You can request this method with the following cURL request:

curl -k -X GET --url http://localhost:8001/1.0/machines
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func CloudsimSimulationCreate

func CloudsimSimulationCreate(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CloudsimSimulationCreate is the main func to launch a new simulation You can request this method with the following cURL request:

curl -k -X POST --url http://localhost:8001/1.0/simulations
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func CloudsimSimulationDelete

func CloudsimSimulationDelete(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CloudsimSimulationDelete finishes all resources associated to a cloudsim simulation. (eg. Nodes, Hosts, Pods) You can request this method with the following cURL request:

curl -k -X DELETE --url http://localhost:8001/1.0/simulations/{group}
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func CloudsimSimulationLaunch

func CloudsimSimulationLaunch(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CloudsimSimulationLaunch launches a held simulation. You can request this method with the following cURL request:

curl -k -X POST --url http://localhost:8001/1.0/simulations/{group}/launch
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func CloudsimSimulationList

func CloudsimSimulationList(user *users.User, tx *gorm.DB,
	w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CloudsimSimulationList returns a list with simulation deployments. You can request this method with the following cURL request:

curl -k -X GET --url http://localhost:8001/1.0/simulations
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func CloudsimSimulationRestart

func CloudsimSimulationRestart(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CloudsimSimulationRestart restarts a failed single simulation. You can request this method with the following cURL request:

curl -k -X POST --url http://localhost:8001/1.0/simulations/{group}/restart
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func CreateSession

func CreateSession(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CreateSession starts a payment session with the payments service for the current user.

func CustomRuleList

func CustomRuleList(user *users.User, tx *gorm.DB,
	w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

CustomRuleList returns a paginated list of circuit custom rules, filtering by circuit, owner or rule. This operation can only be performed by a system or application administrator. GET parameters include: application, circuit, owner and rule_type. You can request this method with the following cURL request:

curl -k -X GET --url http://localhost:8001/1.0/rules
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func Debug

func Debug(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

Debug is a debug endpoint to get internal state information about a simulation.

func DeleteCustomRule

func DeleteCustomRule(user *users.User, tx *gorm.DB, w http.ResponseWriter,
	r *http.Request) (interface{}, *ign.ErrMsg)

DeleteCustomRule deletes a custom rule for an owner in a circuit. You can request this method with the following cURL request:

curl -k -X DELETE --url http://localhost:8000/1.0/rules/{circuit}/{owner}/{rule}
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func EnvVarToSlice

func EnvVarToSlice(envVar string) []string

EnvVarToSlice reads the contents of an environment variable and splits it into an array of strings using comma as the separator.

func ErrorMessage

func ErrorMessage(err SimErrCode) ign.ErrMsg

ErrorMessage receives an error code and generate an error message response

func GetCloudsimSimulation

func GetCloudsimSimulation(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

GetCloudsimSimulation returns a single simulation. You can request this method with the following cURL request:

curl -k -X GET --url http://localhost:8000/1.0/simulations/{group}
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func GetCompetitionRobots

func GetCompetitionRobots(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

GetCompetitionRobots returns an array of robots for the competition.

func GetCreditsBalance

func GetCreditsBalance(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

GetCreditsBalance gets the credit balance of the current user.

func GetKubernetesClient

func GetKubernetesClient(kubeconfig *string) (*kubernetes.Clientset, error)

GetKubernetesClient returns a client object to access a kubernetes master. Note that this kube client assumes there is a kubernetes configuration in the server's ~/.kube/config file. That config is used to connect to the kubernetes master.

func GetKubernetesConfig

func GetKubernetesConfig(kubeconfig *string) (*restclient.Config, error)

GetKubernetesConfig returns the kubernetes config file in the specified path. If no path is provided (i.e. nil), then the configuration in ~/.kube/config is returned.

func GetPendingCircuitRules

func GetPendingCircuitRules(tx *gorm.DB) (*[]SubTCircuitRules, error)

GetPendingCircuitRules gets a list of circuits that are scheduled for competition

func GetRemainingSubmissions

func GetRemainingSubmissions(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

GetRemainingSubmissions returns the number of remaining submissions for an owner in a circuit. You can request this method with the following cURL request:

curl -k -X GET --url http://localhost:8000/1.0/{circuit}/remaining_submissions/{owner}
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func GetS3SimulationLogKey

func GetS3SimulationLogKey(dep *SimulationDeployment) string

GetS3SimulationLogKey returns the key where logs for a given simulation are stored within a bucket.

func Healthz

func Healthz(tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

Healthz returns a string to confirm that cloudsim is running.

curl -k -X GET --url http://localhost:8001/1.0/healthz

func InstallSimulationCustomValidators

func InstallSimulationCustomValidators(validate *validator.Validate)

InstallSimulationCustomValidators extends validator.v9 with custom validation functions and meta tags for simulations.

func InstallSubTCustomValidators

func InstallSubTCustomValidators(validate *validator.Validate)

InstallSubTCustomValidators extends validator.v9 with custom validation functions and meta tags for SubT simulations.

func IsCompetitionCircuit

func IsCompetitionCircuit(circuit string) bool

IsCompetitionCircuit checks if the given circuit is a competition circuit. This is used to check if the given circuit is a Tunnel, Urban or Cave circuit.

func IsOwnerQualifiedForCircuit

func IsOwnerQualifiedForCircuit(tx *gorm.DB, owner, circuit string, username string) bool

IsOwnerQualifiedForCircuit returns true when an owner is qualified for certain circuit In any other cases, it returns false.

func IsWebsocketAddress

func IsWebsocketAddress(addr string, groupID *string) bool

IsWebsocketAddress checks that the given address is a valid websocket address for cloudsim. If a groupID is provided, it will check that the given address includes a group ID.

func MarkPreviousSubmissionsSuperseded

func MarkPreviousSubmissionsSuperseded(tx *gorm.DB, groupID, owner, circuit string) error

MarkPreviousSubmissionsSuperseded marks a set of submissions with the simSuperseded status.

func Max

func Max(x, y int) int

Max returns the maximum value between two ints.

func Min

func Min(x, y int) int

Min returns the minimum value between two ints.

func NewErrorMessage

func NewErrorMessage(err SimErrCode) *ign.ErrMsg

NewErrorMessage is a convenience function that receives an error code and returns a pointer to an ErrMsg.

func NewErrorMessageWithBase

func NewErrorMessageWithBase(err SimErrCode, base error) *ign.ErrMsg

NewErrorMessageWithBase receives an error code and a root error and returns a pointer to an ErrMsg.

func NewSubTSimulationServiceAdaptor

func NewSubTSimulationServiceAdaptor(db *gorm.DB) simulations.Service

NewSubTSimulationServiceAdaptor initializes a new simulations.Service implementation using the SimulationServiceAdaptor.

func NewTracksService

func NewTracksService(db *gorm.DB, logger ign.Logger) tracks.Service

NewTracksService initializes a new tracks.Service implementation using subTCircuitService.

func ParseStruct

func ParseStruct(s interface{}, r *http.Request, isForm bool) *ign.ErrMsg

ParseStruct reads the http request and decodes sent values into the given struct. It uses the isForm bool to know if the values comes as "request.Form" values or as "request.Body". It also calls validator to validate the struct fields.

func QueueCount

func QueueCount(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

QueueCount returns the launch queue elements count

curl -k -X GET --url http://localhost:8001/1.0/simulations/queue/count
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func QueueGet

func QueueGet(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

QueueGet returns all the simulations from the launch queue If the url query includes `page` and `page_size` as parameters then this handler will return a paginated list of elements given by those values.

curl -k -X GET --url http://localhost:8001/1.0/simulations/queue
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func QueueMoveToBack

func QueueMoveToBack(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

QueueMoveToBack moves the element to the back of the queue.

curl -k -X PATCH --url http://localhost:8001/1.0/simulations/queue/{groupID}/move/back
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func QueueMoveToFront

func QueueMoveToFront(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

QueueMoveToFront moves the element to the front of the queue.

curl -k -X PATCH --url http://localhost:8001/1.0/simulations/queue/{groupID}/move/front
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func QueueRemove

func QueueRemove(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

QueueRemove removes an element from the queue.

curl -k -X DELETE --url http://localhost:8001/1.0/simulations/queue/{groupID}
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func QueueSwap

func QueueSwap(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

QueueSwap swaps elements from position A to position B and vice versa

curl -k -X PATCH --url http://localhost:8001/1.0/simulations/queue/{groupIDA}/swap/{groupIDB}
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func ReconnectWebsocket

func ReconnectWebsocket(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

ReconnectWebsocket is the endpoint that reconnects a simulation to its respective websocket server

func SendSimulationSummaryEmail

func SendSimulationSummaryEmail(e email.Sender, dep *SimulationDeployment, summary AggregatedSubTSimulationValues,
	runData *string) *ign.ErrMsg

SendSimulationSummaryEmail sends a summary email to the user that created the simulation `summary` contains summary information for the run. It should be passed for all types of simulation. `runData` contains specific simulation run information. It should only be passed for single sims.

func SetCustomRule

func SetCustomRule(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

SetCustomRule creates or updates a custom rule for an owner in a circuit. You can request this method with the following cURL request:

curl -k -X PUT --url http://localhost:8000/1.0/rules/{circuit}/{owner}/{rule}/{value}
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func SimulationLogFileDownload

func SimulationLogFileDownload(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

SimulationLogFileDownload downloads a simulation's logs. If the url query includes `link=true` as parameter then this handler will return the download URL as a string result instead of doing an http redirect. If the url query includes `robot` as parameter with the name of a robot in the simulation and the request is for a single simulation, then this will return the ROS logs for a specific robot in the simulation. You can request this method with the following curl request:

curl -k -X GET --url http://localhost:8001/1.0/simulations/{group}/logs/file?link=true
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func SimulationLogGateway

func SimulationLogGateway(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

SimulationLogGateway returns a URL and a boolean that represent the URL to the proper logs and if it's a file or not. If the simulation is running, it will return an URL for live logs and the boolean will be false. If the simulation is stopped, it will return an URL for downloadable logs and the boolean will be true. You can request this method with the following curl request:

curl -k -X GET --url http://localhost:8001/1.0/simulations/{group}/logs/
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func SimulationLogLive

func SimulationLogLive(user *users.User, tx *gorm.DB, w http.ResponseWriter, r *http.Request) (interface{}, *ign.ErrMsg)

SimulationLogLive returns a log from a running simulation. If the url query includes `lines=N` as parameter, and the request is for a single simulation then this handler will return the last N lines of logs from a live simulation. If the url query includes `robot` as parameter with the name of a robot in the simulation and the request is for a single simulation, then this will return the ROS logs for a specific robot in the simulation. If the simulation has been launched as a multisim, it will return a summary of all finished children in the multisim. You can request this method with the following curl request:

curl -k -X GET --url http://localhost:8001/1.0/simulations/{group}/logs/live?lines=200
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func SimulationWebsocketAddress

func SimulationWebsocketAddress(user *users.User, tx *gorm.DB, w http.ResponseWriter,
	r *http.Request) (interface{}, *ign.ErrMsg)

SimulationWebsocketAddress returns the address of the websocket server and authorization token for the specified running simulation. This address and token are meant to be used by the client to establish a websocket connection with the simulation to get real-time simulation information. A simulation's websocket server is only available while a simulation is running. If a simulation is not running, an error will be returned as the websocket server will no longer be available. You can request this method with the following curl request:

curl -k -X GET --url http://localhost:8001/1.0/simulations/{group}/websocket
  --header 'authorization: Bearer <A_VALID_AUTH0_JWT_TOKEN>'

func SliceToStr

func SliceToStr(slice []string) string

SliceToStr joins the elements of a string array using comma as the separator.

func StrSliceContains

func StrSliceContains(val string, list []string) bool

StrSliceContains determines if val is contained within list.

func StrToIntSlice

func StrToIntSlice(str string) ([]int, error)

StrToIntSlice converts a string to an array of ints, where each element is a section of the complete number.

func UploadToS3Bucket

func UploadToS3Bucket(s3Svc s3iface.S3API, bucket *string, key *string, file []byte) (*s3.PutObjectOutput, error)

UploadToS3Bucket uploads a file to a bucket in a certain key.

func ValidateStruct

func ValidateStruct(s interface{}) *ign.ErrMsg

ValidateStruct Validate struct values using golang validator.v9

func WithUser

func WithUser(handler handlerWithUser) ign.HandlerWithResult

WithUser is a middleware that checks for a valid user from the JWT and passes the user to the handlerWithUser. If the user is not present or invalid, an error is returned.

func WithUserOrAnonymous

func WithUserOrAnonymous(handler handlerWithUser) ign.HandlerWithResult

WithUserOrAnonymous is a middleware that checks for a valid user from the JWT and passes the user to the handlerWithUser. If the user is not present or invalid, a nil user is passed.

Types

type AWSFactory

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

AWSFactory is the single place where all AWS service instances are created.

func NewAWSFactory

func NewAWSFactory(isGoTest bool) *AWSFactory

NewAWSFactory creates a new AWSFactory

func (*AWSFactory) NewEC2Svc

func (f *AWSFactory) NewEC2Svc(p client.ConfigProvider, cfgs ...*aws.Config) ec2iface.EC2API

NewEC2Svc creates a new instance of the EC2 client with a session. If additional configuration is needed for the client instance use the optional aws.Config parameter to add your extra config.

func (*AWSFactory) NewS3Svc

func (f *AWSFactory) NewS3Svc(p client.ConfigProvider, cfgs ...*aws.Config) s3iface.S3API

NewS3Svc creates a new instance of the S3 client with a session. If additional configuration is needed for the client instance use the optional aws.Config parameter to add your extra config.

type AggregatedSubTSimulationValues

type AggregatedSubTSimulationValues struct {
	Score                  float64 `json:"-"`
	SimTimeDurationAvg     float64 `json:"sim_time_duration_avg"`
	SimTimeDurationStdDev  float64 `json:"sim_time_duration_std_dev"`
	RealTimeDurationAvg    float64 `json:"real_time_duration_avg"`
	RealTimeDurationStdDev float64 `json:"real_time_duration_std_dev"`
	ModelCountAvg          float64 `json:"model_count_avg"`
	ModelCountStdDev       float64 `json:"model_count_std_dev"`
	Sources                string  `json:"-"`
}

AggregatedSubTSimulationValues contains the total score and average statistics of a group of simulation deployments. These simulations are typically all the child simulations of a multi-sim.

func GetAggregatedSubTSimulationValues

func GetAggregatedSubTSimulationValues(tx *gorm.DB, simDep *SimulationDeployment) (*AggregatedSubTSimulationValues, error)

GetAggregatedSubTSimulationValues returns the total score and average and standard deviation of a group of simulations.

type ApplicationType

type ApplicationType interface {
	GetSchedulableTasks(ctx context.Context, s *Service, tx *gorm.DB) []SchedulableTask

	ValidateSimulationLaunch(ctx context.Context, tx *gorm.DB, dep *SimulationDeployment) *ign.ErrMsg
	// contains filtered or unexported methods
}

ApplicationType represents an Application (eg. SubT). Applications are used to customize launched Simulations.

type CircuitCustomRule

type CircuitCustomRule struct {
	gorm.Model
	Owner    *string        `json:"owner"`
	Circuit  *string        `json:"circuit" validate:"iscircuit"`
	RuleType CustomRuleType `gorm:"not null" json:"rule_type" validate:"isruletype"`
	Value    string         `gorm:"not null" json:"value"`
}

CircuitCustomRule holds custom rules for a specific combination of owner (user or organization) or circuit. Rules contain arbitrary values that can be used to configure specific aspects of a circuit/application (e.g. max_submissions - A custom rule for a specific owner to allow for extra submissions in a specific circuit). Rules for several owners or circuits can be defined by creating rules with NULL values in either fields. Rules with NULL values have less priority than rules with values, with the following priority: owner, circuit. This means that a rule with NULL circuit and owner will apply to ALL circuits for ALL owners, but any rule with either circuit or owner will override this general rule.

func GetCircuitCustomRule

func GetCircuitCustomRule(tx *gorm.DB, circuit string, owner string, rule CustomRuleType) (*CircuitCustomRule, error)

GetCircuitCustomRule returns the rule value for a specific circuit and owner.

type CircuitCustomRules

type CircuitCustomRules []CircuitCustomRule

CircuitCustomRules is a slice of CircuitCustomRule

type CreateSimulation

type CreateSimulation struct {
	// TODO Reenable notinblacklist validator for Name
	Name  string `json:"name" validate:"required,min=3,alphanum" form:"name"`
	Owner string `json:"owner" form:"owner"`
	// The docker image(s) that will be used for the Field Computer(s)
	Image       []string `json:"image" form:"image"`
	Platform    *string  `json:"platform" form:"platform"`
	Application string   `json:"application" form:"application"`
	Private     *bool    `json:"private" validate:"omitempty" form:"private"`
	// When shutting down simulations, stop EC2 instances instead of terminating them. Requires admin privileges.
	StopOnEnd *bool `json:"stop_on_end" validate:"omitempty" form:"stop_on_end"`
	// Extra: it is expected that this field will be set by the Application logic
	// and not From form values.
	Extra *string `form:"-"`
	// ExtraSelector: it is expected that this field will be set by the Application logic
	// and not from Form values.
	ExtraSelector *string `form:"-"`
	// TODO: This is a field specific to SubT. As such this is a temporary field
	//  that should be included in the same separate table where Extra and
	//  ExtraSelector should reside.
	// Contains the names of all robots in the simulation in a comma-separated list.
	Robots *string `form:"-"`
}

CreateSimulation contains information about a simulation creation request.

type CustomRuleType

type CustomRuleType string

CustomRuleType defines the type for circuit custom rules

const (
	// Maximum number of submissions allowed for a specific circuit
	MaxSubmissions CustomRuleType = "max_submissions"
)

List of rule types

type DeploymentStatus

type DeploymentStatus int

DeploymentStatus are the possible status values of SimulationDeployments

func DeploymentStatusFrom

func DeploymentStatusFrom(str string) *DeploymentStatus

DeploymentStatusFrom returns the DeploymentStatus value corresponding to the given string. It will return nil if not found.

func (DeploymentStatus) Eq

func (ds DeploymentStatus) Eq(st int) bool

Eq function will compare for equality with an int based Status.

func (DeploymentStatus) String

func (ds DeploymentStatus) String() string

String function will return the string version of the status.

func (DeploymentStatus) ToInt

func (ds DeploymentStatus) ToInt() int

ToInt returns the int value of this status value.

func (DeploymentStatus) ToPtr

func (ds DeploymentStatus) ToPtr() *int

ToPtr returns a pointer to int of this status value

type ErrorStatus

type ErrorStatus string

ErrorStatus are possible status values of SimulationDeployment ErrorStatus field.

func ErrorStatusFrom

func ErrorStatusFrom(str string) *ErrorStatus

ErrorStatusFrom returns the ErrorStatus value corresponding to the given string. It will return nil if not found.

func (ErrorStatus) ToStringPtr

func (es ErrorStatus) ToStringPtr() *string

ToStringPtr returns a pointer to string of this status value

type ExtraInfoSubT

type ExtraInfoSubT struct {
	Circuit    string          `json:"circuit,omitempty"`
	WorldIndex *int            `json:"world_index,omitempty"`
	Robots     []SubTRobot     `json:"robots,omitempty"`
	Marsupials []SubTMarsupial `json:"marsupials,omitempty"`
	// Which "simulation run" number is this? It is computed based on the number of worlds in the circuit and
	// how many time to run them. For multiSims, the RunIndex can be seen as the child index.
	RunIndex *int `json:"run_index,omitempty"`
}

ExtraInfoSubT is a struct use to hold the Extra information added by SubT to SimulationDeployments DB records. If new internal fields are added, they should be removed inside GetSimulationDeployment() method.

func ReadExtraInfoSubT

func ReadExtraInfoSubT(dep *SimulationDeployment) (*ExtraInfoSubT, error)

ReadExtraInfoSubT reads the ExtraInfoSubT from a given simulation deployment.

func (*ExtraInfoSubT) ToJSON

func (e *ExtraInfoSubT) ToJSON() (*string, error)

ToJSON marshals an ExtraInfoSubT into a json string.

type HTTPHandler

type HTTPHandler struct {
	UserAccessor useracc.Service
}

HTTPHandler is used to invoke inner logic based on incoming Http requests.

var HTTPHandlerInstance *HTTPHandler

HTTPHandlerInstance is the default HTTPHandler instance. It is used by routes.go.

func NewHTTPHandler

func NewHTTPHandler(ctx context.Context, ua useracc.Service) (*HTTPHandler, error)

NewHTTPHandler creates a new HTTPHandler.

type JobPool

type JobPool interface {
	Serve(args interface{}) error
}

JobPool is a pool of Jobs that can accept jobs to be executed. For more details see project "github.com/panjf2000/ants".

func SynchronicPoolFactory

func SynchronicPoolFactory(poolSize int, jobF func(interface{})) (JobPool, error)

SynchronicPoolFactory is a Factory function that creates a new SynchronicPool using the given arguments.

type K8Factory

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

K8Factory is the single place where K8 instances are created.

func NewK8Factory

func NewK8Factory(isGoTest, connectToCloudServices bool) *K8Factory

NewK8Factory creates a new K8 factory

func (*K8Factory) NewK8

NewK8 creates a new instance of Kubernetes client.

type LocalNodes

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

LocalNodes is a client to interact with a local k8 cluster

func NewLocalNodesClient

func NewLocalNodesClient(ctx context.Context, kcli kubernetes.Interface) (*LocalNodes, error)

NewLocalNodesClient creates a client to interact with a local k8 cluster and set of machines.

func (*LocalNodes) CloudMachinesList

func (s *LocalNodes) CloudMachinesList(ctx context.Context, p *ign.PaginationRequest,
	tx *gorm.DB, byStatus *MachineStatus, invertStatus bool, groupID *string, application *string) (*MachineInstances, *ign.PaginationResult, *ign.ErrMsg)

CloudMachinesList returns a paginated list with all cloud machines. In the local impl we just return an empty set (for now). @public

type LogGateway

type LogGateway struct {
	Path   string `json:"path"`
	IsFile bool   `json:"is_file"`
}

LogGateway describes a response from the logs gateway handler.

type MachineInstance

type MachineInstance struct {
	ID        uint       `gorm:"primary_key" json:"-"`
	CreatedAt time.Time  `gorm:"type:timestamp(3) NULL" json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `gorm:"type:timestamp(2) NULL" sql:"index" json:"-"`

	InstanceID      *string `json:"instance_id" gorm:"not null;unique"`
	LastKnownStatus *string `json:"status,omitempty"`
	// Cloudsim Group Id
	GroupID *string `json:"group_id"`
	// Applicaton to which this machine belongs to
	Application *string `json:"application,omitempty"`
}

MachineInstance is a host/instance launched by Cloudsim. This structure is used by the ec2_machines module

func GetMachine

func GetMachine(tx *gorm.DB, instanceID string) (*MachineInstance, error)

GetMachine gets a machine instance record by its instanceID Fails if not found.

type MachineInstances

type MachineInstances []MachineInstance

MachineInstances is a MachineInstance slice

type MachineStatus

type MachineStatus string

MachineStatus is a status of Host machines/instances

func MachineStatusFrom

func MachineStatusFrom(str string) *MachineStatus

MachineStatusFrom returns the MachineStatus value corresponding to the given string. It will return nil if not found.

func (MachineStatus) ToStringPtr

func (ms MachineStatus) ToStringPtr() *string

ToStringPtr returns a pointer to string of this status value

type MockService

type MockService struct {
}

MockService implements the functions defined for the SimService interface, but prevents cloud instances from starting.

func (*MockService) CustomizeSimRequest

func (s *MockService) CustomizeSimRequest(ctx context.Context, r *http.Request, createSim *CreateSimulation) *ign.ErrMsg

CustomizeSimRequest allows registered Applications to customize the incoming CreateSimulation request. Eg. reading specific SubT fields.

func (*MockService) DeleteNodesAndHostsForGroup

func (s *MockService) DeleteNodesAndHostsForGroup(ctx context.Context,
	tx *gorm.DB, dep *SimulationDeployment, user *users.User) (interface{}, *ign.ErrMsg)

DeleteNodesAndHostsForGroup starts the shutdown of all the kubernates nodes and associated Hosts (instances) of a given Cloudsim Group Id.

func (*MockService) GetCloudMachineInstances

func (s *MockService) GetCloudMachineInstances(ctx context.Context, p *ign.PaginationRequest,
	tx *gorm.DB, byStatus *MachineStatus, invertStatus bool, user *users.User,
	owner *string, application *string) (*MachineInstances, *ign.PaginationResult, *ign.ErrMsg)

GetCloudMachineInstances returns a paginated list with all cloud instances.

func (*MockService) GetSimulationDeployment

func (s *MockService) GetSimulationDeployment(ctx context.Context, tx *gorm.DB,
	groupID string, user *users.User) (interface{}, *ign.ErrMsg)

GetSimulationDeployment returns a single simulation deployment based on its groupID

func (*MockService) GetSimulationLogsForDownload

func (s *MockService) GetSimulationLogsForDownload(ctx context.Context, tx *gorm.DB,
	groupID string, user *users.User) (*string, *ign.ErrMsg)

GetSimulationLogsForDownload returns the generated logs from a simulation.

func (*MockService) RegisterApplication

func (s *MockService) RegisterApplication(ctx context.Context, app ApplicationType)

RegisterApplication registers a new application type.

func (*MockService) ShutdownSimulationAsync

func (s *MockService) ShutdownSimulationAsync(ctx context.Context, tx *gorm.DB,
	groupID string, user *users.User) (interface{}, *ign.ErrMsg)

ShutdownSimulationAsync finishes all resources associated to a cloudsim simulation.

func (*MockService) SimulationDeploymentList

func (s *MockService) SimulationDeploymentList(ctx context.Context,
	p *ign.PaginationRequest, tx *gorm.DB, byStatus *DeploymentStatus,
	invertStatus bool, byErrStatus *ErrorStatus, invertErrStatus bool,
	user *users.User, owner *string, application *string, includeChildren bool) (*SimulationDeployments, *ign.PaginationResult, *ign.ErrMsg)

SimulationDeploymentList returns a paginated list with all cloudsim simulations

func (*MockService) Start

func (s *MockService) Start(ctx context.Context) error

Start starts this simulation service

func (*MockService) StartSimulationAsync

func (s *MockService) StartSimulationAsync(ctx context.Context,
	tx *gorm.DB, createSim *CreateSimulation, user *users.User) (interface{}, *ign.ErrMsg)

StartSimulationAsync is the main func to launch a new simulation

func (*MockService) Stop

func (s *MockService) Stop(ctx context.Context) error

Stop stops this simulation service

type MockableClientset

type MockableClientset struct {
	kubernetes.Interface
}

MockableClientset is a type used in tests to allow for easy mocking of Kubernetes clientset.

func AssertMockedClientset

func AssertMockedClientset(cli kubernetes.Interface) *MockableClientset

AssertMockedClientset casts the given arg to MockableClientset or fails.

func (*MockableClientset) SetImpl

func (m *MockableClientset) SetImpl(cli kubernetes.Interface)

SetImpl sets the underlying implementation of this MockableClientset

type MockableEC2

type MockableEC2 struct {
	ec2iface.EC2API
}

MockableEC2 is a type used in tests to allow for easy mocking of EC2 operations.

func AssertMockedEC2

func AssertMockedEC2(svc ec2iface.EC2API) *MockableEC2

AssertMockedEC2 casts the given arg to MockableEC2 or fails.

func (*MockableEC2) SetImpl

func (m *MockableEC2) SetImpl(svc ec2iface.EC2API)

SetImpl sets the underlying implementation of this MockableEC2

type MockableS3

type MockableS3 struct {
	s3iface.S3API
}

MockableS3 is a type used in tests to allow for easy mocking of S3 service.

func EnsureMockableS3

func EnsureMockableS3(svc s3iface.S3API) *MockableS3

EnsureMockableS3 casts the given arg to MockableS3 or fails.

type MultiSimType

type MultiSimType int

MultiSimType represents which rol plays a simulation within a multiSim deployment

type NodeManager

type NodeManager interface {
	CloudMachinesList(ctx context.Context, p *ign.PaginationRequest,
		tx *gorm.DB, byStatus *MachineStatus, invertStatus bool, groupID *string, application *string) (*MachineInstances, *ign.PaginationResult, *ign.ErrMsg)
	// contains filtered or unexported methods
}

NodeManager is responsible of creating and removing cloud instances, and kubernetes nodes. NodeManager is the expected interface to be implemented by Cloudsim NodeManagers. Example implementations can be found in `ec2_machines.go` and `local_machines.go`.

type PlatformType

type PlatformType interface {
	// contains filtered or unexported methods
}

PlatformType is used to tailor an instance that is being created.

type PodLog

type PodLog struct {
	Log string `json:"log"`
}

PodLog describes a pod log from kubernetes

type PoolEvent

type PoolEvent int

PoolEvent registers a single pool event listener that will receive notifications any time a pool worker "finishes" its job (either with result or error).

const (
	PoolStartSimulation PoolEvent = iota
	PoolShutdownSimulation
	PoolRollbackFailedLaunch
	PoolCompleteFailedTermination
)

PoolEvent enum

type PoolFactory

type PoolFactory func(poolSize int, jobF func(interface{})) (JobPool, error)

PoolFactory is a function responsible of initializing and returning a JobPool. Dev note: we created the PoolFactory abstraction to allow tests use synchronic pools.

type PoolNotificationCallback

type PoolNotificationCallback func(poolEvent PoolEvent, groupID string, result interface{}, err error)

PoolNotificationCallback type of the listeners

type RemainingSubmissions

type RemainingSubmissions struct {
	RemainingSubmissions *int `json:"remaining_submissions"`
}

RemainingSubmissions contains GetRemaingSubmissions response struct

type RunningSimulation

type RunningSimulation struct {
	// The simulation GroupID assigned by the sim_service
	GroupID string
	// The user (or Org) that launched this simulation
	Owner string

	// SimTimeSeconds tracks the current "sim seconds" reported by the simulation /stats topic.
	SimTimeSeconds int64
	// SimWarmupSeconds holds the "sim seconds" value when the simulation notified
	// the warmup was finished.
	SimWarmupSeconds int64
	// SimMaxAllowedSeconds allows to configure an Expiration time based on the simulation time.
	SimMaxAllowedSeconds int64
	// SimCreatedAtTime keeps track of the entire simulation group launch time.
	SimCreatedAtTime time.Time
	// MaxValidUntil keeps track of the Max time this simulation should be automatically
	// terminated. It is used to avoid dangling simulations.
	MaxValidUntil time.Time
	// Finished indicates if the simulation has finished running. A "recording_complete" message in the warmup topic will mark the
	// simulation as finished.
	Finished bool
	// contains filtered or unexported fields
}

RunningSimulation represents a running simulation. It is created by the simulation service when a simulation is lauched. It holds the current state reported by gazebo and also holds an ign-transport node to interact with gazebo (pub/sub). It uses the given simulation GroupID as the ign-transport's Partition.

func NewRunningSimulation

func NewRunningSimulation(ctx context.Context, dep *SimulationDeployment, t ignws.PubSubWebsocketTransporter, worldStatsTopic string,
	worldWarmupTopic string, maxSimSeconds int) (*RunningSimulation, error)

NewRunningSimulation creates a new running simulation. The worldStatsTopic arg is the topic to subscribe to get notifications about the simulation state (eg. /world/default/stats). The optional worldWarmupTopic is used to get notifications about the time when the Simulation actually started.

func (*RunningSimulation) Free

func (s *RunningSimulation) Free(ctx context.Context)

Free releases the resources of this running simulation.

func (*RunningSimulation) IsExpired

func (s *RunningSimulation) IsExpired() bool

IsExpired returns true is the RunningSimulation is expired.

func (*RunningSimulation) PauseSimulation

func (s *RunningSimulation) PauseSimulation(ctx context.Context) error

PauseSimulation request Gazebo to pause the simulation.

func (*RunningSimulation) ResumeSimulation

func (s *RunningSimulation) ResumeSimulation(ctx context.Context) error

ResumeSimulation request to resume the gazebo simulation from pause state. Dev note: To do it, this node will send `resume` messages to Gazebo until the node receives a message saying the simulation is running.

func (*RunningSimulation) SendMessage

func (s *RunningSimulation) SendMessage(ctx context.Context, topic, msg, msgType string)

SendMessage publishes a string message to an specific topic.

type SchedulableTask

type SchedulableTask struct {
	Fn   func()
	Date time.Time
}

SchedulableTask describes a task that can be given to a scheduler to be run at a certain time.

type Service

type Service struct {
	DB *gorm.DB

	ServiceAdaptor simulations.Service
	// contains filtered or unexported fields
}

Service is the main struct exported by this Simulations service.

func (*Service) CreateSession

func (s *Service) CreateSession(ctx context.Context, user *users.User, req billing.CreateSessionRequest) (interface{}, *ign.ErrMsg)

CreateSession starts a checkout session with the payment service for the current user.

func (*Service) CustomRuleList

func (s *Service) CustomRuleList(ctx context.Context, p *ign.PaginationRequest, tx *gorm.DB, user *users.User,
	application *string, circuit *string, owner *string, ruleType *CustomRuleType) (*CircuitCustomRules,
	*ign.PaginationResult, *ign.ErrMsg)

CustomRuleList returns a paginated list of circuit custom rules. This operation can only be performed by a system administrator and team administrators.

func (*Service) CustomizeSimRequest

func (s *Service) CustomizeSimRequest(ctx context.Context, r *http.Request, tx *gorm.DB, createSim *CreateSimulation,
	username string) *ign.ErrMsg

CustomizeSimRequest allows registered Applications to customize the incoming CreateSimulation request. Eg. reading specific SubT fields.

func (*Service) Debug

func (s *Service) Debug(user *users.User, groupID simulations.GroupID) (interface{}, *ign.ErrMsg)

Debug acts as a helper to debug specific code in cloudsim.

func (*Service) DeleteCustomRule

func (s *Service) DeleteCustomRule(ctx context.Context, tx *gorm.DB, user *users.User, application *string,
	circuit *string, owner *string, ruleType *CustomRuleType) (interface{}, *ign.ErrMsg)

DeleteCustomRule deletes a custom rule for an owner in a circuit. This operation can only be performed by a system administrator and team administrators. TODO System and team admins are able to delete rules for invalid owners because admin privileges override

invalid owner errors.

func (*Service) DeployHeldCircuitSimulations

func (s *Service) DeployHeldCircuitSimulations(ctx context.Context, tx *gorm.DB, circuit string) error

DeployHeldCircuitSimulations launches the held simulation deployments for a given circuit

func (*Service) DeployHeldSimulation

func (s *Service) DeployHeldSimulation(ctx context.Context, tx *gorm.DB, dep *SimulationDeployment) *ign.ErrMsg

DeployHeldSimulation deploys a simulation that is being held by cloudsim

func (*Service) GetApplications

func (s *Service) GetApplications() map[string]ApplicationType

GetApplications returns a map of application name and application type.

func (*Service) GetCloudMachineInstances

func (s *Service) GetCloudMachineInstances(ctx context.Context, p *ign.PaginationRequest,
	tx *gorm.DB, byStatus *MachineStatus, invertStatus bool, groupID *string, user *users.User,
	application *string) (*MachineInstances, *ign.PaginationResult, *ign.ErrMsg)

GetCloudMachineInstances returns a paginated list with all cloud instances.

func (*Service) GetCompetitionRobots

func (s *Service) GetCompetitionRobots(applicationName string) (interface{}, *ign.ErrMsg)

GetCompetitionRobots returns the list of available robot configurations for a competition.

func (*Service) GetCreditsBalance

func (s *Service) GetCreditsBalance(ctx context.Context, user *users.User) (interface{}, *ign.ErrMsg)

GetCreditsBalance gets the credit balance of the current user.

func (*Service) GetRemainingSubmissions

func (s *Service) GetRemainingSubmissions(ctx context.Context, tx *gorm.DB, user *users.User, circuit *string,
	owner *string) (interface{}, *ign.ErrMsg)

GetRemainingSubmissions returns the number of remaining submissions for an owner in a circuit.

func (*Service) GetSimulationDeployment

func (s *Service) GetSimulationDeployment(ctx context.Context, tx *gorm.DB,
	groupID string, user *users.User) (interface{}, *ign.ErrMsg)

GetSimulationDeployment returns a single simulation deployment based on its groupID

func (*Service) GetSimulationLiveLogs

func (s *Service) GetSimulationLiveLogs(ctx context.Context, tx *gorm.DB, user *users.User, groupID string,
	robotName *string, lines *int64) (interface{}, *ign.ErrMsg)

GetSimulationLiveLogs returns the live logs from a simulation.

func (*Service) GetSimulationLogsForDownload

func (s *Service) GetSimulationLogsForDownload(ctx context.Context, tx *gorm.DB,
	user *users.User, groupID string, robotName *string) (*string, *ign.ErrMsg)

GetSimulationLogsForDownload returns the generated logs from a simulation.

func (*Service) GetSimulationWebsocketAddress

func (s *Service) GetSimulationWebsocketAddress(ctx context.Context, tx *gorm.DB, user *users.User,
	groupID string) (interface{}, *ign.ErrMsg)

GetSimulationWebsocketAddress returns a live simulation's websocket server address and authorization token. If the simulation is not running, an error is returned.

func (*Service) LaunchSimulationAsync

func (s *Service) LaunchSimulationAsync(ctx context.Context, tx *gorm.DB,
	groupID string, user *users.User) (interface{}, *ign.ErrMsg)

LaunchSimulationAsync launches a simulation that is currently being held by cloudsim.

func (*Service) QueueCount

func (s *Service) QueueCount(ctx context.Context, user *users.User) (interface{}, *ign.ErrMsg)

QueueCount returns the element count from the launch queue.

func (*Service) QueueGetElements

func (s *Service) QueueGetElements(ctx context.Context, user *users.User, page, perPage *int) ([]interface{}, *ign.ErrMsg)

QueueGetElements returns a paginated list of elements from the launch queue. If no page or perPage arguments are passed, it sets those value to 0 and 10 respectively.

func (*Service) QueueMoveElementToBack

func (s *Service) QueueMoveElementToBack(ctx context.Context, user *users.User, groupID string) (interface{}, *ign.ErrMsg)

QueueMoveElementToBack moves an element by the given groupID to the back of the queue.

func (*Service) QueueMoveElementToFront

func (s *Service) QueueMoveElementToFront(ctx context.Context, user *users.User, groupID string) (interface{}, *ign.ErrMsg)

QueueMoveElementToFront moves an element by the given groupID to the front of the queue.

func (*Service) QueueRemoveElement

func (s *Service) QueueRemoveElement(ctx context.Context, user *users.User, groupID string) (interface{}, *ign.ErrMsg)

QueueRemoveElement removes an element by the given groupID from the queue

func (*Service) QueueSwapElements

func (s *Service) QueueSwapElements(ctx context.Context, user *users.User, groupIDA, groupIDB string) (interface{}, *ign.ErrMsg)

QueueSwapElements swaps positions of groupIDs A and B.

func (*Service) ReconnectWebsocket

func (s *Service) ReconnectWebsocket(user *users.User, groupID simulations.GroupID) (interface{}, *ign.ErrMsg)

ReconnectWebsocket reconnects a list of simulation to their respective websocket server

func (*Service) RegisterApplication

func (s *Service) RegisterApplication(ctx context.Context, app ApplicationType)

RegisterApplication registers a new application type.

func (*Service) RestartSimulationAsync

func (s *Service) RestartSimulationAsync(ctx context.Context, tx *gorm.DB,
	groupID string, user *users.User) (interface{}, *ign.ErrMsg)

RestartSimulationAsync re-launches a single (children) simulation that previosly finished with an error status.

func (*Service) SetCustomRule

func (s *Service) SetCustomRule(ctx context.Context, tx *gorm.DB, user *users.User, application *string,
	circuit *string, owner *string, ruleType *CustomRuleType, value *string) (*CircuitCustomRule, *ign.ErrMsg)

SetCustomRule creates or updates a custom rule for an owner in a circuit. This operation can only be performed by a system administrator and team administrators. TODO System and application admins are able to create rules for invalid owners because admin privileges override

invalid owner errors.

func (*Service) SetPoolEventsListener

func (s *Service) SetPoolEventsListener(cb PoolNotificationCallback)

SetPoolEventsListener sets a new PoolNotificationCallback to the poolNotificationCallback field.

func (*Service) ShutdownSimulationAsync

func (s *Service) ShutdownSimulationAsync(ctx context.Context, tx *gorm.DB,
	groupID string, user *users.User) (interface{}, *ign.ErrMsg)

ShutdownSimulationAsync spawns a task to finish a simulation.

func (*Service) SimulationDeploymentList

func (s *Service) SimulationDeploymentList(ctx context.Context, p *ign.PaginationRequest,
	tx *gorm.DB, byStatus *DeploymentStatus, invertStatus bool,
	byErrStatus *ErrorStatus, invertErrStatus bool, byCircuit *string, user *users.User,
	application *string, includeChildren bool, owner *string, private *bool) (*SimulationDeployments, *ign.PaginationResult, *ign.ErrMsg)

SimulationDeploymentList returns a paginated list with cloudsim simulations. Members of the submitting team can see the list of simulations they submitted. Members of the organizing application (eg. members of SubT Organization) can see all simulations for that application.

func (*Service) Start

func (s *Service) Start(ctx context.Context) error

Start starts this simulation service. It needs to be invoked AFTER 'Applications' were registered using 'RegisterApplication'.

func (*Service) StartExpiredSimulationsCleaner

func (s *Service) StartExpiredSimulationsCleaner()

StartExpiredSimulationsCleaner initialize the routine that will check for expired simulations.

func (*Service) StartMultiSimStatusUpdater

func (s *Service) StartMultiSimStatusUpdater()

StartMultiSimStatusUpdater initialize the routine that will update the DeploymentStatus and ErrorStatus of Parents in Multi-simulations. The statuses will be updated based on the status of their children.

func (*Service) StartSimulationAsync

func (s *Service) StartSimulationAsync(ctx context.Context,
	tx *gorm.DB, createSim *CreateSimulation, user *users.User) (interface{}, *ign.ErrMsg)

StartSimulationAsync spawns a task to start a simulation

func (*Service) Stop

func (s *Service) Stop(ctx context.Context) error

Stop stops this Simulations Service

func (*Service) StopExpiredSimulationsCleaner

func (s *Service) StopExpiredSimulationsCleaner()

StopExpiredSimulationsCleaner stops the cleaner process

func (*Service) StopMultiSimStatusUpdater

func (s *Service) StopMultiSimStatusUpdater()

StopMultiSimStatusUpdater stops the update of MultiSim Parents status process.

func (*Service) VerifyPermissionOverPrivateSimulation

func (s *Service) VerifyPermissionOverPrivateSimulation(user *users.User, dep *SimulationDeployment) *ign.ErrMsg

VerifyPermissionOverPrivateSimulation Checks if the given user has permissions over a private simulation.

type SimErrCode

type SimErrCode int64

SimErrCode is the type for all simulations related error codes

const (
	// ErrorMarkingLocalNodeAsFree is triggered when there is an error updating a node
	// labels to mark a minikube node as free.
	ErrorMarkingLocalNodeAsFree SimErrCode = 5501
	// ErrorMarkingLocalNodeAsUsed is triggered when there is an error updating a node
	// labels to mark a minikube node as being used.
	ErrorMarkingLocalNodeAsUsed SimErrCode = 5502
	// ErrorFreeNodeNotFound is triggered when there is no free node to use (minikube)
	ErrorFreeNodeNotFound SimErrCode = 5503
	// ErrorLabeledNodeNotFound is triggered when a node cannot be found using a label selector.
	ErrorLabeledNodeNotFound SimErrCode = 5504
	// ErrorCreatingRunningSimulationNode is triggered when a RunningSimulation cannot be created.
	ErrorCreatingRunningSimulationNode SimErrCode = 5505
	// ErrorOwnerSimulationsLimitReached is triggered when an Owner wants to launch in parallel
	// more than the allowed simulations.
	ErrorOwnerSimulationsLimitReached SimErrCode = 5506
	// ErrorCircuitSubmissionLimitReached is triggered when an Owner wants to
	// launch a simulation to a circuit that has a limit on the number of
	// submissions.
	ErrorCircuitSubmissionLimitReached SimErrCode = 5507
	// ErrorRuleForOwnerNotFound is triggered when an Admin attempts to delete
	// a rule that does not exist for a specific Owner
	ErrorRuleForOwnerNotFound SimErrCode = 5508
	// ErrorRuleNotFound is triggered when a nonexistent rule is set/deleted
	ErrorRuleNotFound SimErrCode = 5509
	// ErrorInvalidScore is triggered when the score file for a simulation cannot be accessed
	ErrorInvalidScore SimErrCode = 5510
	// ErrorInvalidSummary is triggered when the simulation summary file for a simulation cannot be accessed
	ErrorInvalidSummary SimErrCode = 5511
	// ErrorFailedToUploadLogs is triggered when simulations logs fail to upload
	ErrorFailedToUploadLogs SimErrCode = 5512
	// ErrorCreditsExceeded is triggered when the robot credit sum exceeds the circuit credits limit.
	ErrorCreditsExceeded SimErrCode = 5513
	// ErrorCircuitRuleNotFound is triggered when the circuit rule doesn't exist.
	ErrorCircuitRuleNotFound SimErrCode = 5514
	// ErrorFailedToGetLiveLogs is triggered when simulation live logs cannot be get
	ErrorFailedToGetLiveLogs SimErrCode = 5515
	// ErrorRobotIdentifierNotFound is triggered when a robot identifier cannot be found.
	ErrorRobotIdentifierNotFound SimErrCode = 5516
	// ErrorCompetitionNotStarted is triggered when a competition hasn't started yet.
	ErrorCompetitionNotStarted SimErrCode = 5517
	// ErrorNotQualified is triggered when a user/team is not qualified to compete on a circuit.
	ErrorNotQualified SimErrCode = 5518
	// ErrorLaunchHeldSimulation is triggered when an error is found while launching a held simulation.
	ErrorLaunchHeldSimulation SimErrCode = 5519
	// ErrorInvalidRobotImage is triggered when an owner attempts to start a simulation with a robot image that does
	// not belong to them
	ErrorInvalidRobotImage SimErrCode = 5520
	// ErrorInvalidMarsupialSpecification is triggered when an invalid SubT marsupial pair is specified.
	ErrorInvalidMarsupialSpecification SimErrCode = 5521
	// ErrorRobotModelLimitReached is triggered when attempting to launch a simulation with too many robots of a
	// single model.
	ErrorRobotModelLimitReached SimErrCode = 5522
	// ErrorSubmissionDeadlineReached is triggered when a submission deadline for a certain circuit has been reached.
	ErrorSubmissionDeadlineReached SimErrCode = 5523
	// ErrorLaunchSupersededSimulation is triggered when a held simulation is superseded.
	ErrorLaunchSupersededSimulation SimErrCode = 5524
	// ErrorInvalidRunInformation is triggered when the run information file for a simulation cannot be accessed
	ErrorInvalidRunInformation SimErrCode = 5525
	// ErrorNotEnoughCredits is returned when the user doesn't have enough credits to run a simulation.
	ErrorNotEnoughCredits SimErrCode = 5526
)

type SimService

type SimService interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
	CustomizeSimRequest(ctx context.Context, r *http.Request, tx *gorm.DB, createSim *CreateSimulation, username string) *ign.ErrMsg
	GetCloudMachineInstances(ctx context.Context, p *ign.PaginationRequest,
		tx *gorm.DB, byStatus *MachineStatus, invertStatus bool, groupID *string, user *users.User, application *string) (*MachineInstances, *ign.PaginationResult, *ign.ErrMsg)
	GetSimulationDeployment(ctx context.Context, tx *gorm.DB, groupID string,
		user *users.User) (interface{}, *ign.ErrMsg)
	GetSimulationWebsocketAddress(ctx context.Context, tx *gorm.DB, user *users.User,
		groupID string) (interface{}, *ign.ErrMsg)
	GetSimulationLiveLogs(ctx context.Context, tx *gorm.DB, user *users.User, groupID string,
		robotName *string, lines *int64) (interface{}, *ign.ErrMsg)
	GetSimulationLogsForDownload(ctx context.Context, tx *gorm.DB, user *users.User, groupID string,
		robotName *string) (*string, *ign.ErrMsg)
	RegisterApplication(ctx context.Context, app ApplicationType)
	ShutdownSimulationAsync(ctx context.Context, tx *gorm.DB,
		groupID string, user *users.User) (interface{}, *ign.ErrMsg)
	SimulationDeploymentList(ctx context.Context, p *ign.PaginationRequest, tx *gorm.DB, byStatus *DeploymentStatus,
		invertStatus bool, byErrStatus *ErrorStatus, invertErrStatus bool, byCircuit *string, user *users.User,
		application *string, includeChildren bool, owner *string, private *bool) (*SimulationDeployments, *ign.PaginationResult, *ign.ErrMsg)
	StartSimulationAsync(ctx context.Context, tx *gorm.DB, createSim *CreateSimulation,
		user *users.User) (interface{}, *ign.ErrMsg)
	LaunchSimulationAsync(ctx context.Context, tx *gorm.DB, groupID string,
		user *users.User) (interface{}, *ign.ErrMsg)
	RestartSimulationAsync(ctx context.Context, tx *gorm.DB, groupID string,
		user *users.User) (interface{}, *ign.ErrMsg)
	GetRemainingSubmissions(ctx context.Context, tx *gorm.DB, user *users.User, circuit *string,
		owner *string) (interface{}, *ign.ErrMsg)
	CustomRuleList(ctx context.Context, p *ign.PaginationRequest, tx *gorm.DB, user *users.User, application *string,
		circuit *string, owner *string, ruleType *CustomRuleType) (*CircuitCustomRules, *ign.PaginationResult, *ign.ErrMsg)
	SetCustomRule(ctx context.Context, tx *gorm.DB, user *users.User, application *string,
		circuit *string, owner *string, ruleType *CustomRuleType, value *string) (*CircuitCustomRule, *ign.ErrMsg)
	DeleteCustomRule(ctx context.Context, tx *gorm.DB, user *users.User, application *string, circuit *string,
		owner *string, ruleType *CustomRuleType) (interface{}, *ign.ErrMsg)
	GetCompetitionRobots(applicationName string) (interface{}, *ign.ErrMsg)
	QueueGetElements(ctx context.Context, user *users.User, page, pageSize *int) ([]interface{}, *ign.ErrMsg)
	QueueMoveElementToFront(ctx context.Context, user *users.User, groupID string) (interface{}, *ign.ErrMsg)
	QueueMoveElementToBack(ctx context.Context, user *users.User, groupID string) (interface{}, *ign.ErrMsg)
	QueueSwapElements(ctx context.Context, user *users.User, groupIDA, groupIDB string) (interface{}, *ign.ErrMsg)
	QueueRemoveElement(ctx context.Context, user *users.User, groupID string) (interface{}, *ign.ErrMsg)
	QueueCount(ctx context.Context, user *users.User) (interface{}, *ign.ErrMsg)
	Debug(user *users.User, groupID simulations.GroupID) (interface{}, *ign.ErrMsg)
	ReconnectWebsocket(user *users.User, groupID simulations.GroupID) (interface{}, *ign.ErrMsg)
	GetCreditsBalance(ctx context.Context, user *users.User) (interface{}, *ign.ErrMsg)
	CreateSession(ctx context.Context, user *users.User, req billing.CreateSessionRequest) (interface{}, *ign.ErrMsg)
}

SimService is an interface that supports managing simulation instances.

var SimServImpl SimService

SimServImpl holds the instance of the Simulations Service. It is set at initialization.

func NewSimulationsService

func NewSimulationsService(ctx context.Context, db *gorm.DB, pf PoolFactory, ua useracc.Service,
	isTest bool) (SimService, error)

NewSimulationsService creates a new simulations service

type SimulationDeployment

type SimulationDeployment struct {
	// Override default GORM Model fields
	ID        uint      `gorm:"primary_key" json:"-"`
	CreatedAt time.Time `gorm:"type:timestamp(3) NULL" json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	// Added 2 milliseconds to DeletedAt field
	DeletedAt *time.Time `gorm:"type:timestamp(2) NULL" sql:"index" json:"-"`
	// Timestamp in which this simulation was stopped/terminated.
	StoppedAt *time.Time `gorm:"type:timestamp(3) NULL" json:"stopped_at,omitempty"`
	// LaunchedAt is the time on which the simulation was launched to run.
	LaunchedAt *time.Time `gorm:"type:timestamp(3) NULL" json:"launched_at,omitempty"`
	// ChargedAt is the time on which this simulation was charged.
	ChargedAt *time.Time `gorm:"type:timestamp(3) NULL" json:"-"`
	// Represents the maximum time this simulation should live. After that time
	// it will be eligible for automatic termination.
	// It is a time.Duration (stored as its string representation).
	ValidFor *string `json:"valid_for,omitempty"`
	// The owner of this deployment (must exist in UniqueOwners). Can be user or org.
	// Also added to the name_owner unique index
	Owner *string `json:"owner,omitempty"`
	// The username of the User that created this resource (usually got from the JWT)
	Creator *string `json:"creator,omitempty"`
	// Private - True to make this a private resource
	Private *bool `json:"private,omitempty"`
	// When shutting down simulations, stop EC2 instances instead of terminating them. Requires admin privileges.
	StopOnEnd *bool `json:"stop_on_end"`
	// The user defined Name for the simulation.
	Name *string `json:"name,omitempty"`
	// The docker image url to use for the simulation (usually for the Field Computer)
	Image *string `json:"image,omitempty" form:"image"`
	// GroupID - Simulation Unique identifier
	// All k8 pods and services (or other created resources) will share this groupID
	GroupID *string `gorm:"not null;unique" json:"group_id"`
	// ParentGroupID (optional) holds the GroupID of the parent simulation record.
	// It is used with requests for multi simulations (multiSims), where a single
	// user request spawns multiple simulation runs based on a single template.
	ParentGroupID *string `json:"parent"`
	// MultiSim holds which role this simulation plays within a multiSim deployment.
	// Values should be of type MultiSimType.
	MultiSim int
	// A value from DeploymentStatus constants
	DeploymentStatus *int `json:"status,omitempty"`
	// A value from ErrorStatus constants
	ErrorStatus *string `json:"error_status,omitempty"`
	// NOTE: statuses should be updated in sequential DB Transactions. ie. one status per TX.
	Platform    *string `json:"platform,omitempty" form:"platform"`
	Application *string `json:"application,omitempty" form:"application"`
	// TODO: both fields Extra and ExtraSelector should be a separate table, specific to
	//   each Application, and with a reference back to this simulation ID.
	// A free form string field to store extra details, usually associated to the
	// chosen Application. Eg. SubT would store here the different robot names, types
	// and images.
	Extra *string `gorm:"size:999999" json:"extra,omitempty"`
	// A extra string field to store a selector that can help specific Applications
	// to filter simulations (eg. SQL WHERE). SubT could store the circuit here.
	ExtraSelector *string `json:"-"`
	// TODO: This is a field specific to SubT. As such this is a temporary field
	//  that should be included in the same separate table where Extra and
	//  ExtraSelector should reside.
	// Contains the names of all robots in the simulation in a comma-separated list.
	Robots *string `gorm:"size:1000" json:"robots"`
	// TODO: This is a field specific to SubT. This is a temporary field that should be
	//  extracted from the SimulationDeployment struct.
	Held bool `json:"held"`
	// Processed indicates that this simulation has been post-processed.
	// Used to avoid post-processing simulations more than once.
	Processed bool `json:"-"`
	// AuthorizationToken contains a security token used to let external services authorize requests related to this
	// simulation.
	// This token is currently used to establish connections with the simulation's websocket server.
	AuthorizationToken *string `json:"-"`
	// Score has the simulation's score. It's updated when the simulations finishes and gets processed.
	Score *float64 `json:"score,omitempty"`
	// Rate is the rate at which this simulation should be charged for in USD per hour.
	Rate *uint `json:"-"`
}

SimulationDeployment represents a cloudsim simulation .

func GetParentSimulation

func GetParentSimulation(tx *gorm.DB, dep *SimulationDeployment) (*SimulationDeployment, error)

GetParentSimulation returns the DB record corresponding to the parent simulation

func GetSimulationDeployment

func GetSimulationDeployment(tx *gorm.DB, groupID string) (*SimulationDeployment, error)

GetSimulationDeployment gets a simulation deployment record by its GroupID Fails if not found.

func NewSimulationDeployment

func NewSimulationDeployment() (*SimulationDeployment, error)

NewSimulationDeployment creates and initializes a simulation deployment struct. TODO: Receive a DTO struct as a parameter

func (*SimulationDeployment) Clone

Clone clones a SimulationDeployment

func (*SimulationDeployment) GetChargedAt

func (dep *SimulationDeployment) GetChargedAt() *time.Time

GetChargedAt returns the date and time on which this simulation was charged.

func (*SimulationDeployment) GetCost

func (dep *SimulationDeployment) GetCost() (uint, calculator.Rate, error)

GetCost applies the current rate to this simulation resulting in the amount of money that it should be charged. The calculation will always be rounded up to the closest hour

func (*SimulationDeployment) GetCreator

func (dep *SimulationDeployment) GetCreator() string

GetCreator returns the SimulationDeployment's Creator. It returns an empty string if no creator has been assigned.

func (*SimulationDeployment) GetError

func (dep *SimulationDeployment) GetError() *simulations.Error

GetError returns the SimulationDeployment's ErrorStatus

func (*SimulationDeployment) GetGroupID

func (dep *SimulationDeployment) GetGroupID() simulations.GroupID

GetGroupID returns the SimulationDeployment's GroupID.

func (*SimulationDeployment) GetImage

func (dep *SimulationDeployment) GetImage() string

GetImage returns the SimulationDeployment's image.

func (*SimulationDeployment) GetKind

func (dep *SimulationDeployment) GetKind() simulations.Kind

GetKind returns the SimulationDeployment's Kind. It parses the MultiSim field into a Kind.

func (*SimulationDeployment) GetLaunchedAt

func (dep *SimulationDeployment) GetLaunchedAt() *time.Time

GetLaunchedAt returns the time and date the simulation was officially launched. This date can differ from the time the simulation was requested due to the simulation having been held, or because it has been unable to launch because of insufficient cloud resources.

func (*SimulationDeployment) GetMarsupials

func (dep *SimulationDeployment) GetMarsupials() []simulations.Marsupial

GetMarsupials parses the extra field and returns the marsupials.

func (*SimulationDeployment) GetName

func (dep *SimulationDeployment) GetName() string

GetName returns the SimulationsDeployment's Name. t returns an empty string if no name has been assigned.

func (*SimulationDeployment) GetOwner

func (dep *SimulationDeployment) GetOwner() *string

GetOwner returns the SimulationDeployment's Owner.

func (*SimulationDeployment) GetPlatform

func (dep *SimulationDeployment) GetPlatform() *string

GetPlatform returns the SimulationDeployment's Platform.

func (*SimulationDeployment) GetRate

func (dep *SimulationDeployment) GetRate() calculator.Rate

GetRate returns at which rate this simulation will be charged per hour.

func (*SimulationDeployment) GetRobots

func (dep *SimulationDeployment) GetRobots() []simulations.Robot

GetRobots parses the robots from the extra field and returns them as a slice of robots.

func (*SimulationDeployment) GetRunIndex

func (dep *SimulationDeployment) GetRunIndex() int

GetRunIndex returns the simulation's run index.

func (*SimulationDeployment) GetStatus

func (dep *SimulationDeployment) GetStatus() simulations.Status

GetStatus returns the SimulationDeployment's DeploymentStatus.

func (*SimulationDeployment) GetStoppedAt

func (dep *SimulationDeployment) GetStoppedAt() *time.Time

GetStoppedAt returns at what time the simulation stopped. It returns nil if the simulation didn't stop.

func (*SimulationDeployment) GetToken

func (dep *SimulationDeployment) GetToken() *string

GetToken returns the SimulationDeployment's websocket authorization token.

func (*SimulationDeployment) GetTrack

func (dep *SimulationDeployment) GetTrack() string

GetTrack returns the SimulationDeployment's circuit name.

func (*SimulationDeployment) GetValidFor

func (dep *SimulationDeployment) GetValidFor() time.Duration

GetValidFor returns the SimulationDeployment's ValidFor parsed as time.Duration.

func (*SimulationDeployment) GetWorldIndex

func (dep *SimulationDeployment) GetWorldIndex() int

GetWorldIndex returns the simulation's world index.

func (*SimulationDeployment) HasStatus

func (dep *SimulationDeployment) HasStatus(status simulations.Status) bool

HasStatus checks that the SimulationDeployment's DeploymentStatus is equal to the given status.

func (*SimulationDeployment) IsKind

func (dep *SimulationDeployment) IsKind(kind simulations.Kind) bool

IsKind checks that the SimulationDeployment

func (*SimulationDeployment) IsProcessed

func (dep *SimulationDeployment) IsProcessed() bool

IsProcessed returns true if the SimulationDeployment has been processed.

func (*SimulationDeployment) IsRunning

func (dep *SimulationDeployment) IsRunning() bool

IsRunning returns true if the SimulationDeployment can be considered "running". Running goes from the moment a simulation is scheduled to run (ie. Pending state) up to until its termination is requested (ie. 'terminate requested' state).

func (*SimulationDeployment) MarkAsMultiSimChild

func (dep *SimulationDeployment) MarkAsMultiSimChild(tx *gorm.DB, parent *SimulationDeployment) *ign.ErrMsg

MarkAsMultiSimChild marks this SimulationDeployment to be a child of the given simulation.

func (*SimulationDeployment) MarkAsMultiSimParent

func (dep *SimulationDeployment) MarkAsMultiSimParent(tx *gorm.DB) *ign.ErrMsg

MarkAsMultiSimParent marks this simulationDeployment as the parent in a multiSimulation. Parent simulationDeployment usually don't launch simulations themselves but instead group a set of child simulations.

func (*SimulationDeployment) SetRate

func (dep *SimulationDeployment) SetRate(rate calculator.Rate)

SetRate sets the given rate to the current simulation.

func (*SimulationDeployment) SetStatus

func (dep *SimulationDeployment) SetStatus(status simulations.Status)

SetStatus sets the SimulationDeployment's DeploymentStatus to the given status.

func (*SimulationDeployment) UpdateHeldStatus

func (dep *SimulationDeployment) UpdateHeldStatus(tx *gorm.DB, state bool) error

UpdateHeldStatus returns an error if the SimulationDeployment held field failed to update.

func (*SimulationDeployment) UpdateProcessed

func (dep *SimulationDeployment) UpdateProcessed(tx *gorm.DB, state bool) error

UpdateProcessed sets the given state in the Processed value. Returns an error if the SimulationDeployment Processed field failed to update.

func (*SimulationDeployment) UpdateScore

func (dep *SimulationDeployment) UpdateScore(tx *gorm.DB, score *float64) *ign.ErrMsg

UpdateScore is used to update the score of the current simulation while it's being processed. Returns an error if the SimulationDeployment Score field failed to update.

type SimulationDeployments

type SimulationDeployments []SimulationDeployment

SimulationDeployments is a slice of SimulationDeployment

func GetChildSimulationDeployments

func GetChildSimulationDeployments(tx *gorm.DB, dep *SimulationDeployment, statusFrom,
	statusTo DeploymentStatus) (*SimulationDeployments, error)

GetChildSimulationDeployments returns the child simulation deployments of a given parent simulation deployment. The returned set will only contain children simulations whose deploymentStatus is within the given statuses range, and with NO ErrorStatus.

func GetParentSimulationDeployments

func GetParentSimulationDeployments(tx *gorm.DB, statusFrom,
	statusTo DeploymentStatus, validErrors []ErrorStatus) (*SimulationDeployments, error)

GetParentSimulationDeployments returns the "parent" simulation deployments from Multi Sim deployments. The returned set will only contain simulations whose deploymentStatus is within the given statuses range, and with NO ErrorStatus.

func GetSimulationDeploymentsByCircuit

func GetSimulationDeploymentsByCircuit(tx *gorm.DB, circuit string, statusFrom,
	statusTo DeploymentStatus, held *bool) (*SimulationDeployments, error)

GetSimulationDeploymentsByCircuit gets a list of simulation deployments for a given circuit. The returned set will only contain simulations whose deploymentStatus is within the given statuses range.

func GetSimulationDeploymentsByOwner

func GetSimulationDeploymentsByOwner(tx *gorm.DB, owner string, statusFrom,
	statusTo DeploymentStatus) (*SimulationDeployments, error)

GetSimulationDeploymentsByOwner gets a list of simulation deployment records filtered by a given owner. The returned set will only contain simulations whose deploymentStatus is within the given statuses range.

type SimulationDeploymentsSubTValue

type SimulationDeploymentsSubTValue struct {
	gorm.Model
	SimulationDeployment *SimulationDeployment `gorm:"foreignkey:SimDep" json:"-"`
	// Simulation unique identifier
	GroupID *string `gorm:"not null;unique" json:"-"`
	// Simulation score
	Score *float64 `gorm:"not null" json:"score"`
	// Simulation run info
	SimTimeDurationSec  int `gorm:"not null" json:"sim_time_duration_sec"`
	RealTimeDurationSec int `gorm:"not null" json:"real_time_duration_sec"`
	ModelCount          int `gorm:"not null" json:"model_count"`
}

SimulationDeploymentsSubTValue holds SubT-specific values associated to a given simulation deployment. E.g. specific simulation score, summary values, etc.

type SimulationServiceAdaptor

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

SimulationServiceAdaptor implements the simulations.Service interface. It acts as an adaptor between the legacy code and the new code introduced in the code refactor.

func (*SimulationServiceAdaptor) Create

Create creates a simulation (SimulationDeployment) from the given input.

func (*SimulationServiceAdaptor) Get

Get gets a simulation deployment with the given GroupID.

func (*SimulationServiceAdaptor) GetParent

GetParent gets the parent simulation for the given GroupID.

func (*SimulationServiceAdaptor) GetRobots

func (sa *SimulationServiceAdaptor) GetRobots(groupID simulations.GroupID) ([]simulations.Robot, error)

GetRobots returns the list of robots for the given groupID.

func (*SimulationServiceAdaptor) GetWebsocketToken

func (sa *SimulationServiceAdaptor) GetWebsocketToken(groupID simulations.GroupID) (string, error)

GetWebsocketToken returns a simulation's websocket authorization token.

func (*SimulationServiceAdaptor) MarkCharged

func (sa *SimulationServiceAdaptor) MarkCharged(groupID simulations.GroupID) error

MarkCharged marks a simulation identified with the given Group ID as charged. If the ChargedAt value is already set, it won't be updated.

func (*SimulationServiceAdaptor) MarkStopped

func (sa *SimulationServiceAdaptor) MarkStopped(groupID simulations.GroupID) error

MarkStopped marks a simulation with the time when it has stopped running. If the StoppedAt value is already set, it won't be updated.

func (*SimulationServiceAdaptor) Update

func (sa *SimulationServiceAdaptor) Update(groupID simulations.GroupID, simulation simulations.Simulation) error

Update updates the simulation identified by groupID with the data given in simulation.

func (*SimulationServiceAdaptor) UpdateScore

func (sa *SimulationServiceAdaptor) UpdateScore(groupID simulations.GroupID, score *float64) error

UpdateScore updates the score of a certain simulation deployment.

func (*SimulationServiceAdaptor) UpdateStatus

func (sa *SimulationServiceAdaptor) UpdateStatus(groupID simulations.GroupID, status simulations.Status) error

UpdateStatus persists the given status that assigns to the given GroupID.

type SimulationStatistics

type SimulationStatistics struct {
	WasStarted          int `yaml:"was_started"`
	SimTimeDurationSec  int `yaml:"sim_time_duration_sec"`
	RealTimeDurationSec int `yaml:"real_time_duration_sec"`
	ModelCount          int `yaml:"model_count"`
}

SimulationStatistics contains the summary values of a simulation run.

type SubTApplication

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

SubTApplication represents an application used to tailor SubT simulation requests.

func NewSubTApplication

func NewSubTApplication(ctx context.Context) (*SubTApplication, error)

NewSubTApplication creates a SubT application, used to tailor simulation requests.

func (*SubTApplication) GetSchedulableTasks

func (sa *SubTApplication) GetSchedulableTasks(ctx context.Context, s *Service, tx *gorm.DB) []SchedulableTask

GetSchedulableTasks returns a slice of schedulable tasks to be registered on cloudsim's scheduler.

func (*SubTApplication) ValidateSimulationLaunch

func (sa *SubTApplication) ValidateSimulationLaunch(ctx context.Context, tx *gorm.DB, dep *SimulationDeployment) *ign.ErrMsg

ValidateSimulationLaunch returns an error if there is an error on the validation process. Any function that needs to validate a simulation right before pushing to the queue should be appended here.

type SubTCircuitRules

type SubTCircuitRules struct {
	gorm.Model
	Circuit      *string `gorm:"not null;unique" json:"-"`
	Image        *string `json:"-"`
	BridgeImage  *string `json:"-"`
	MappingImage *string `json:"-"`
	// MoleBridgeImage contains an optional Mole ROS/Pulsar bridge image URI. If not defined, the bridge will not be
	// launched.
	MoleBridgeImage *string `json:"-"`
	Worlds          *string `gorm:"size:2048" json:"-"`
	Times           *string `json:"-"`
	// WorldStatsTopics is the topic used to track general stats of the simulation (runtime, sim runtime, etc.)
	WorldStatsTopics *string `gorm:"size:2048" json:"-"`
	// WorldWarmupTopics is the topic used to track when the simulation officially starts and ends
	WorldWarmupTopics *string `gorm:"size:2048" json:"-"`
	// WorldMaxSimSeconds is the maximum number of allowed "simulation seconds" for each world. 0 means unlimited.
	WorldMaxSimSeconds *string `json:"-"`
	// Seeds is comma separated list of seed numbers. Each seed will be used with each world run.
	// As an example, if field "Worlds" contains 3 worlds and "times" contains "1,2,2", then
	// there should be 5 seeds.
	Seeds      *string `gorm:"size:2048" json:"-"`
	MaxCredits *int    `json:"-"`
	// CompetitionDate is the date when all held simulations for this circuit will be launched.
	CompetitionDate *time.Time `json:"-"`
	// SubmissionDeadline is the deadline for all teams to submit simulations for this circuit.
	SubmissionDeadline *time.Time `json:"-"`
	// If this field is set to true, every team that has qualified for this circuit
	// must be added to the table sub_t_qualified_participant.
	// All the participants that were not added to the qualified participants table will be rejected when submitting
	// a new simulation for this circuit.
	RequiresQualification *bool `json:"-"`
}

SubTCircuitRules holds the rules associated to a given circuit. Eg which worlds to run and how many times.

func GetCircuitRules

func GetCircuitRules(tx *gorm.DB, circuit string) (*SubTCircuitRules, error)

GetCircuitRules gets the rules for a given circuit

func (*SubTCircuitRules) ToTrack

func (r *SubTCircuitRules) ToTrack(worldID int, runID int) (*tracks.Track, error)

ToTrack generates a representation of a tracks.Track from the current SubTCircuitRules. It receives a worldID and runID to generate the track based on the worlds and seeds from SubTCircuitRules.

type SubTCreateSimulation

type SubTCreateSimulation struct {
	CreateSimulation `json:"-"`
	// Robot Names . Note the validate tag with the "dive" validation to validate each item
	// TODO Reenable notinblacklist validator for Name
	RobotName []string `json:"robot_name" validate:"gt=0,unique,dive,required,min=2,max=24,alphanum" form:"robot_name"`
	RobotType []string `json:"robot_type" validate:"lenEqFieldLen=RobotName,dive,isrobottype" form:"robot_type"`
	// Override the CreateSimulation Image field
	RobotImage []string `json:"robot_image" validate:"lenEqFieldLen=RobotName" form:"robot_image"`
	Marsupial  []string `json:"marsupial" form:"marsupial"`
	Circuit    string   `json:"circuit" validate:"required,iscircuit" form:"circuit"`
}

SubTCreateSimulation is a CreateSimulation request extension that adds specfic fields and validations for SubT application.

type SubTMarsupial

type SubTMarsupial struct {
	Parent string
	Child  string
}

SubTMarsupial is an internal type used to describe marsupial vehicles in SubT.

func (*SubTMarsupial) GetChild

func (s *SubTMarsupial) GetChild() simulations.Robot

GetChild returns the child robot.

func (*SubTMarsupial) GetParent

func (s *SubTMarsupial) GetParent() simulations.Robot

GetParent returns the parent robot.

type SubTQualifiedParticipant

type SubTQualifiedParticipant struct {
	gorm.Model
	Circuit string `gorm:"not null" json:"circuit"`
	Owner   string `gorm:"not null" json:"owner"`
}

SubTQualifiedParticipant represents a qualification from a certain owner to participate in a circuit.

type SubTRobot

type SubTRobot struct {
	Name    string
	Type    string
	Image   string
	Credits int
}

SubTRobot is an internal type used to describe a single SubT robot (field-computer) request.

func (*SubTRobot) GetImage

func (s *SubTRobot) GetImage() string

GetImage returns the robot image.

func (*SubTRobot) GetKind

func (s *SubTRobot) GetKind() string

GetKind returns the robot type.

func (*SubTRobot) GetName

func (s *SubTRobot) GetName() string

GetName returns the robot name.

func (*SubTRobot) IsEqual

func (s *SubTRobot) IsEqual(robot simulations.Robot) bool

IsEqual asserts the given robot equals the current robot.

type SubTRobotType

type SubTRobotType struct {
	// Owner is the organization that owns the robot in Fuel.
	Owner string `json:"owner"`
	// Name is the name of the robot shown to users.
	Name string `json:"name"`
	// Model is the robot model name. A single model can contain different sets of sensors.
	Model string `json:"model"`
	// Type contains the name of the robot's model and sensor combo.
	Type string `json:"type"`
	// Credits contains the cost of the robot.
	Credits int `json:"credits"`
	// Thumbnail contains the robot's thumbnail URL.
	Thumbnail string `json:"thumbnail"`
}

SubTRobotType represents a SubT robot. These robots are expected to be part of the SubT portal in Fuel.

type SynchronicPool

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

SynchronicPool is used to schedule Jobs and make the caller wait (block) until they are executed. Dev note: it wraps an ants.job pool and uses a sync.WaitGroup to make the calling routine block until the job finishes.

func (*SynchronicPool) Serve

func (sp *SynchronicPool) Serve(args interface{}) error

Serve submits a task to pool. Implements simulations.JobPool interface.

type WebsocketAddressResponse

type WebsocketAddressResponse struct {
	Token   string `json:"authorization_token"`
	Address string `json:"websocket_address"`
}

WebsocketAddressResponse represents a response from the get websocket's server address route.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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