containers

package module
v0.0.0-...-921e06b Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2023 License: Apache-2.0 Imports: 14 Imported by: 0

README

go-containers

A pre-made Golang module for easily spinning up and managing lxd containers.

Go Report Card

  • Author: John Connor Sanders
  • License: Apache Version 2.0
  • Version Release Date: 04/18/2021
  • Current Version: 0.0.3
  • Developed for Ubuntu 20.x

License

  • Copyright 2021 John Connor Sanders

This source code of this package is released under the Apache Version 2.0 license. Please see the LICENSE for the full content of the license.

Installation

$ go get github.com/JECSand/go-containers

Dependencies

Ensure that LXD is installed and running on your environment
  • Use the provided lxd installer script if needed:
$ . ./build_lxd.sh

Module Main Data Structs

###1. GoCluster

type GoCluster struct {
    Name         string
    Type         string
    ReverseProxy string
    LoadBalancer string
    Controller   string
    Containers   []*GoContainer
    Images       []*GoImage
    Network      *Network
}
  • ###GoCluster Methods

    I. Scan()

    func (gc *GoCluster) Scan() ([]*GoContainers, error)
    

    II. CreateContainer()

    func (gc *GoCluster) CreateContainer(auth *Auth, controller bool, name string, cType string, cRelease string, config []byte) error
    

    III. GetContainers()

    func (gc *GoCluster) GetContainers() ([]*GoContainer, error)
    

    IV. GetContainer()

    func (gc *GoCluster) GetContainer(containerName string) (*GoContainer, error)
    

    V. DeleteContainer()

    func (gc *GoCluster) DeleteContainer(containerName string) error
    

    VI. ExportContainer()

    func (gc *GoCluster) ExportContainer(containerName string) (*GoImage, error)
    

    VII. ImportContainer()

    func (gc *GoCluster) ImportContainer(containerName string, image *GoImage) (*GoContainer, error)
    

    VIII. ScanImages()

    func (gc *GoCluster) ScanImages() ([]*GoImage, error)
    

    IX. CreateImage()

    func (gc *GoCluster) CreateImage(containerName string, sName string) error 
    

    X. DeleteImage()

    func (gc *GoCluster) DeleteImage(fingerprint string) error
    

###2. Network

type Network struct {
    PublicIP    string
    PrivateIP   string
    HWAddr      string
    Type        string
    HostName    string
    SSL         bool
    DNS         string
    Connections []*Connection
}

###3. GoContainer

type GoContainer struct {
    Name        string
    Controller  bool
    SSHClient   *SSHClient
    Type        string
    Release     string
    Services    []string
    InitFile    []byte
    Storage     string
    Network     *Network
    Auth        *Auth
    GoSnapshots []*GoSnapshot
    Status      string
}
  • ###GoContainer Methods

    I. Create()

    func (c *GoContainer) Create() error
    

    II. Stop()

    func (c *GoContainer) Stop() error
    

    II. Boot()

    func (c *GoContainer) Boot() error
    

    III. Reboot()

    func (c *GoContainer) Reboot() error
    

    IV. Delete()

    func (c *GoContainer) Delete() error
    

    V. CreateSnapshot()

    func (c *GoContainer) CreateSnapshot() (string, error)
    

    VI. GetSnapshots()

    func (c *GoContainer) GetSnapshots() ([]*GoSnapshot, error) 
    

    VII. Restore()

    func (c *GoContainer) Restore(snapshotName string) error
    

    VIII. Image()

    func (c *GoContainer) Image(snapshotName string) (*GoImage, error) 
    

    IX. Export()

    func (c *GoContainer) Export() (*GoImage, error) 
    

    X. Import()

    func (c *GoContainer) Import(image *GoImage) error
    

    XI. CMD()

    func (c *GoContainer) CMD(cmd string, userName string, reErr bool) ([]byte, error)
    

    XII. OpenSSH()

    func (c *GoContainer) OpenSSH() error 
    

###4. GoContainer.Auth

type Auth struct {
    User           string
    Type           string
    Credential     string
    SecurityString string
    Port           string
}

###5. GoContainer.GoSnapshot

type GoSnapshot struct {
    Name       string
    DateTime   string
}

###6. GoContainer.SSHClient

type SSHClient struct {
    SSHConn   *ssh.Client
}
  • ###SSHClient Methods

    I. Close()

    func (ssh *SSHClient) Close() error
    

###7. GoImage

type GoImage struct {
    Name        string
    Type        string
    Fingerprint string
    TarMeta     []string
    Contents    [][]byte
    DateTime    string
}
  • ###GoImage Methods

    I. Import()

    func (im *GoImage) Import() error
    

    II. Export()

    func (im *GoImage) Export() error
    

Usage Examples

package main

import (
	"fmt"
	"github.com/JECSand/go-containers"
	"log"
)

func main() {
	// #1: Declare a Cluster of LXC GoContainers
	goCluster := containers.NewGoCluster("test", "ubuntu", "HA-Proxy", "nginx", "")
	
	// #2: Scan your cluster for existing containers at any time to reload the GoContainer Map
	clusterContains, err := goCluster.Scan()
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Println(clusterContains)
	
	// #3: Create a New GoContainer
	//       -Params: Username, AuthType, Pass/Key, SecretKey, SSH Port
	cAuth := containers.NewAuth("envUserName", "password", "envPW", "SecurityString*", "22") // Auth for the GoContainer
	// *Note: SecurityString is for SSH Key Auth, which is coming soon
	isCluterControllerNode := true
	//  Create the new GoContainer
	//       -Params: Auth, isController, ContainerName, ContainerOS, osRelease, CloudInitFile
	err = goCluster.CreateContainer(cAuth, isCluterControllerNode, "testContainer", "ubuntu", "xenial", []byte{})
	if err != nil {
		log.Fatal(err.Error())
	}
	
	// #4: Get a GoContainer from GoCluster
	goCon, err := goCluster.GetContainer("testContainer")
	if err != nil {
		log.Fatal(err.Error())
	}
	goCon.Auth = cAuth
	
	// #5: Open a SSHClient on your GoContainer
	err = goCon.OpenSSH()
	if err != nil {
		log.Fatal(err.Error())
	}
	
	// #6: Execute Shell Commands on your GoContainer via SSH
	cmd := "echo Hello GoContainer ; sudo apt-get -y update"
	sshSession, _ := goCon.SSHClient.SSHConn.NewSession()
	defer sshSession.Close()
	sshSession.Run(cmd) // Execute the SSH Command
	// #7: Close the SSHClient Session
	goCon.SSHClient.close()
	
	// #8: Execute a Shell Command on your GoContainer via lxc exec
	out, _ := goCon.CMD("pwd", "ubuntu", false)
	fmt.Println("Remote Command Output: ", string(out))
	
	// #9: Export GoContainer to GoImage
	reImg, err := goCluster.ExportContainer("testContainer")
	if err != nil {
		log.Fatal("Error Exporting the GoContainer: ", err.Error())
	}
	// Exported GoContainer's contents stored in tar.gz format
	fmt.Println(reImg.TarMeta[0])
	fmt.Println(len(reImg.Contents[0]))

	// #10: Import GoContainer from a GoImage
	imCon, err := goCluster.ImportContainer("ImportedContainer", reImg)
	if err != nil {
		log.Fatal("Error Importing the GoContainer: ", err.Error())
	}
	fmt.Println(imCon.Name)
	
	// #11: Delete GoContainer from GoCluster
	err = goCluster.DeleteContainer("testContainer")
	if err != nil {
		log.Fatal(err.Error())
	}
	
	// #12: Get all GoContainers in GoCluster
	goCons, err := goCluster.GetContainers()
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Println(goCons)
}

Documentation

Index

Constants

View Source
const SRCYAML = `` /* 1046-byte string literal not displayed */

TODO: Build in system for generating cloud init config with proper ssh keys!

View Source
const ShellToUse = "bash"

Variables

This section is empty.

Functions

func BASH

func BASH(command string) ([]byte, []byte, error)

BASH

func SHELL

func SHELL(name string, sType string, cmdStr string) ([][]byte, error)

SHELL executes a unix shell Cmd

Types

type Auth

type Auth struct {
	User           string
	Type           string
	Credential     string
	SecurityString string
	Port           string
}

Auth stores auth information for a GoContainer's user

func NewAuth

func NewAuth(name string, cType string, credential string, SecurityString string, port string) *Auth

NewAuth create a pointer to a new Connection

type CMD

type CMD struct {
	Type        string
	ScriptName  string
	Raw         string
	Args        []string
	Cmd         *exec.Cmd
	Status      int // 0 - Error, 1 - Initialized, 2 - Executed, 3 - Finished
	OutputBytes []byte
}

CMD defines a async os command

func (*CMD) Execute

func (cm *CMD) Execute() error

Execute a CMD

type Connection

type Connection struct {
	Name string
	Type string
	Port string
}

Connection stores info relating to externally connecting to a GoContainer

func NewConnection

func NewConnection(name string, cType string, port string) *Connection

NewConnection create a pointer to a new Connection

type ContainSnapshot

type ContainSnapshot struct {
	Name         string    `json:"name,omitempty"`
	Architecture string    `json:"architecture,omitempty"`
	Config       LXCConfig `json:"config,omitempty"`
	LastUsed     string    `json:"last_used_at,omitempty"`
}

ContainSnapshot

type ContainerCPU

type ContainerCPU struct {
	Usage int `json:"usage,omitempty"`
}

ContainerCPU

type ContainerMemory

type ContainerMemory struct {
	Usage     int `json:"usage,omitempty"`
	UsagePeak int `json:"usage_peak,omitempty"`
}

ContainerMemory

type ContainerNetwork

type ContainerNetwork struct {
	Usage     int `json:"usage,omitempty"`
	UsagePeak int `json:"usage_peak,omitempty"`
}

ContainerNetwork

type ContainerOutput

type ContainerOutput struct {
	Architecture string         `json:"architecture,omitempty"`
	Config       LXCConfig      `json:"config,omitempty"`
	State        ContainerState `json:"state,omitempty"`
	Name         string         `json:"name,omitempty"`
	Status       string         `json:"status,omitempty"`
	StatusCode   int            `json:"status_code,omitempty"`
	LastUsed     string         `json:"last_used_at,omitempty"`
}

ContainerOutput

type ContainerState

type ContainerState struct {
	Memory    ContainerMemory   `json:"memory,omitempty"`
	CPU       ContainerCPU      `json:"cpu,omitempty"`
	PID       int               `json:"pid,omitempty"`
	Processes int               `json:"processes,omitempty"`
	SnapShots []ContainSnapshot `json:"snapshots,omitempty"`
}

ContainerState

type GoCluster

type GoCluster struct {
	Name         string
	Type         string
	ReverseProxy string
	LoadBalancer string
	Controller   string
	Containers   []*GoContainer
	Images       []*GoImage
	Network      *Network
}

A GoCluster is a deployment of GoContainers

func NewGoCluster

func NewGoCluster(name string, cType string, reverseProxy string, loadBalancer string, controller string) *GoCluster

NewGoCluster creates a pointer to a new GoCluster

func (*GoCluster) CreateContainer

func (cu *GoCluster) CreateContainer(auth *Auth, controller bool, name string, cType string, cRelease string, config []byte) error

CreateContainer create a new GoContainer in the GoCluster

func (*GoCluster) CreateImage

func (cu *GoCluster) CreateImage(cName string, sName string) error

CreateImage an image of a GoCluster's GoContainer

func (*GoCluster) DeleteContainer

func (cu *GoCluster) DeleteContainer(cName string) error

DeleteContainer deletes the GoContainer whose name is inputted

func (*GoCluster) DeleteImage

func (cu *GoCluster) DeleteImage(fingerprint string) error

DeleteImage an Image from the GoCluster

func (*GoCluster) ExportContainer

func (cu *GoCluster) ExportContainer(cName string) (*GoImage, error)

ExportContainer from the GoCluster

func (*GoCluster) GetContainer

func (cu *GoCluster) GetContainer(cName string) (*GoContainer, error)

GetContainer gets a single container back from the GoCluster with GoContainer name as the filter

func (*GoCluster) GetContainers

func (cu *GoCluster) GetContainers() ([]*GoContainer, error)

GetContainers gets all containers for a given GoCluster

func (*GoCluster) ImportContainer

func (cu *GoCluster) ImportContainer(containerName string, image *GoImage) (*GoContainer, error)

ImportContainer into the GoCluster

func (*GoCluster) Scan

func (cu *GoCluster) Scan() ([]*GoContainer, error)

Scan gets each GoContainer in a given GoCluster

func (*GoCluster) ScanImages

func (cu *GoCluster) ScanImages() ([]*GoImage, error)

ScanImages from a GoCluster

type GoContainer

type GoContainer struct {
	Name        string
	Controller  bool
	SSHClient   *SSHClient
	Type        string
	Release     string
	Services    []string
	InitFile    []byte
	Storage     string
	Network     *Network
	Auth        *Auth
	GoSnapshots []*GoSnapshot
	Status      string
}

A GoContainer defines the structure of a lxc container

func NewGoContainer

func NewGoContainer(name string, controller bool, cType string, release string, services []string, initFile []byte, storage string, network *Network, auth *Auth) *GoContainer

NewGoContainer creates a pointer to a new GoContainer

func (*GoContainer) Boot

func (co *GoContainer) Boot() error

Boot boots an offline GoContainer

func (*GoContainer) CMD

func (co *GoContainer) CMD(cmd string, userName string, reErr bool) ([]byte, error)

CMD executes a command on a GoContainer

func (*GoContainer) Create

func (co *GoContainer) Create() error

Create a new GoContainer

func (*GoContainer) CreateSnapshot

func (co *GoContainer) CreateSnapshot() (string, error)

CreateSnapshot creates a new GoSnapshot off an existing GoContainer

func (*GoContainer) Delete

func (co *GoContainer) Delete() error

Delete an existing GoContainer from the GoCluster

func (*GoContainer) DeleteSnapshot

func (co *GoContainer) DeleteSnapshot(snapName string) error

DeleteSnapshot deletes a GoSnapshot

func (*GoContainer) Export

func (co *GoContainer) Export() (*GoImage, error)

Export a GoContainer from the GoCluster

func (*GoContainer) GetSnapshots

func (co *GoContainer) GetSnapshots() ([]*GoSnapshot, error)

GetSnapshots for all containers

func (*GoContainer) Image

func (co *GoContainer) Image(snapShot string) (*GoImage, error)

Image of the GoContainer

func (*GoContainer) Import

func (co *GoContainer) Import(image *GoImage) error

Import a GoContainer into the GoCluster

func (*GoContainer) OpenSSH

func (co *GoContainer) OpenSSH() error

OpenSSH begins an SSHClient session

func (*GoContainer) Reboot

func (co *GoContainer) Reboot() error

Reboot Stops then Boots an online GoContainer

func (*GoContainer) Restore

func (co *GoContainer) Restore(snapName string) error

Restore a GoContainer from a snapshot

func (*GoContainer) Stop

func (co *GoContainer) Stop() error

Stop shutdowns a GoContainer

type GoImage

type GoImage struct {
	Name        string
	Type        string
	Fingerprint string
	TarMeta     []string
	Contents    [][]byte
	DateTime    string
}

GoImage represents a GoImage of a GoContainer stored in the cluster

func NewGoImage

func NewGoImage(name string, iType string, fingerprint string, dt string) *GoImage

NewGoImage loads a new GoImage

func (*GoImage) Export

func (im *GoImage) Export() error

Export a GoImage

func (*GoImage) Import

func (im *GoImage) Import() error

Import a GoImage

type GoSnapshot

type GoSnapshot struct {
	Name     string
	DateTime string
}

GoSnapshot represents a GoContainer's snapshot

func NewGoSnapshot

func NewGoSnapshot(name string, dt string) *GoSnapshot

NewGoSnapshot loads a GoSnapshot

type ImageOutput

type ImageOutput struct {
	Public      bool            `json:"public,omitempty"`
	Props       ImageProperties `json:"properties,omitempty"`
	Filename    string          `json:"filename,omitempty"`
	Fingerprint string          `json:"fingerprint,omitempty"`
	Size        int             `json:"size,omitempty"`
	Type        string          `json:"type,omitempty"`
	Created     string          `json:"created_at,omitempty"`
}

ImageOutput

type ImageProperties

type ImageProperties struct {
	Architecture string `json:"architecture,omitempty"`
	OSType       string `json:"os,omitempty"`
	OSRelease    string `json:"os_release,omitempty"`
}

ImageProperties

type ImagesOutput

type ImagesOutput struct {
	Outputs []ImageOutput `json:"output,omitempty"`
}

ImagesOutput

func LoadImagesOutput

func LoadImagesOutput(jsonStr string) *ImagesOutput

LoadImagesOutput

func (*ImagesOutput) GetImages

func (imo *ImagesOutput) GetImages() []*GoImage

GetImages

type LXCConfig

type LXCConfig struct {
	ImageArchitecture string `json:"image.architecture,omitempty"`
	ImageDescription  string `json:"image.description,omitempty"`
	ImageOS           string `json:"image.os,omitempty"`
	ImageRelease      string `json:"image.release,omitempty"`
}

LXCConfig

type ListOutput

type ListOutput struct {
	Outputs []ContainerOutput `json:"output,omitempty"`
}

ListOutput

func LoadListOut

func LoadListOut(jsonStr string) (*ListOutput, error)

LoadNetworkOutput

func (*ListOutput) GetContainers

func (lo *ListOutput) GetContainers() []*GoContainer

GetContainers

type Network

type Network struct {
	PublicIP    string
	PrivateIP   string
	HWAddr      string
	Type        string
	HostName    string
	SSL         bool
	DNS         string
	Connections []*Connection
}

Network stores the network info for a GoContainer

func (*Network) AddConnection

func (n *Network) AddConnection(conn *Connection)

AddConnection to a Network

func (*Network) LoadEntry

func (n *Network) LoadEntry(nw *NetworkEntry) error

LoadEntry loads a lxc data into a pointer to NetworkEntry struct

type NetworkEntry

type NetworkEntry struct {
	Hostname string `json:"hostname,omitempty"`
	HWAddr   string `json:"hwaddr,omitempty"`
	Address  string `json:"address,omitempty"`
	Type     string `json:"type,omitempty"`
	Location string `json:"location,omitempty"`
}

NetworkEntry

type NetworkOutput

type NetworkOutput struct {
	NetworkEntries []NetworkEntry `json:"network_entries,omitempty"`
}

NetworkOutput

func LoadNetworkOutput

func LoadNetworkOutput(jsonStr string) (*NetworkOutput, error)

LoadNetworkOutput

func (*NetworkOutput) GetContainerEntry

func (nwo *NetworkOutput) GetContainerEntry(containerName string) *Network

GetContainerEntry

type SSHClient

type SSHClient struct {
	SSHConn *ssh.Client
}

SSHClient stores a pointer to a GoContainer ssh.Client

func (*SSHClient) Close

func (ssh *SSHClient) Close() error

Close wil close an open Container SSHClient

type Shell

type Shell struct {
	Name     string
	Type     string
	Commands []*CMD
	Status   int // 0 - Error, 1 - Initialized, 2 - Executed, 3 - Finished
}

Shell wraps around a slice of sh CMD

func NewShell

func NewShell(name string, sType string, commands []string) (*Shell, error)

NewShell initializes a new sh Shell

func (*Shell) Execute

func (sh *Shell) Execute() error

Execute a Shell

func (*Shell) OutputBytes

func (sh *Shell) OutputBytes() [][]byte

OutputBytes from Shell Execution

func (*Shell) Run

func (sh *Shell) Run() error

Run a Shell

Jump to

Keyboard shortcuts

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