helpers

package
v0.0.0-...-21eebf0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2020 License: GPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CloudNotifierStatusCreated ...
	CloudNotifierStatusCreated = ""
	// CloudNotifierStatusRunning ...
	CloudNotifierStatusRunning = "working"
	// CloudNotifierStatusDone ...
	CloudNotifierStatusDone = "finished"
	// CloudNotifierStatusErrored ...
	CloudNotifierStatusErrored = "errored"
	// CloudNotifierStatusTimeout ...
	CloudNotifierStatusTimeout = "timeout"
)
View Source
const (
	// StatusWorking says the task is working
	StatusWorking = "working"
	// StatusFinished says the task is done
	StatusFinished = "finished"
	// StatusErrored says the task errored and is done
	StatusErrored = "errored"
	// TypeInfo is the standard event type
	TypeInfo = "info"
	// TypeError is an event type that indicates an error
	TypeError = "error"
	// TypeImportantInfo is an event type that indicates an important event
	TypeImportantInfo = "importantInfo"
	// TypeCloseOK indicates that the stream should be closed. That should be
	// used once the task ended well.
	TypeCloseOK = "closeOK"
	// TypeCloseError should be used to indicate that the stream is closed with
	// an error
	TypeCloseError = "closeError"
)

Variables

This section is empty.

Functions

func AddFlash

func AddFlash(w http.ResponseWriter, r *http.Request, msg string, store sessions.Store, ft FlashType) error

AddFlash ...

func GetLogs

func GetLogs(aliasName, bucketName, prefix string) ([]*TaskEvent, CloudNotifierStatus, error)

GetLogs returns the list of existing logs at given prefix. The list is sorted by the time of task events, with the most recent at the first index.

func GetMinioClient

func GetMinioClient() (*minio.Client, error)

GetMinioClient return a static minio client

func GetRandomName

func GetRandomName() string

GetRandomName returns a random name string composed of and adjectiv-anminal

func RandString

func RandString(n int) string

RandString returns a random string of N chars

func RedirectWithErrorFlash

func RedirectWithErrorFlash(path, message string, w http.ResponseWriter, r *http.Request, store sessions.Store)

RedirectWithErrorFlash sets an error flash and redirect to the path. If there is an error during this process, raises a json error. One must return after calling this function.

func RedirectWithInfoFlash

func RedirectWithInfoFlash(path, message string, w http.ResponseWriter, r *http.Request, store sessions.Store)

RedirectWithInfoFlash sets a warning flash and redirect to the path. If there is an error during this process, raises a json error. One must return after calling this function.

func RedirectWithWarningFlash

func RedirectWithWarningFlash(path, message string, w http.ResponseWriter, r *http.Request, store sessions.Store)

RedirectWithWarningFlash sets a warning flash and redirect to the path. If there is an error during this process, raises a json error. One must return after calling this function.

func SendRequestError

func SendRequestError(err error, w http.ResponseWriter)

SendRequestError is a utility function that fills the given http.ResponseWriter with the provided error as json formatted. When calling this function one should directly return. It makes use of RequestedError by checking if the provided error matches this type.

func StatusImage

func StatusImage(status StatusTask) string

StatusImage return an html image corresponding to the status

Types

type CloudClient

type CloudClient interface {
	PutObject(bucketName, objectName string, reader io.Reader, objectSize int64,
		opts interface{}) (n int64, err error)
	GetObject(bucketName, objectName string, opts interface{}) (CloudObject, error)
	BucketExists(bucketName string) (bool, error)
	MakeBucket(bucketName string, location string) (err error)
}

CloudClient defines the primitives needed to use a cloud client, This abstraction allows us to mock the traditional minio client.

func NewMinioCloudClient

func NewMinioCloudClient() (CloudClient, error)

NewMinioCloudClient return a new minio cloud client

type CloudNotifier

type CloudNotifier struct {
	sync.Mutex
	Status CloudNotifierStatus
	// This bool indicates if the CloudNotifier is done or not. Once set to true
	// it shoudl never be set back to false
	Terminated bool
	ID         string
	// This variable is updated with new task events.
	TaskEventCh chan TaskEvent
	// AliasName is the name used when configuring minio, for example "dedis"
	AliasName string
	// BucketName is the name of the bucket. In our case it's the project id
	BucketName string
	// This is the path after the bucket name, in the form
	// "logs/{request index}"
	Prefix      string
	IsClosed    bool
	Done        chan bool
	NotifDoneCh chan struct{}
}

CloudNotifier notify subscribers about the update of a project or request status

func NewCloudNotifier

func NewCloudNotifier(aliasName, bucketName, prefix string) (*CloudNotifier, error)

NewCloudNotifier return a new status notifier. CloudURL should be of form {alias}/{bucket name}/logs/{request index}

type CloudNotifierStatus

type CloudNotifierStatus string

CloudNotifierStatus indicates the status of the cloud notifier

type CloudNotifierSubscriber

type CloudNotifierSubscriber struct {
	NotifyStream chan string
	Done         chan bool
}

CloudNotifierSubscriber represent a client that subscribes to receive notifications about a cloud endpoint

type CloudObject

type CloudObject interface {
	Close() (err error)
	Stat() (minio.ObjectInfo, error)
	Read(p []byte) (n int, err error)
}

CloudObject is the abstraction of an element that we get from the cloud

type DefaultHTTP

type DefaultHTTP struct {
}

DefaultHTTP is the default implementation of runhttp that uses net/http

func (DefaultHTTP) Do

func (dh DefaultHTTP) Do(client *http.Client, req *http.Request) (resp *http.Response, err error)

Do implements runhttp by using the net/http lib

type DefaultTaskManager

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

DefaultTaskManager implements TaskManagerI. It provides a default implementation

func NewDefaultTaskManager

func NewDefaultTaskManager() *DefaultTaskManager

NewDefaultTaskManager return a new DefaultTaskManager

func (*DefaultTaskManager) DeleteAllTasks

func (dtm *DefaultTaskManager) DeleteAllTasks()

DeleteAllTasks deletes all the tasks

- implements TaskManagerI

func (*DefaultTaskManager) GetSortedTasks

func (dtm *DefaultTaskManager) GetSortedTasks() []TaskI

GetSortedTasks return the list of tasks sorted by index

- implements TaskManagerI

func (*DefaultTaskManager) GetTask

func (dtm *DefaultTaskManager) GetTask(index int) TaskI

GetTask returns a tsak by its index

- implements TaskManagerI

func (*DefaultTaskManager) NewTask

func (dtm *DefaultTaskManager) NewTask(title string) TaskI

NewTask return a new Task

- implements TaskManagerI

func (*DefaultTaskManager) NumTasks

func (dtm *DefaultTaskManager) NumTasks() int

NumTasks return the number of tasks

- implements TaskManagerI

func (*DefaultTaskManager) RestoreTasks

func (dtm *DefaultTaskManager) RestoreTasks(tasks []TaskI) error

RestoreTasks sets the provided tasks in the task list. The previous tasks are deleted.

- implements TaskManagerI

type Executor

type Executor interface {
	Run(args ...string) (bytes.Buffer, error)
}

Executor is an interface that alllows one to execute commands. This abstraction allows us to mock a traditional "os/exec" command in the tests.

type Flash

type Flash struct {
	Msg  string
	Type FlashType
}

Flash ...

func ExtractFlash

func ExtractFlash(w http.ResponseWriter, r *http.Request, store sessions.Store) ([]Flash, error)

ExtractFlash ...

type FlashType

type FlashType int

FlashType ...

const (
	// Info ...
	Info FlashType = iota
	// Warning ...
	Warning
	// Error ...
	Error
)

type MinioCloudClient

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

MinioCloudClient is the default implementation for a CloudClient

func (MinioCloudClient) BucketExists

func (mcc MinioCloudClient) BucketExists(bucketName string) (bool, error)

BucketExists tells if a bucket exists

func (MinioCloudClient) GetObject

func (mcc MinioCloudClient) GetObject(bucketName, objectName string,
	opts interface{}) (CloudObject, error)

GetObject gets an object

func (MinioCloudClient) MakeBucket

func (mcc MinioCloudClient) MakeBucket(bucketName string, location string) (err error)

MakeBucket makes a bucket

func (MinioCloudClient) PutObject

func (mcc MinioCloudClient) PutObject(bucketName, objectName string, reader io.Reader, objectSize int64,
	opts interface{}) (n int64, err error)

PutObject puts an object on the cloud

type OSExecutor

type OSExecutor struct {
}

OSExecutor implements the Executor interface with os/exec

func NewOSExecutor

func NewOSExecutor() OSExecutor

NewOSExecutor returns a new OS Executor

func (OSExecutor) Run

func (ose OSExecutor) Run(args ...string) (bytes.Buffer, error)

Run executes the command given in args. The first arg must be the name of the command

type RequestError

type RequestError struct {
	Message string
	Code    int
	Status  string
	Data    map[string]interface{}
}

RequestError is returned as json formated when something went wrong during the handling of a request

func NewInternalError

func NewInternalError(msg string) RequestError

NewInternalError represents a 500 error

func NewNotAcceptedError

func NewNotAcceptedError(resp *http.Response) RequestError

NewNotAcceptedError used when a 202 response is expected

func NewNotCreatedError

func NewNotCreatedError(resp *http.Response) RequestError

NewNotCreatedError used when a 201 response is expected

func NewNotOkError

func NewNotOkError(resp *http.Response) RequestError

NewNotOkError used when a 200 response is expected

func (RequestError) Error

func (e RequestError) Error() string

type RunHTTP

type RunHTTP interface {
	Do(client *http.Client, req *http.Request) (*http.Response, error)
}

RunHTTP mocks traditional calls to an http server. This allows us to mock the enclave manager in the tests

func NewDefaultRunHTTP

func NewDefaultRunHTTP() RunHTTP

NewDefaultRunHTTP returns the default RunHTTP

type StatusNotifier

type StatusNotifier struct {
	sync.Mutex
	Status string
	// This bool indicates if the StatusNotifier is done or not. Once set to
	// true it shoudl never be set back to false
	Terminated  bool
	Subscribers []*StatusNotifierSubscriber
	ID          string
}

StatusNotifier notify subscribers about the update of a project or request status

func NewStatusNotifier

func NewStatusNotifier() *StatusNotifier

NewStatusNotifier return a new status notifier

func (*StatusNotifier) Subscribe

func (s *StatusNotifier) Subscribe() *StatusNotifierSubscriber

Subscribe creates a new StatusNotifierSubscriber that will be notified of status update.

func (*StatusNotifier) UpdateStatus

func (s *StatusNotifier) UpdateStatus(status string)

UpdateStatus updates the status and notifies all the subscribers

func (*StatusNotifier) UpdateStatusAndClose

func (s *StatusNotifier) UpdateStatusAndClose(status string)

UpdateStatusAndClose updates the status and notifies all the subscribers

type StatusNotifierSubscriber

type StatusNotifierSubscriber struct {
	NotifyStream chan string
	Done         chan bool
}

StatusNotifierSubscriber represent a client that subscribes to receive notifications about a status

func (*StatusNotifierSubscriber) Close

func (s *StatusNotifierSubscriber) Close()

Close terminates a subscriber

type StatusTask

type StatusTask string

StatusTask defines the status of a task

type Subscriber

type Subscriber struct {
	TaskStream chan *TaskEvent
	PastEvents []*TaskEvent
	Done       chan bool
}

Subscriber is a client that subscribes to be notified. We store the past events so that the client can catch up.

func (*Subscriber) Close

func (s *Subscriber) Close()

Close terminates a subscriber

type Task

type Task struct {
	sync.Mutex
	Data *TaskData
}

Task implements TaskI. It uses a publisher/subscriber pattern that allows us to asynchronously handle tasks in our app.

func (*Task) AddInfo

func (t *Task) AddInfo(source, msg, details string)

AddInfo adds a new task event of type info

- implements TaskI

func (*Task) AddInfof

func (t *Task) AddInfof(source, msg, details string, args ...interface{})

AddInfof adds a new task event of type info

- implements TaskI

func (*Task) AddTaskEvent

func (t *Task) AddTaskEvent(event TaskEvent)

AddTaskEvent adds a new event and notify the subscribers. If the event is of type closeOK or closeError, then the task is ended and the subscibers are closed.

- implements TaskI

func (*Task) CloseError

func (t *Task) CloseError(source, msg, details string)

CloseError sets the error status and closes all the clients

- implements TaskI

func (*Task) CloseOK

func (t *Task) CloseOK(source, msg, details string)

CloseOK sets the finished status and closes all the clients

- implements TaskI

func (*Task) GetData

func (t *Task) GetData() *TaskData

GetData returns the data of the task

- implements TaskI

func (*Task) MarshalBinary

func (t *Task) MarshalBinary() ([]byte, error)

MarshalBinary marshalls a task into a buffer

- implements encoding.BinaryMarshaler

func (*Task) StatusImg

func (t *Task) StatusImg() string

StatusImg return an HTML image of the status

- implements TaskI

func (*Task) Subscribe

func (t *Task) Subscribe() *Subscriber

Subscribe creates a new client and will be updated by the task when a new event occurs.

- implements TaskI

func (*Task) UnmarshalBinary

func (t *Task) UnmarshalBinary(data []byte) error

UnmarshalBinary restores the task from a buffer

- implements encoding.BinaryUnmarshaler

type TaskData

type TaskData struct {
	// A random string
	ID string
	// its index on the TaskList
	Index       int
	Subscribers []*Subscriber
	History     []*TaskEvent
	Status      StatusTask
	Description string
	StartD      string
	EndD        string
	// Should be used to allow the user going back to its task
	GoBackLink string
}

TaskData holds the data of a task. We use this structure so that it is not part of the TaskI interface and avoid the need to have a complex TaskI interface with a lot of getter/setter for those attributes. Here the user of TaskI can just use GetData() to manipulate all those attributes.

type TaskEvent

type TaskEvent struct {
	Type    TaskEventType `json:"type"`
	Time    string        `json:"time"`
	Message string        `json:"message"`
	Details string        `json:"details"`
	Source  string        `json:"source"`
}

TaskEvent is an event that happens on a specific task, stored in a chan. A task holds multiple task events and notifies all its subscribers when there is a new task event.

func NewTaskEvent

func NewTaskEvent(ttype TaskEventType, source, msg, details string) TaskEvent

NewTaskEvent creates a new task event

func NewTaskEventCloseError

func NewTaskEventCloseError(source, msg, details string) TaskEvent

NewTaskEventCloseError return a task to print an error message

func NewTaskEventCloseErrorf

func NewTaskEventCloseErrorf(source, msg, details string, args ...interface{}) TaskEvent

NewTaskEventCloseErrorf return a task to print an error message

func NewTaskEventCloseOK

func NewTaskEventCloseOK(source, msg, details string) TaskEvent

NewTaskEventCloseOK return a task to print an error message

func NewTaskEventError

func NewTaskEventError(source, msg, details string) TaskEvent

NewTaskEventError return a task to print an error

func NewTaskEventErrorf

func NewTaskEventErrorf(source, msg, details string, args ...interface{}) TaskEvent

NewTaskEventErrorf return a task to print a formatted error message

func NewTaskEventImportantInfo

func NewTaskEventImportantInfo(source, msg, details string) TaskEvent

NewTaskEventImportantInfo return a task to print info

func NewTaskEventInfo

func NewTaskEventInfo(source, msg, details string) TaskEvent

NewTaskEventInfo return a task to print info

func NewTaskEventInfof

func NewTaskEventInfof(source, msg, details string, args ...interface{}) TaskEvent

NewTaskEventInfof return a task to print a formatted info message

func NewTaskEventf

func NewTaskEventf(ttype TaskEventType, source, msg, details string, args ...interface{}) TaskEvent

NewTaskEventf creates a new task event with a formatted string as the details

func (TaskEvent) JSONStream

func (t TaskEvent) JSONStream() string

JSONStream build a Json string representation following the SSE stream format, which starts each message with "data:" and must end with a double new line.

type TaskEventFFactory

type TaskEventFFactory struct {
	Source string
	// contains filtered or unexported fields
}

TaskEventFFactory is a handy struct that make the creation of task events a bit less tidious with the HTPP flusher

func NewTaskEventFFactory

func NewTaskEventFFactory(source string, flusher http.Flusher,
	w http.ResponseWriter) *TaskEventFFactory

NewTaskEventFFactory creates a new TaskFactory

func (TaskEventFFactory) FlushTaskEventCloseError

func (t TaskEventFFactory) FlushTaskEventCloseError(msg, details string)

FlushTaskEventCloseError creates a new task and writes it to the responsewriter

func (TaskEventFFactory) FlushTaskEventCloseErrorf

func (t TaskEventFFactory) FlushTaskEventCloseErrorf(msg, details string, args ...interface{})

FlushTaskEventCloseErrorf creates a new task and writes it to the responsewriter

func (TaskEventFFactory) FlushTaskEventCloseOK

func (t TaskEventFFactory) FlushTaskEventCloseOK(msg, details string)

FlushTaskEventCloseOK creates a new task and writes it to the responsewriter

func (TaskEventFFactory) FlushTaskEventError

func (t TaskEventFFactory) FlushTaskEventError(msg, details string)

FlushTaskEventError creates a new task and writes it to the responsewriter

func (TaskEventFFactory) FlushTaskEventErrorf

func (t TaskEventFFactory) FlushTaskEventErrorf(msg, details string, args ...interface{})

FlushTaskEventErrorf creates a new task and writes it to the responsewriter

func (TaskEventFFactory) FlushTaskEventImportantInfo

func (t TaskEventFFactory) FlushTaskEventImportantInfo(msg, details string)

FlushTaskEventImportantInfo creates a new task of type important info and writes it to the responsewriter.

func (TaskEventFFactory) FlushTaskEventInfo

func (t TaskEventFFactory) FlushTaskEventInfo(msg, details string)

FlushTaskEventInfo creates a new task and writes it to the responsewriter

func (TaskEventFFactory) FlushTaskEventInfof

func (t TaskEventFFactory) FlushTaskEventInfof(msg, details string, args ...interface{})

FlushTaskEventInfof creates a new task and writes it to the responsewriter

func (TaskEventFFactory) XFlushTaskEventCloseError

func (t TaskEventFFactory) XFlushTaskEventCloseError(err2 error, msg, details string)

XFlushTaskEventCloseError takes an additional parameter, an error, that is added to the message if not nil. We need this when for example there are some extra steps that must be done to handle the error, like updating the project instance status, and those can return an error. In that case we still want to flush exit but if one of those extra steps failed, the user should know about it.

func (TaskEventFFactory) XFlushTaskEventCloseErrorf

func (t TaskEventFFactory) XFlushTaskEventCloseErrorf(err2 error, msg, details string, args ...interface{})

XFlushTaskEventCloseErrorf creates a new task and writes it to the responsewriter

type TaskEventFactory

type TaskEventFactory struct {
	Source string
}

TaskEventFactory is a handy struct that make the creation of task events a bit less tidious.

func NewTaskEventFactory

func NewTaskEventFactory(source string) *TaskEventFactory

NewTaskEventFactory creates a new TaskFactory

func (TaskEventFactory) NewTaskEventCloseError

func (t TaskEventFactory) NewTaskEventCloseError(msg, details string) TaskEvent

NewTaskEventCloseError return a task close error

func (TaskEventFactory) NewTaskEventCloseOK

func (t TaskEventFactory) NewTaskEventCloseOK(msg, details string) TaskEvent

NewTaskEventCloseOK return a task to print an error

func (TaskEventFactory) NewTaskEventError

func (t TaskEventFactory) NewTaskEventError(msg, details string) TaskEvent

NewTaskEventError return a task to print an error

func (TaskEventFactory) NewTaskEventErrorf

func (t TaskEventFactory) NewTaskEventErrorf(msg, details string, args ...interface{}) TaskEvent

NewTaskEventErrorf return a task to print a formatted error message

func (TaskEventFactory) NewTaskEventInfo

func (t TaskEventFactory) NewTaskEventInfo(msg, details string) TaskEvent

NewTaskEventInfo return a task to print info

func (TaskEventFactory) NewTaskEventInfof

func (t TaskEventFactory) NewTaskEventInfof(msg, details string, args ...interface{}) TaskEvent

NewTaskEventInfof return a task to print a formatted info message

type TaskEventSorter

type TaskEventSorter []*TaskEvent

TaskEventSorter is used to define a sorter that sorts projects by the CreatedAt field.

func (TaskEventSorter) Len

func (p TaskEventSorter) Len() int

Len returns the len

func (TaskEventSorter) Less

func (p TaskEventSorter) Less(i, j int) bool

Less compares two projects based on their CreatedAt fields

func (TaskEventSorter) Swap

func (p TaskEventSorter) Swap(i, j int)

Swap swaps

type TaskEventType

type TaskEventType string

TaskEventType defines the type of a task

type TaskI

type TaskI interface {
	CloseError(source, msg, details string)
	AddInfo(source, msg, details string)
	AddInfof(source, msg, details string, args ...interface{})
	CloseOK(source, msg, details string)
	AddTaskEvent(event TaskEvent)
	Subscribe() *Subscriber
	GetData() *TaskData
	StatusImg() string
	encoding.BinaryMarshaler
	encoding.BinaryUnmarshaler
}

TaskI defines the primitives needed for a standard task. This abstraction allows us to better test our program.

type TaskManagerI

type TaskManagerI interface {
	NewTask(title string) TaskI
	NumTasks() int
	GetTask(index int) TaskI
	GetSortedTasks() []TaskI
	DeleteAllTasks()
	RestoreTasks(tasks []TaskI) error
}

TaskManagerI defines all the primitives needed to handle tasks. Having this interface makes testing easier.

type TaskSorter

type TaskSorter []*Task

TaskSorter is used to define a sorter that sorts tasks by their Index field

func (TaskSorter) Len

func (p TaskSorter) Len() int

Len returns the len

func (TaskSorter) Less

func (p TaskSorter) Less(i, j int) bool

Less compares two Task based on their CreatedAt fields

func (TaskSorter) Swap

func (p TaskSorter) Swap(i, j int)

Swap swaps

Jump to

Keyboard shortcuts

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