codetainer

package module
v0.0.0-...-30b2c5b Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2016 License: MIT Imports: 43 Imported by: 7

README

codetainer

codetainer gif

Build Status

codetainer allows you to create code 'sandboxes' you can embed in your web applications (think of it like an OSS clone of codepicnic.com).

Codetainer runs as a webservice and provides APIs to create, view, and attach to the sandbox along with a nifty HTML terminal you can interact with the sandbox in realtime. It uses Docker and its introspection APIs to provide the majority of this functionality.

Codetainer is written in Go.

For more information, see the slides from a talk introduction.

Build & Installation

Requirements

  • Docker >=1.8 (required for file upload API)
  • Go >=1.4
  • godep
Building & Installing From Source
# set your $GOPATH
go get github.com/codetainerapp/codetainer  
# you may get errors about not compiling due to Asset missing, it's ok. bindata.go needs to be created
# by `go generate` first.
cd $GOPATH/src/github.com/codetainerapp/codetainer
# make install_deps  # if you need the dependencies like godep
make

This will create ./bin/codetainer.

Configuring Docker

You must configure Docker to listen on a TCP port.

DOCKER_OPTS="-H tcp://127.0.0.1:4500 -H unix:///var/run/docker.sock"

Configuring codetainer

See ~/.codetainer/config.toml. This file will get auto-generated the first time you run codetainer, please edit defaults as appropriate.

# Docker API server and port
DockerServer = "localhost"
DockerPort = 4500

# Enable TLS support (optional, if you access to Docker API over HTTPS)
# DockerServerUseHttps = true
# Certificate directory path (optional)
#   e.g. if you use Docker Machine: "~/.docker/machine/certs"
# DockerCertPath = "/path/to/certs"

# Database path (optional, default is ~/.codetainer/codetainer.db)
# DatabasePath = "/path/to/codetainer.db"

Running an example codetainer

$ sudo docker pull ubuntu:14.04
$ codetainer image register ubuntu:14.04
$ codetainer create ubuntu:14.04 my-codetainer-name
$ codetainer server  # to start the API server on port 3000
Embedding a codetainer in your web app
  1. Copy codetainer.js to your webapp.
  2. Include codetainer.js and jquery in your web page. Create a div to house the codetainer terminal iframe (it's #terminal in the example below).
<!DOCTYPE html>
<html>
 <head>
   <meta charset="UTF-8">
   <title>lsof tutorial</title>
   <link rel='stylesheet' href='/stylesheets/style.css' />
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="/javascripts/codetainer.js"></script>
   <script src="/javascripts/lsof.js"></script>
 </head>
 <body>
    <div id="terminal" data-container="YOUR CODETAINER ID HERE"> 
 </body>
</html> 
  1. Run the javascript to load the codetainer iframe from the codetainer API server (supply data-container as the id of codetainer on the div, or supply codetainer in the constructor options).
 $('#terminal').codetainer({
     terminalOnly: false,                 // set to true to show only a terminal window 
     url: "http://127.0.0.1:3000",        // replace with codetainer server URL
     container: "YOUR CONTAINER ID HERE",
     width: "100%",
     height: "100%",
  });
API Documentation

TODO

Profiles

TODO more documentation.

You can use profiles to apply Docker configs to limit CPU, memory, network access, and more.

See example profiles for some examples of this.

Register a profile to use with codetainer using codetainer profile register <path-to-json> <name of profile> and then supply codetainer-config-id when POST'ing to /api/v1/codetainer to create.

Status

Codetainer is unstable and in active development.

Documentation

Overview

Package codetainer Codetainer API

This API allows you to create, attach, and interact with codetainers.

Schemes: http, https
Host: localhost
BasePath: /api/v1
Version: 0.0.1
License: MIT http://opensource.org/licenses/MIT
Contact: info@codetainer.org

Consumes:
- application/json

Produces:
- application/json

swagger:meta

Index

Constants

View Source
const (
	// Name application name
	Name = "Codetainer"

	// Description
	Description = ""

	// Version application version number
	Version = "0.1.0"
)
View Source
const (
	// Email regex
	Email string = "" /* 1212-byte string literal not displayed */
)

Variables

View Source
var (
	// Build SHA
	Build string

	// TimeFormat global time format string
	TimeFormat = "15:04:05"

	// Log Global logger
	Log *mlog.Logger

	// DevMode Development mode switch. If true
	// debug logging and serving assets from disk
	// is enabled.
	DevMode bool

	// TestMode
	TestMode bool
)
View Source
var (
	//
	// Default command to start in a container
	//
	DefaultExecCommand string = "/bin/bash"
)
View Source
var DockerApiVersion string = "1.17"

Functions

func CloseDb

func CloseDb(db *Database)

func CodetainerList

func CodetainerList()

func CodetainerRemove

func CodetainerRemove(id string)

func ComputeMd5

func ComputeMd5(filePath string) ([]byte, error)

func CreateCodetainer

func CreateCodetainer(imageId string, name string)

func DateFormat

func DateFormat(t time.Time, format string) string

func GetRemoteAddr

func GetRemoteAddr(req *http.Request) (string, error)

func IsEmail

func IsEmail(str string) bool

IsEmail checks a string to validate its a proper email address

func IsExist

func IsExist(path string) bool

IsExist checks whether a file or directory exists. It returns false when the file or directory does not exist.

func ListCodetainerImages

func ListCodetainerImages()

func ListCodetainerProfiles

func ListCodetainerProfiles()

func RegisterCodetainerImage

func RegisterCodetainerImage(id string, command string)

func RegisterCodetainerProfile

func RegisterCodetainerProfile(pathToProfile string, name string)

func RouteApiV1Codetainer

func RouteApiV1Codetainer(ctx *Context) error

func RouteApiV1CodetainerAttach

func RouteApiV1CodetainerAttach(ctx *Context) error

Attach to a codetainer

func RouteApiV1CodetainerCreate

func RouteApiV1CodetainerCreate(ctx *Context) error

CodetainerCreate swagger:route POST /codetainer codetainer codetainerCreate

Create a new codetainer.

Responses:

default: APIErrorResponse
    200: CodetainerBody

func RouteApiV1CodetainerFile

func RouteApiV1CodetainerFile(ctx *Context) error

func RouteApiV1CodetainerFileDownload

func RouteApiV1CodetainerFileDownload(ctx *Context) error

FileDownload swagger:route GET /codetainer/{id}/file/download codetainer fileDownload

Download a file from a codetainer. Requires path={path of file to download}. Returns the multipart messsage with the file bytes.

Responses:

default: APIErrorResponse
    200: Object

func RouteApiV1CodetainerFileList

func RouteApiV1CodetainerFileList(ctx *Context) error

ListFiles swagger:route GET /codetainer/{id}/filescodetainer listFiles

List Files in a codetainer

Responses:

default: APIErrorResponse
    200: Object

func RouteApiV1CodetainerFileUpload

func RouteApiV1CodetainerFileUpload(ctx *Context) error

CodetainerFileUpload swagger:route PUT /codetainer/{id}/file codetainerFileUpload

Upload a file to a codetainer

Responses:

default: APIErrorResponse
    200: CodetainerListBody

func RouteApiV1CodetainerGet

func RouteApiV1CodetainerGet(ctx *Context) error

CodetainerGet swagger:route GET /codetainer/{id} codetainer codetainerGet

Get a codetainer

Responses:

default: APIErrorResponse
    200: CodetainerBody

func RouteApiV1CodetainerGetCurrentTTY

func RouteApiV1CodetainerGetCurrentTTY(ctx *Context) error

GetCurrentTTY swagger:route GET /codetainer/{id}/tty codetainer getCurrentTTY

Return the codetainer TTY height and width.

Responses:

default: APIErrorResponse
    200: TTYBody

func RouteApiV1CodetainerId

func RouteApiV1CodetainerId(ctx *Context) error

func RouteApiV1CodetainerImage

func RouteApiV1CodetainerImage(ctx *Context) error

func RouteApiV1CodetainerImageCreate

func RouteApiV1CodetainerImageCreate(ctx *Context) error

ImageCreate swagger:route POST /image codetainer imageCreate

Register a Docker image to be used as a codetainer.

Responses:

default: APIErrorResponse
    200: CodetainerImageBody

func RouteApiV1CodetainerImageList

func RouteApiV1CodetainerImageList(ctx *Context) error

ImageList swagger:route GET /image codetainer imageList

List all codetainer images.

Responses:

default: APIErrorResponse
    200: CodetainerImageListBody

func RouteApiV1CodetainerList

func RouteApiV1CodetainerList(ctx *Context) error

CodetainerList swagger:route GET /codetainer codetainer codetainerList

List all codetainers

Responses:

default: APIErrorResponse
    200: CodetainerListBody

func RouteApiV1CodetainerRemove

func RouteApiV1CodetainerRemove(ctx *Context) error

CodetainerRemove swagger:route DELETE /codetainer/{id} codetainer codetainerRemove

Remove a codetainer

Responses:

default: APIErrorResponse
    200: CodetainerBody

func RouteApiV1CodetainerSend

func RouteApiV1CodetainerSend(ctx *Context) error

SendCommand swagger:route POST /codetainer/{id}/send codetainer sendCommand

Send a command to a container

Responses:

default: APIErrorResponse
    200: GenericSuccess

func RouteApiV1CodetainerStart

func RouteApiV1CodetainerStart(ctx *Context) error

CodetainerStart swagger:route POST /codetainer/{id}/start codetainer codetainerStart

Start a stopped codetainer

Responses:

default: APIErrorResponse
    200: CodetainerBody

func RouteApiV1CodetainerStop

func RouteApiV1CodetainerStop(ctx *Context) error

CodetainerStop swagger:route POST /codetainer/{id}/stop codetainer codetainerStop

Stop a codetainer

Responses:

default: APIErrorResponse
    200: CodetainerBody

func RouteApiV1CodetainerTTY

func RouteApiV1CodetainerTTY(ctx *Context) error

func RouteApiV1CodetainerUpdateCurrentTTY

func RouteApiV1CodetainerUpdateCurrentTTY(ctx *Context) error

UpdateCurrentTTY swagger:route POST /codetainer/{id}/tty codetainer updateCurrentTTY

Update the codetainer TTY height and width.

Responses:

default: APIErrorResponse
    200: TTYBody

func RouteApiV1CodetainerView

func RouteApiV1CodetainerView(ctx *Context) error

View codetainer

func RouteIndex

func RouteIndex(ctx *Context) error

func Start

func Start()

func StartServer

func StartServer()

func UrlEncoded

func UrlEncoded(str string) (string, error)

Types

type APIErrorResponse

type APIErrorResponse struct {
	Error   bool   `json:"error" description:"set if an error is returned"`
	Message string `json:"message" description:"error message string"`
}

Return type for errors

swagger:response APIErrorResponse

type Codetainer

type Codetainer struct {
	Id        string    `schema:"id" json:"id"`
	Name      string    `schema:"name" json:"name"`
	ImageId   string    `schema:"image-id" json:"image-id"`
	Defunct   bool      `schema"-"`          // false if active
	Running   bool      `schema"-" xorm:"-"` // true if running
	Profile   string    `schema:"-"`
	CreatedAt time.Time `schema:"-"`
	UpdatedAt time.Time `schema:"-"`
}

Codetainer data structure.

swagger:parameters codetainerCreate

func (*Codetainer) Create

func (codetainer *Codetainer) Create(db *Database) error

func (*Codetainer) DownloadFile

func (codetainer *Codetainer) DownloadFile(filePath string) ([]byte, error)

func (*Codetainer) GetProfileSpec

func (c *Codetainer) GetProfileSpec() (*CodetainerProfileSpec, error)

func (*Codetainer) Lookup

func (codetainer *Codetainer) Lookup(db *Database) error

func (*Codetainer) LookupByNameOrId

func (codetainer *Codetainer) LookupByNameOrId(id string, db *Database) error

func (*Codetainer) Remove

func (codetainer *Codetainer) Remove(db *Database) error

func (*Codetainer) Save

func (c *Codetainer) Save(db *Database) error

func (*Codetainer) Start

func (codetainer *Codetainer) Start() error

func (*Codetainer) Stop

func (codetainer *Codetainer) Stop() error

func (*Codetainer) UploadFile

func (codetainer *Codetainer) UploadFile(
	fileData []byte,
	fileName string,
	dstFolder string) error

Upload a file to a `dstPath` in a container.

type CodetainerBody

type CodetainerBody struct {
	Codetainer `json:"codetainer"`
}

Codetainer response

swagger:response CodetainerBody

type CodetainerConfig

type CodetainerConfig struct {
	// id
	Id   string `xorm:"not null unique pk varchar(128)" json:"id" schema:"id"`
	Name string `xorm:"not null unique" json:"name" schema:"-"`
	// profile string with the CodetainerSpec format
	Profile   string    `json:"profile" schema:"profile"`
	CreatedAt time.Time `schema:"-"`
	UpdatedAt time.Time `schema:"-"`
	Enabled   bool
}

func (*CodetainerConfig) GetProfileSpec

func (c *CodetainerConfig) GetProfileSpec() (*CodetainerProfileSpec, error)

func (*CodetainerConfig) Lookup

func (c *CodetainerConfig) Lookup(db *Database) error

func (*CodetainerConfig) LookupByNameOrId

func (c *CodetainerConfig) LookupByNameOrId(db *Database) error

func (*CodetainerConfig) Save

func (c *CodetainerConfig) Save(db *Database) error

func (*CodetainerConfig) Validate

func (c *CodetainerConfig) Validate() error

type CodetainerCreateParams

type CodetainerCreateParams struct {
	Codetainer
	CodetainerConfigId string `schema:"codetainer-config-id" json:"codetainer-config-id"`
}

Codetainer Create Params

swagger:parameters CodetainerCreate

type CodetainerImage

type CodetainerImage struct {
	Id                  string    `xorm:"varchar(128) not null unique" json:"id" schema:"id"`
	DefaultStartCommand string    `json:"command" schema:"command"`
	Description         string    `json:"description" schema:"description"`
	Tags                []string  `schema:"-"`
	CreatedAt           time.Time `schema:"-"`
	UpdatedAt           time.Time `schema:"-"`
	Enabled             bool
}

Container image.

swagger:parameters imageCreate

func (*CodetainerImage) Register

func (img *CodetainerImage) Register(db *Database) error

type CodetainerImageBody

type CodetainerImageBody struct {
	Image CodetainerImage `json:"image"`
}

CodetainerImage response

swagger:response CodetainerImageBody

type CodetainerImageListBody

type CodetainerImageListBody struct {
	Images []CodetainerImage `json:"images"`
}

CodetainerImageList response

swagger:response CodetainerImageListBody

type CodetainerListBody

type CodetainerListBody struct {
	Codetainers []Codetainer `json:"codetainers"`
}

CodetainerList response

swagger:response CodetainerListBody

type CodetainerProfileSpec

type CodetainerProfileSpec struct {
	Config     *docker.Config     `json:"Config,omitempty" yaml:"Config,omitempty"`
	HostConfig *docker.HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty"`
}

type Config

type Config struct {
	DockerServerUseHttps bool
	DockerServer         string
	DockerPort           int
	DockerCertPath       string
	DatabasePath         string
	// contains filtered or unexported fields
}
var (
	DefaultConfigFileSettings = `# Docker API server and port 
DockerServer = "localhost"
DockerPort = 4500`
	GlobalConfig Config
)

func NewConfig

func NewConfig(configPath string) (*Config, error)

func (*Config) GetDatabase

func (c *Config) GetDatabase() (*Database, error)

func (*Config) GetDatabasePath

func (c *Config) GetDatabasePath() string

func (*Config) GetDockerClient

func (c *Config) GetDockerClient() (*docker.Client, error)

func (*Config) GetDockerEndpoint

func (c *Config) GetDockerEndpoint() string

func (*Config) TestConfig

func (c *Config) TestConfig() bool

Ensure a configuration is valid and all dependencies are installed.

func (*Config) Url

func (c *Config) Url() string

func (*Config) UtilsPath

func (c *Config) UtilsPath() string

type ContainerConnection

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

func (*ContainerConnection) SendSingleMessage

func (c *ContainerConnection) SendSingleMessage(msg string) error

func (*ContainerConnection) Start

func (c *ContainerConnection) Start() error

type Context

type Context struct {
	Session *sessions.Session
	W       http.ResponseWriter
	R       *http.Request
	WS      *websocket.Conn
}

type Database

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

func NewDatabase

func NewDatabase(dbPath string) (*Database, error)

func (*Database) ListCodetainerImages

func (db *Database) ListCodetainerImages() (*[]CodetainerImage, error)

func (*Database) ListCodetainers

func (db *Database) ListCodetainers() (*[]Codetainer, error)

List all running codetainers

func (*Database) LookupCodetainerImage

func (db *Database) LookupCodetainerImage(id string) (*CodetainerImage, error)

List codetainer images

type GenericSuccess

type GenericSuccess struct {
	Success bool `json:"success"`
}

type ShortFileInfo

type ShortFileInfo struct {
	Name    string    `json:"name"`
	Size    int64     `json:"size"`
	IsDir   bool      `json:"is_dir"`
	IsLink  bool      `json:"is_link"`
	ModTime time.Time `json:"modified_time"`
}

func NewShortFileInfo

func NewShortFileInfo(f os.FileInfo) *ShortFileInfo

type TTY

type TTY struct {
	Height int `json:"height" description:"height of tty"`
	Width  int `json:"width" description:"width of tty"`
}

TTY parameters for a codetainer

swagger:parameters updateCurrentTTY

type TTYBody

type TTYBody struct {
	Tty TTY `json:"tty"`
}

TTY response

swagger:response TTYBody

Directories

Path Synopsis
Godeps
_workspace/src/github.com/Unknwon/com
Package com is an open source project for commonly used functions for the Go programming language.
Package com is an open source project for commonly used functions for the Go programming language.
_workspace/src/github.com/alecthomas/template
Package template implements data-driven templates for generating textual output.
Package template implements data-driven templates for generating textual output.
_workspace/src/github.com/alecthomas/template/parse
Package parse builds parse trees for templates as defined by text/template and html/template.
Package parse builds parse trees for templates as defined by text/template and html/template.
_workspace/src/github.com/alecthomas/units
Package units provides helpful unit multipliers and functions for Go.
Package units provides helpful unit multipliers and functions for Go.
_workspace/src/github.com/dustin/go-humanize
Package humanize converts boring ugly numbers to human-friendly strings and back.
Package humanize converts boring ugly numbers to human-friendly strings and back.
_workspace/src/github.com/elazarl/go-bindata-assetfs
assetfs allows packages to serve static content embedded with the go-bindata tool with the standard net/http package.
assetfs allows packages to serve static content embedded with the go-bindata tool with the standard net/http package.
_workspace/src/github.com/fsouza/go-dockerclient
Package docker provides a client for the Docker remote API.
Package docker provides a client for the Docker remote API.
_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/parsers
Package parsers provides helper functions to parse and validate different type of string.
Package parsers provides helper functions to parse and validate different type of string.
_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools
Package pools provides a collection of pools which provide various data types with buffers.
Package pools provides a collection of pools which provide various data types with buffers.
_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ulimit
Package ulimit provides structure and helper function to parse and represent resource limits (Rlimit and Ulimit, its human friendly version).
Package ulimit provides structure and helper function to parse and represent resource limits (Rlimit and Ulimit, its human friendly version).
_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units
Package units provides helper function to parse and print size and time units in human-readable format.
Package units provides helper function to parse and print size and time units in human-readable format.
_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context
Package context stores values shared during a request lifetime.
Package context stores values shared during a request lifetime.
_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux
Package gorilla/mux implements a request router and dispatcher.
Package gorilla/mux implements a request router and dispatcher.
_workspace/src/github.com/fsouza/go-dockerclient/testing
Package testing provides a fake implementation of the Docker API, useful for testing purpose.
Package testing provides a fake implementation of the Docker API, useful for testing purpose.
_workspace/src/github.com/go-xorm/xorm
Package xorm is a simple and powerful ORM for Go.
Package xorm is a simple and powerful ORM for Go.
_workspace/src/github.com/gorilla/context
Package context stores values shared during a request lifetime.
Package context stores values shared during a request lifetime.
_workspace/src/github.com/gorilla/mux
Package gorilla/mux implements a request router and dispatcher.
Package gorilla/mux implements a request router and dispatcher.
_workspace/src/github.com/gorilla/schema
Package gorilla/schema fills a struct with form values.
Package gorilla/schema fills a struct with form values.
_workspace/src/github.com/gorilla/securecookie
Package gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values.
Package gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values.
_workspace/src/github.com/gorilla/sessions
Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.
Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.
_workspace/src/github.com/gorilla/websocket
Package websocket implements the WebSocket protocol defined in RFC 6455.
Package websocket implements the WebSocket protocol defined in RFC 6455.
_workspace/src/github.com/gorilla/websocket/examples/autobahn
Command server is a test server for the Autobahn WebSockets Test Suite.
Command server is a test server for the Autobahn WebSockets Test Suite.
_workspace/src/github.com/mattn/go-sqlite3
Package sqlite3 provides interface to SQLite3 databases.
Package sqlite3 provides interface to SQLite3 databases.
_workspace/src/github.com/pborman/uuid
The uuid package generates and inspects UUIDs.
The uuid package generates and inspects UUIDs.
_workspace/src/gopkg.in/alecthomas/kingpin.v2
Package kingpin provides command line interfaces like this: $ chat usage: chat [<flags>] <command> [<flags>] [<args> ...] Flags: --debug enable debug mode --help Show help.
Package kingpin provides command line interfaces like this: $ chat usage: chat [<flags>] <command> [<flags>] [<args> ...] Flags: --debug enable debug mode --help Show help.
_workspace/src/gopkg.in/alecthomas/kingpin.v2/examples/curl
A curl-like HTTP command-line client.
A curl-like HTTP command-line client.
cmd

Jump to

Keyboard shortcuts

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