<|start_filename|>client/stop.go<|end_filename|>
package client

import (
	"fmt"
	"strings"

	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdStop(args ...string) error {

	var opts struct {
		Container bool `short:"c" long:"container" default-mask:"-" description:"stop container"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)
	parser.Usage = "stop [OPTIONS] CONTAINER_ID|POD_ID\n\nStop running container or pod"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("\"stop\" requires a minimum of 1 argument, please provide POD ID.\n")
	}

	for i := range args {
		if opts.Container {
			err = cli.client.StopContainer(args[i])
			if err != nil {
				fmt.Fprintf(cli.err, "fail to stop container %s: %v", args[i], err)
			}
		} else {
			code, cause, err := cli.client.StopPod(args[i], "yes")
			if err != nil {
				fmt.Fprintf(cli.err, "fail to stop pod %s: %v", args[i], err)
				continue
			}
			if code != 0 {
				fmt.Fprintf(cli.err, "Error code is %d, cause is %s", code, cause)
				continue
			}
			fmt.Printf("Successfully shutdown the POD: %s!\n", args[i])
		}
	}

	return nil
}


<|start_filename|>mac_installer/resources/welcome.html<|end_filename|>
<html>

<head>

    <style type="text/css">
        body {
            font-family: Helvetica
        }
    </style>
</head>

<body>

    <h1>Hyper for Mac</h1>

    <p>Hyper is a Hypervisor-agnostic Docker Engine, it runs Docker&trade; images in hypervisor directly.</p>

    <p>Hyper for Mac runs on top of VirtualBox 5. Make sure you have Virtualbox 5 installed.</p>

</body>

</html>


<|start_filename|>vendor/github.com/opencontainers/image-spec/specs-go/version.go<|end_filename|>
// Copyright 2016 The Linux Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package specs

import "fmt"

const (
	// VersionMajor is for an API incompatible changes
	VersionMajor = 1
	// VersionMinor is for functionality in a backwards-compatible manner
	VersionMinor = 0
	// VersionPatch is for backwards-compatible bug fixes
	VersionPatch = 0

	// VersionDev indicates development branch. Releases will be empty string.
	VersionDev = "-rc5"
)

// Version is the specification version that the package types support.
var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)


<|start_filename|>storage/overlay/overlay_test.go<|end_filename|>
package overlay

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"strings"
	"syscall"
	"testing"
)

var (
	overlaySupport = false
	temp           = os.TempDir()
	tempDir        = path.Join(temp, "overlay-test")
	sharedTempDir  = path.Join(tempDir, "shared")
	containerId    = "123"
	lowerId        = "12345"
	lowerDir       = path.Join(tempDir, lowerId)
	containerDir   = path.Join(tempDir, containerId)
	workDir        = path.Join(containerDir, "work")
	upperDir       = path.Join(containerDir, "upper")
	loweridFile    = fmt.Sprintf("%s/lower-id", containerDir)
	testFile3      = fmt.Sprintf("%s/root/3", lowerDir)
	testFile2      = fmt.Sprintf("%s/root/2", lowerDir)
	testFile1      = fmt.Sprintf("%s/root/1", lowerDir)
)

func init() {
	overlaySupport = supportOverlay()
}

func InitDir() error {
	if err := os.MkdirAll(tempDir, 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(lowerDir, "root"), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(containerDir, 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(workDir, 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(upperDir, 0755); err != nil {
		return err
	}

	return nil
}

func Cleanup() error {
	if err := os.RemoveAll(tempDir); err != nil {
		return err
	}

	return nil
}

func InitFile() error {
	file1Data := ""
	file2Data := "1\n"
	file3Data := "1\n2\n"

	if err := ioutil.WriteFile(testFile1, []byte(file1Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(testFile2, []byte(file2Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(testFile3, []byte(file3Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(loweridFile, []byte(lowerId), 0755); err != nil {
		return err
	}

	return nil
}

func supportOverlay() bool {
	// We can try to modprobe overlay first before looking at
	// proc/filesystems for when overlay is supported
	if os.Getgid() == 0 {
		if err := exec.Command("/bin/sh", "-c", "modprobe", "overlay").Run(); err != nil {
			exec.Command("/bin/sh", "-c", "modprobe", "overlayfs").Run()
		}
	}

	f, err := os.Open("/proc/filesystems")
	if err != nil {
		return false
	}
	defer f.Close()

	s := bufio.NewScanner(f)
	for s.Scan() {
		if strings.Contains(s.Text(), "overlay") {
			return true
		}
	}
	return false
}

func TestTempDirCreate(t *testing.T) {
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}

}

func TestMountContainerToShareDir(t *testing.T) {
	if os.Getgid() != 0 {
		t.Errorf("This test case should be run in root group")
		return
	}
	if overlaySupport == false {
		return
	}
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(tempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("lower files create failed")
		} else {
			t.Fatalf("lower files create failed, %s", err.Error())
		}
	}
	if err := os.MkdirAll(sharedTempDir, 0755); err != nil {
		t.Fatalf("Shared dir create failed, %s", err.Error())
	}
	if _, err := os.Stat(sharedTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("shared dir create failed")
		} else {
			t.Fatalf("shared dir create failed, %s", err.Error())
		}
	}

	t.Log("Mount the parent read-only images and container")
	mountPoint, err := MountContainerToSharedDir(containerId, tempDir, sharedTempDir, "")
	if err != nil {
		t.Fatalf("Error during mounting paths: %s\n", err.Error())
	}
	t.Logf(mountPoint)

	// verify the mount result
	t.Log("Verify the mount result")
	if _, err := os.Stat(path.Join(mountPoint, "1")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (1) does not mount successfully!")
	}
	if _, err := os.Stat(path.Join(mountPoint, "2")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (2) does not mount successfully!")
	}
	if _, err := os.Stat(path.Join(mountPoint, "3")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (3) does not mount successfully!")
	}

	if err := os.MkdirAll(path.Join(mountPoint, "haha"), 0755); err != nil {
		t.Fatalf("Error on mkdir in mounted target dir!")
	}
	if _, err := os.Stat(path.Join(mountPoint, "haha")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The dir in mounted target dir does not exist!")
	}

	// Unmount the target dir and then remove it
	if err := syscall.Unmount(mountPoint, 0); err != nil {
		t.Fatalf("Unmount error: %s", err.Error())
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}
}

func TestAttachFiles(t *testing.T) {
	if os.Getgid() != 0 {
		t.Errorf("This test case should be run in root group")
		return
	}
	if overlaySupport == false {
		return
	}
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(tempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("layer files create failed")
		} else {
			t.Fatalf("layer files create failed, %s", err.Error())
		}
	}
	if err := os.MkdirAll(sharedTempDir, 0755); err != nil {
		t.Fatalf("Shared dir create failed, %s", err.Error())
	}
	if _, err := os.Stat(sharedTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("shared dir create failed")
		} else {
			t.Fatalf("shared dir create failed, %s", err.Error())
		}
	}

	t.Log("MountContainerToSharedDir do")
	mountPoint, err := MountContainerToSharedDir(containerId, tempDir, sharedTempDir, "")
	if err != nil {
		t.Fatalf("Error during mounting paths: %s\n", err.Error())
	}

	t.Log("AttachFiles do")
	err = AttachFiles(containerId, "/etc/os-release", "/", sharedTempDir, "0755", "0", "0")
	if err != nil {
		t.Fatalf(err.Error())
	}

	t.Log("Verify the AttachFiles function execution result")
	if _, err := os.Stat(mountPoint + "/os-release"); err != nil && os.IsNotExist(err) {
		t.Fatalf("The dir in mounted target dir does not exist!")
	}

	// Unmount the target dir and then remove it
	if err := syscall.Unmount(mountPoint, 0); err != nil {
		t.Fatalf("Unmount error: %s", err.Error())
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}
}


<|start_filename|>lib/sysinfo/sysinfo_darwin.go<|end_filename|>
// +build darwin

package sysinfo

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"strconv"
	"syscall"
)

func getMemInfo() (*MemInfo, error) {
	mem := &MemInfo{}
	stdbuf := new(bytes.Buffer)
	sysctl, err := exec.LookPath("sysctl")
	if err != nil {
		return nil, fmt.Errorf("Can not find sysctl command")
	}

	cmd := exec.Command(sysctl, "hw.memsize")
	cmd.Stdout = stdbuf
	if err := cmd.Run(); err != nil {
		return nil, err
	}
	reader := bufio.NewReader(stdbuf)
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		if i := bytes.Index(line, []byte("hw.memsize:")); i >= 0 {
			mem.MemTotal, err = strconv.ParseUint(string(line)[12:], 0, 64)
			if err != nil {
				continue
			}
		}
	}
	return mem, nil
}

func getCpuInfo() (*CpuInfo, error) {
	return nil, nil
}

func getOSInfo() (*OSInfo, error) {
	osinfo := &OSInfo{}
	var err error
	osinfo.Name, err = syscall.Sysctl("kern.ostype")
	if err != nil {
		return nil, err
	}
	osinfo.Version, err = syscall.Sysctl("kern.osrelease")
	if err != nil {
		return nil, err
	}
	osinfo.Id = osinfo.Name
	osinfo.IdLike = osinfo.Name
	osinfo.PrettyName = osinfo.Name + " Kernel Version " + osinfo.Version
	osinfo.VersionId = osinfo.Version
	osinfo.HomeURL = "www.apple.com"
	return osinfo, nil
}


<|start_filename|>lib/sysinfo/sysinfo.go<|end_filename|>
package sysinfo

type CpuInfo struct {
	Processor       uint64
	Vender_id       string
	CpuFamily       uint64
	Mode            uint64
	ModeName        string
	Stepping        uint64
	MicroCode       string
	CpuMhz          float64
	Cache           string
	PhyId           uint64
	Siblings        uint64
	CoreId          uint64
	CpuCores        uint64
	Apicid          uint64
	InitApicid      uint64
	Fpu             bool
	FpuException    bool
	CpuidLevel      uint64
	Wp              bool
	Flags           string
	Bogomips        float64
	ClFlushSize     uint64
	CacheAlianment  uint64
	AddressSizes    string
	PowerManagement string
}

type MemInfo struct {
	MemTotal          uint64
	MemFree           uint64
	MemAvailable      uint64
	Buffers           uint64
	Cached            uint64
	SwapCached        uint64
	Active            uint64
	Inactive          uint64
	AnonActive        uint64
	AnonInactive      uint64
	FileActive        uint64
	FileInactive      uint64
	Unevictable       uint64
	Mlocked           uint64
	SwapTotal         uint64
	SwapFree          uint64
	Dirty             uint64
	Writeback         uint64
	AnonPages         uint64
	Mapped            uint64
	Shmem             uint64
	Slab              uint64
	SReclaimable      uint64
	SUnreclaim        uint64
	KernelStack       uint64
	PageTables        uint64
	NFS_Unstable      uint64
	Bounce            uint64
	WritebackTmp      uint64
	CommitLimit       uint64
	Committed_AS      uint64
	VmallocTotal      uint64
	VmallocUsed       uint64
	VmallocChunk      uint64
	HardwareCorrupted uint64
	AnonHugePages     uint64
	HugePages_Total   uint64
	HugePages_Free    uint64
	HugePages_Rsvd    uint64
	HugePages_Surp    uint64
	Hugepagesize      uint64
	DirectMap4k       uint64
	DirectMap2M       uint64
	DirectMap1G       uint64
}

type OSInfo struct {
	Name       string
	Version    string
	Id         string
	IdLike     string
	PrettyName string
	VersionId  string
	HomeURL    string
	SupportURL string
	BugURL     string
}

func GetCpuInfo() (*CpuInfo, error) {
	return getCpuInfo()
}

func GetMemInfo() (*MemInfo, error) {
	return getMemInfo()
}

func GetOSInfo() (*OSInfo, error) {
	return getOSInfo()
}


<|start_filename|>server/router/local/local.go<|end_filename|>
package local

import (
	"github.com/hyperhq/hyperd/daemon"
	"github.com/hyperhq/hyperd/server/httputils"
	dkrouter "github.com/hyperhq/hyperd/server/router"
)

// router is a docker router that talks with the local docker daemon.
type router struct {
	daemon *daemon.Daemon
	routes []dkrouter.Route
}

// localRoute defines an individual API route to connect with the docker daemon.
// It implements router.Route.
type localRoute struct {
	method  string
	path    string
	handler httputils.APIFunc
}

// Handler returns the APIFunc to let the server wrap it in middlewares
func (l localRoute) Handler() httputils.APIFunc {
	return l.handler
}

// Method returns the http method that the route responds to.
func (l localRoute) Method() string {
	return l.method
}

// Path returns the subpath where the route responds to.
func (l localRoute) Path() string {
	return l.path
}

// NewRoute initializes a new local router for the reouter
func NewRoute(method, path string, handler httputils.APIFunc) dkrouter.Route {
	return localRoute{method, path, handler}
}

// NewGetRoute initializes a new route with the http method GET.
func NewGetRoute(path string, handler httputils.APIFunc) dkrouter.Route {
	return NewRoute("GET", path, handler)
}

// NewPostRoute initializes a new route with the http method POST.
func NewPostRoute(path string, handler httputils.APIFunc) dkrouter.Route {
	return NewRoute("POST", path, handler)
}

// NewPutRoute initializes a new route with the http method PUT.
func NewPutRoute(path string, handler httputils.APIFunc) dkrouter.Route {
	return NewRoute("PUT", path, handler)
}

// NewDeleteRoute initializes a new route with the http method DELETE.
func NewDeleteRoute(path string, handler httputils.APIFunc) dkrouter.Route {
	return NewRoute("DELETE", path, handler)
}

// NewOptionsRoute initializes a new route with the http method OPTIONS
func NewOptionsRoute(path string, handler httputils.APIFunc) dkrouter.Route {
	return NewRoute("OPTIONS", path, handler)
}

// NewHeadRoute initializes a new route with the http method HEAD.
func NewHeadRoute(path string, handler httputils.APIFunc) dkrouter.Route {
	return NewRoute("HEAD", path, handler)
}

// NewRouter initializes a local router with a new daemon.
func NewRouter(daemon *daemon.Daemon) dkrouter.Router {
	r := &router{
		daemon: daemon,
	}
	r.initRoutes()
	return r
}

// Routes returns the list of routes registered in the router.
func (r *router) Routes() []dkrouter.Route {
	return r.routes
}

// initRoutes initializes the routes in this router
func (r *router) initRoutes() {
	r.routes = []dkrouter.Route{
		// OPTIONS
		// GET
		// /images/json in docker
		NewGetRoute("/images/get", r.getImagesJSON),
		// /images/get in docker
		NewGetRoute("/images/save", r.getImagesSave),
		// POST
		NewPostRoute("/image/create", r.postImagesCreate),
		NewPostRoute("/image/load", r.postImagesLoad),
		NewPostRoute("/image/push", r.postImagesPush),
		// DELETE
		NewDeleteRoute("/image", r.deleteImages),
	}
}


<|start_filename|>examples/Dockerfile<|end_filename|>
From busybox

COPY *.pod /root/


<|start_filename|>client/images.go<|end_filename|>
package client

import (
	"fmt"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"

	"github.com/docker/go-units"

	"github.com/hyperhq/hyperd/utils"
	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdImages(args ...string) error {
	var opts struct {
		All   bool `short:"a" long:"all" description:"Show all images (by default filter out the intermediate image layers)"`
		Quiet bool `short:"q" long:"quiet" description:"Only show numeric IDs"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)

	parser.Usage = "images [OPTIONS] [REPOSITORY]\n\nList images"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}

	remoteInfo, err := cli.client.GetImages(opts.All, opts.Quiet)
	if err != nil {
		return err
	}

	var (
		imagesList = []string{}
	)
	imagesList = remoteInfo.GetList("imagesList")

	w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
	if opts.Quiet == false {
		fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
		for _, item := range imagesList {
			fields := utils.RsplitN(item, ":", 5)
			date, _ := strconv.ParseUint(fields[3], 0, 64)
			fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", fields[0], fields[1], fields[2][:12], time.Unix(int64(date), 0).Format("2006-01-02 15:04:05"), getImageSizeString(fields[4]))
		}
	} else {
		for _, item := range imagesList {
			fields := utils.RsplitN(item, ":", 5)
			fmt.Fprintf(w, "%s\n", fields[2][:12])
		}
	}
	w.Flush()

	return nil
}

func getImageSizeString(size string) string {
	s, err := strconv.Atoi(size)
	if err != nil {
		return ""
	}

	rtn := float64(s)
	return units.HumanSize(rtn)
}


<|start_filename|>image/image.go<|end_filename|>
package image

import (
	"io"
)

// Exporter provides interface for exporting and importing images
type Exporter interface {
	Load(io.ReadCloser, string, map[string]string, io.Writer) error
	// TODO: Load(net.Context, io.ReadCloser, <- chan StatusMessage) error
	Save([]string, string, map[string]string, io.Writer) error
}


<|start_filename|>client/api/rm.go<|end_filename|>
package api

import (
	"fmt"
	"net/url"

	"github.com/hyperhq/hyperd/engine"
	"github.com/hyperhq/runv/hypervisor/types"
)

func (cli *Client) RmPod(id string) error {
	v := url.Values{}
	v.Set("podId", id)
	body, _, err := readBody(cli.call("DELETE", "/pod?"+v.Encode(), nil, nil))
	if err != nil {
		return fmt.Errorf("Error to remove pod(%s), %s", id, err.Error())
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return fmt.Errorf("Error to remove pod(%s), %s", id, err.Error())
	}

	if _, err := out.Write(body); err != nil {
		return fmt.Errorf("Error to remove pod(%s), %s", id, err.Error())
	}
	out.Close()
	errCode := remoteInfo.GetInt("Code")
	if !(errCode == types.E_OK || errCode == types.E_VM_SHUTDOWN) {
		return fmt.Errorf("Error to remove pod(%s), %s", id, remoteInfo.Get("Cause"))
	}
	return nil
}

func (cli *Client) RemoveContainer(container string) error {
	v := url.Values{}
	v.Set("container", container)

	_, _, err := readBody(cli.call("POST", "/container/remove?"+v.Encode(), nil, nil))
	if err != nil {
		return err
	}
	return nil
}


<|start_filename|>client/api/login.go<|end_filename|>
package api

import (
	"encoding/json"

	"github.com/docker/engine-api/types"
)

func (cli *Client) Login(auth types.AuthConfig, response *types.AuthResponse) (remove bool, err error) {
	stream, statusCode, err := cli.call("POST", "/auth", auth, nil)
	if err != nil {
		return false, err
	}
	defer stream.Close()

	if statusCode == 401 {
		return true, err
	}

	if err := json.NewDecoder(stream).Decode(response); err != nil {
		return true, err
	}
	return false, nil
}


<|start_filename|>server/httputils/httputils.go<|end_filename|>
package httputils

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"golang.org/x/net/context"

	"github.com/docker/distribution/registry/api/errcode"
	"github.com/docker/docker/api"
	"github.com/docker/docker/pkg/version"
	"github.com/golang/glog"
)

// APIVersionKey is the client's requested API version.
const APIVersionKey = "api-version"

// APIFunc is an adapter to allow the use of ordinary functions as Docker API endpoints.
// Any function that has the appropriate signature can be register as a API endpoint (e.g. getVersion).
type APIFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error

// HijackConnection interrupts the http response writer to get the
// underlying connection and operate with it.
func HijackConnection(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
	conn, _, err := w.(http.Hijacker).Hijack()
	if err != nil {
		return nil, nil, err
	}
	// Flush the options to make sure the client sets the raw mode
	conn.Write([]byte{})
	return conn, conn, nil
}

// CloseStreams ensures that a list for http streams are properly closed.
func CloseStreams(streams ...interface{}) {
	for _, stream := range streams {
		if tcpc, ok := stream.(interface {
			CloseWrite() error
		}); ok {
			tcpc.CloseWrite()
		} else if closer, ok := stream.(io.Closer); ok {
			closer.Close()
		}
	}
}

// CheckForJSON makes sure that the request's Content-Type is application/json.
func CheckForJSON(r *http.Request) error {
	ct := r.Header.Get("Content-Type")

	// No Content-Type header is ok as long as there's no Body
	if ct == "" {
		if r.Body == nil || r.ContentLength == 0 {
			return nil
		}
	}

	// Otherwise it better be json
	if api.MatchesContentType(ct, "application/json") {
		return nil
	}
	return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
}

// ParseForm ensures the request form is parsed even with invalid content types.
// If we don't do this, POST method without Content-type (even with empty body) will fail.
func ParseForm(r *http.Request) error {
	if r == nil {
		return nil
	}
	if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
		return err
	}
	return nil
}

// ParseMultipartForm ensure the request form is parsed, even with invalid content types.
func ParseMultipartForm(r *http.Request) error {
	if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
		return err
	}
	return nil
}

// WriteError decodes a specific docker error and sends it in the response.
func WriteError(w http.ResponseWriter, err error) {
	if err == nil || w == nil {
		glog.Errorf("unexpected HTTP error handling, error %v, writer %v", err, w)
		return
	}

	statusCode := http.StatusInternalServerError
	errMsg := err.Error()

	// Based on the type of error we get we need to process things
	// slightly differently to extract the error message.
	// In the 'errcode.*' cases there are two different type of
	// error that could be returned. errocode.ErrorCode is the base
	// type of error object - it is just an 'int' that can then be
	// used as the look-up key to find the message. errorcode.Error
	// extends errorcode.Error by adding error-instance specific
	// data, like 'details' or variable strings to be inserted into
	// the message.
	//
	// Ideally, we should just be able to call err.Error() for all
	// cases but the errcode package doesn't support that yet.
	//
	// Additionally, in both errcode cases, there might be an http
	// status code associated with it, and if so use it.
	switch err.(type) {
	case errcode.ErrorCode:
		daError, _ := err.(errcode.ErrorCode)
		statusCode = daError.Descriptor().HTTPStatusCode
		errMsg = daError.Message()

	case errcode.Error:
		// For reference, if you're looking for a particular error
		// then you can do something like :
		//   import ( derr "github.com/docker/docker/errors" )
		//   if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }

		daError, _ := err.(errcode.Error)
		statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
		errMsg = daError.Message

	default:
		// This part of will be removed once we've
		// converted everything over to use the errcode package

		// FIXME: this is brittle and should not be necessary.
		// If we need to differentiate between different possible error types,
		// we should create appropriate error types with clearly defined meaning
		errStr := strings.ToLower(err.Error())
		for keyword, status := range map[string]int{
			"not found":             http.StatusNotFound,
			"no such":               http.StatusNotFound,
			"bad parameter":         http.StatusBadRequest,
			"conflict":              http.StatusConflict,
			"impossible":            http.StatusNotAcceptable,
			"wrong login/password":  http.StatusUnauthorized,
			"hasn't been activated": http.StatusForbidden,
		} {
			if strings.Contains(errStr, keyword) {
				statusCode = status
				break
			}
		}
	}

	if statusCode == 0 {
		statusCode = http.StatusInternalServerError
	}

	http.Error(w, errMsg, statusCode)
}

// WriteJSON writes the value v to the http response stream as json with standard json encoding.
func WriteJSON(w http.ResponseWriter, code int, v interface{}) error {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	return json.NewEncoder(w).Encode(v)
}

// VersionFromContext returns an API version from the context using APIVersionKey.
// It panics if the context value does not have version.Version type.
func VersionFromContext(ctx context.Context) (ver version.Version) {
	if ctx == nil {
		return
	}
	val := ctx.Value(APIVersionKey)
	if val == nil {
		return
	}
	return val.(version.Version)
}


<|start_filename|>storage/vbox/vbox.go<|end_filename|>
package vbox

import (
	"fmt"

	"github.com/hyperhq/hyperd/utils"
)

// For device mapper, we do not need to mount the container to sharedDir.
// All of we need to provide the block device name of container.
func MountContainerToSharedDir(containerId, sharedDir, devPrefix string) (string, error) {
	devFullName := fmt.Sprintf("%s/vbox/images/%s.vdi", utils.HYPER_ROOT, containerId)
	return devFullName, nil
}

func AttachFiles(containerId, devPrefix, fromFile, toDir, rootPath, perm, uid, gid string) error {
	return nil
}


<|start_filename|>client/api/kill.go<|end_filename|>
package api

import (
	"net/url"
	"strconv"
)

func (cli *Client) KillContainer(container string, sig int) error {
	v := url.Values{}
	v.Set("container", container)
	v.Set("signal", strconv.Itoa(sig))

	_, _, err := readBody(cli.call("POST", "/container/kill?"+v.Encode(), nil, nil))
	if err != nil {
		return err
	}
	return nil
}

func (cli *Client) KillPod(pod string, sig int) error {
	v := url.Values{}
	v.Set("podName", pod)
	v.Set("signal", strconv.Itoa(sig))

	_, _, err := readBody(cli.call("POST", "/pod/kill?"+v.Encode(), nil, nil))
	if err != nil {
		return err
	}
	return nil
}


<|start_filename|>server/router/build/build_routes.go<|end_filename|>
package build

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"

	"github.com/docker/docker/api/server/httputils"
	"github.com/docker/docker/builder"
	"github.com/docker/docker/builder/dockerfile"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/chrootarchive"
	"github.com/docker/docker/pkg/ioutils"
	"github.com/docker/docker/pkg/progress"
	"github.com/docker/docker/pkg/streamformatter"
	"github.com/docker/docker/reference"
	"github.com/docker/docker/utils"
	"github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/container"
	"github.com/docker/go-units"
	"github.com/golang/glog"
	"github.com/hyperhq/hyperd/daemon/daemonbuilder"
	"golang.org/x/net/context"
)

// sanitizeRepoAndTags parses the raw "t" parameter received from the client
// to a slice of repoAndTag.
// It also validates each repoName and tag.
func sanitizeRepoAndTags(names []string) ([]reference.Named, error) {
	var (
		repoAndTags []reference.Named
		// This map is used for deduplicating the "-t" parameter.
		uniqNames = make(map[string]struct{})
	)
	for _, repo := range names {
		if repo == "" {
			continue
		}

		ref, err := reference.ParseNamed(repo)
		if err != nil {
			return nil, err
		}

		ref = reference.WithDefaultTag(ref)

		if _, isCanonical := ref.(reference.Canonical); isCanonical {
			return nil, errors.New("build tag cannot contain a digest")
		}

		if _, isTagged := ref.(reference.NamedTagged); !isTagged {
			ref, err = reference.WithTag(ref, reference.DefaultTag)
		}

		nameWithTag := ref.String()

		if _, exists := uniqNames[nameWithTag]; !exists {
			uniqNames[nameWithTag] = struct{}{}
			repoAndTags = append(repoAndTags, ref)
		}
	}
	return repoAndTags, nil
}

func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBuildOptions, error) {
	//version := httputils.VersionFromContext(ctx)
	options := &types.ImageBuildOptions{}
	options.Remove = true
	//options.PullParent = true

	/*
		if httputils.BoolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
			options.Remove = true
		} else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
			options.Remove = true
		} else {
			options.Remove = httputils.BoolValue(r, "rm")
		}

		if httputils.BoolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
			options.PullParent = true
		}
	*/
	options.Dockerfile = r.FormValue("dockerfile")
	options.SuppressOutput = httputils.BoolValue(r, "q")
	options.NoCache = httputils.BoolValue(r, "nocache")
	options.ForceRemove = httputils.BoolValue(r, "forcerm")
	options.MemorySwap = httputils.Int64ValueOrZero(r, "memswap")
	options.Memory = httputils.Int64ValueOrZero(r, "memory")
	options.CPUShares = httputils.Int64ValueOrZero(r, "cpushares")
	options.CPUPeriod = httputils.Int64ValueOrZero(r, "cpuperiod")
	options.CPUQuota = httputils.Int64ValueOrZero(r, "cpuquota")
	options.CPUSetCPUs = r.FormValue("cpusetcpus")
	options.CPUSetMems = r.FormValue("cpusetmems")
	options.CgroupParent = r.FormValue("cgroupparent")

	if r.Form.Get("shmsize") != "" {
		shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
		if err != nil {
			return nil, err
		}
		options.ShmSize = shmSize
	}

	if i := container.IsolationLevel(r.FormValue("isolation")); i != "" {
		if !container.IsolationLevel.IsValid(i) {
			return nil, fmt.Errorf("Unsupported isolation: %q", i)
		}
		options.IsolationLevel = i
	}

	var buildUlimits = []*units.Ulimit{}
	ulimitsJSON := r.FormValue("ulimits")
	if ulimitsJSON != "" {
		if err := json.NewDecoder(strings.NewReader(ulimitsJSON)).Decode(&buildUlimits); err != nil {
			return nil, err
		}
		options.Ulimits = buildUlimits
	}

	var buildArgs = map[string]string{}
	buildArgsJSON := r.FormValue("buildargs")
	if buildArgsJSON != "" {
		if err := json.NewDecoder(strings.NewReader(buildArgsJSON)).Decode(&buildArgs); err != nil {
			return nil, err
		}
		options.BuildArgs = buildArgs
	}
	return options, nil
}

func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	var (
		authConfigs        = map[string]types.AuthConfig{}
		authConfigsEncoded = r.Header.Get("X-Registry-Config")
		notVerboseBuffer   = bytes.NewBuffer(nil)
	)

	if authConfigsEncoded != "" {
		authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
		if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
			// for a pull it is not an error if no auth was given
			// to increase compatibility with the existing api it is defaulting
			// to be empty.
		}
	}

	w.Header().Set("Content-Type", "application/json")

	output := ioutils.NewWriteFlusher(w)
	defer output.Close()
	sf := streamformatter.NewJSONStreamFormatter()
	errf := func(err error) error {
		if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
			output.Write(notVerboseBuffer.Bytes())
		}
		// Do not write the error in the http output if it's still empty.
		// This prevents from writing a 200(OK) when there is an internal error.
		if !output.Flushed() {
			return err
		}
		_, err = w.Write(sf.FormatError(errors.New(utils.GetErrorMessage(err))))
		if err != nil {
			glog.Warningf("could not write error response: %v", err)
		}
		return nil
	}

	buildOptions, err := newImageBuildOptions(ctx, r)
	if err != nil {
		return errf(err)
	}

	repoAndTags, err := sanitizeRepoAndTags(r.Form["name"])
	if err != nil {
		return errf(err)
	}

	remoteURL := r.FormValue("remote")

	// Currently, only used if context is from a remote url.
	// Look at code in DetectContextFromRemoteURL for more information.
	createProgressReader := func(in io.ReadCloser) io.ReadCloser {
		progressOutput := sf.NewProgressOutput(output, true)
		if buildOptions.SuppressOutput {
			progressOutput = sf.NewProgressOutput(notVerboseBuffer, true)
		}
		return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL)
	}

	var (
		context        builder.ModifiableContext
		dockerfileName string
	)
	context, dockerfileName, err = daemonbuilder.DetectContextFromRemoteURL(r.Body, remoteURL, createProgressReader)
	if err != nil {
		return errf(err)
	}
	defer func() {
		if err := context.Close(); err != nil {
			glog.Infof("[BUILDER] failed to remove temporary context: %v", err)
		}
	}()
	if len(dockerfileName) > 0 {
		buildOptions.Dockerfile = dockerfileName
	}

	uidMaps, gidMaps := br.backend.GetUIDGIDMaps()
	defaultArchiver := &archive.Archiver{
		Untar:   chrootarchive.Untar,
		UIDMaps: uidMaps,
		GIDMaps: gidMaps,
	}

	docker := &daemonbuilder.Docker{
		Daemon:      br.backend,
		OutOld:      output,
		AuthConfigs: authConfigs,
		Archiver:    defaultArchiver,
	}
	if buildOptions.SuppressOutput {
		docker.OutOld = notVerboseBuffer
	}

	docker.InitHyper()
	defer docker.Cleanup()

	b, err := dockerfile.NewBuilder(
		buildOptions, // result of newBuildConfig
		docker,
		builder.DockerIgnoreContext{ModifiableContext: context},
		nil)
	if err != nil {
		return errf(err)
	}
	b.Stdout = &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf}
	b.Stderr = &streamformatter.StderrFormatter{Writer: output, StreamFormatter: sf}
	if buildOptions.SuppressOutput {
		b.Stdout = &streamformatter.StdoutFormatter{Writer: notVerboseBuffer, StreamFormatter: sf}
		b.Stderr = &streamformatter.StderrFormatter{Writer: notVerboseBuffer, StreamFormatter: sf}
	}

	if closeNotifier, ok := w.(http.CloseNotifier); ok {
		finished := make(chan struct{})
		defer close(finished)
		clientGone := closeNotifier.CloseNotify()
		go func() {
			select {
			case <-finished:
			case <-clientGone:
				glog.Infof("Client disconnected, cancelling job: build")
				b.Cancel()
			}
		}()
	}

	imgID, err := b.Build()
	if err != nil {
		return errf(err)
	}

	for _, rt := range repoAndTags {
		if err := br.backend.TagImage(rt, imgID); err != nil {
			return errf(err)
		}
	}

	// Everything worked so if -q was provided the output from the daemon
	// should be just the image ID and we'll print that to stdout.
	if buildOptions.SuppressOutput {
		stdout := &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf}
		fmt.Fprintf(stdout, "%s\n", string(imgID))
	}

	return nil
}


<|start_filename|>client/info.go<|end_filename|>
package client

import (
	"fmt"
	"strings"

	"github.com/docker/go-units"

	gflag "github.com/jessevdk/go-flags"
)

// we need this *info* function to get the whole status from the hyper daemon
func (cli *HyperClient) HyperCmdInfo(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "info\n\nDisplay system-wide information"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}

	remoteInfo, err := cli.client.Info()
	if err != nil {
		return err
	}

	fmt.Fprintf(cli.out, "Images: %d\n", remoteInfo.GetInt("Images"))
	if remoteInfo.Exists("Containers") {
		fmt.Fprintf(cli.out, "Containers: %d\n", remoteInfo.GetInt("Containers"))
	}
	fmt.Fprintf(cli.out, "PODs: %d\n", remoteInfo.GetInt("Pods"))
	fmt.Fprintf(cli.out, "Storage Driver: %s\n", remoteInfo.Get("Driver"))
	var status [][]string
	err = remoteInfo.GetJson("DriverStatus", &status)
	if err == nil {
		for _, pair := range status {
			fmt.Fprintf(cli.out, "  %s: %s\n", pair[0], pair[1])
		}
	}

	fmt.Fprintf(cli.out, "Hyper Root Dir: %s\n", remoteInfo.Get("DockerRootDir"))
	fmt.Fprintf(cli.out, "Index Server Address: %s\n", remoteInfo.Get("IndexServerAddress"))
	fmt.Fprintf(cli.out, "Execution Driver: %s\n", remoteInfo.Get("ExecutionDriver"))

	memTotal := getMemSizeString(remoteInfo.GetInt("MemTotal"))
	fmt.Fprintf(cli.out, "Total Memory: %s\n", memTotal)
	fmt.Fprintf(cli.out, "Operating System: %s\n", remoteInfo.Get("Operating System"))

	return nil
}

func getMemSizeString(s int) string {
	rtn := float64(s)
	return units.HumanSize(rtn)
}


<|start_filename|>client/api/images.go<|end_filename|>
package api

import (
	"fmt"
	"net/url"

	"github.com/hyperhq/hyperd/engine"
)

func (cli *Client) GetImages(all, quiet bool) (*engine.Env, error) {

	v := url.Values{}
	v.Set("all", "no")
	v.Set("quiet", "no")
	if all == true {
		v.Set("all", "yes")
	}
	if quiet == true {
		v.Set("quiet", "yes")
	}
	body, _, err := readBody(cli.call("GET", "/images/get?"+v.Encode(), nil, nil))
	if err != nil {
		return nil, err
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return nil, err
	}

	if _, err := out.Write(body); err != nil {
		fmt.Printf("Error reading remote info: %s", err)
		return nil, err
	}
	out.Close()

	return remoteInfo, nil
}


<|start_filename|>server/router/system/backend.go<|end_filename|>
package system

import (
	"github.com/docker/engine-api/types"
	"github.com/hyperhq/hyperd/engine"
	apitypes "github.com/hyperhq/hyperd/types"
)

// Backend is the methods that need to be implemented to provide
// system specific functionality.
type Backend interface {
	CmdSystemInfo() (*apitypes.InfoResponse, error)
	CmdSystemVersion() *engine.Env
	CmdAuthenticateToRegistry(authConfig *types.AuthConfig) (string, error)
}


<|start_filename|>storage/files.go<|end_filename|>
package storage

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
	"syscall"
)

func FsInjectFile(src io.Reader, containerId, target, baseDir string, perm, uid, gid int) error {
	if containerId == "" {
		return fmt.Errorf("Please make sure the arguments are not NULL!\n")
	}

	targetFile := path.Join(baseDir, containerId, "rootfs", target)

	return WriteFile(src, targetFile, perm, uid, gid)

}

func WriteFile(src io.Reader, targetFile string, permFile, uid, gid int) error {

	targetDir := filepath.Dir(targetFile)
	permDir := permFile | 0111

	if stat, err := os.Stat(targetDir); err != nil {
		if os.IsNotExist(err) {
			err = os.MkdirAll(targetDir, os.FileMode(permDir))
		}
		if err != nil {
			return err
		}
	} else if !stat.IsDir() {
		return errors.New("File target is not a dir: " + targetDir)
	}

	f, err := os.OpenFile(targetFile, os.O_RDWR|os.O_CREATE, os.FileMode(permFile))
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = io.Copy(f, src)
	if err != nil {
		return err
	}

	if err = syscall.Chown(targetFile, uid, gid); err != nil {
		return err
	}

	return nil

}


<|start_filename|>client/build.go<|end_filename|>
package client

import (
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
	"strings"

	rand "github.com/hyperhq/hyperd/utils"

	"github.com/docker/docker/api"
	"github.com/docker/docker/builder/dockerignore"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/fileutils"
	"github.com/docker/docker/pkg/progress"
	"github.com/docker/docker/pkg/streamformatter"
	"github.com/docker/docker/pkg/symlink"
	"github.com/docker/docker/reference"
	gflag "github.com/jessevdk/go-flags"
)

// hyperctl build [OPTIONS] PATH
func (cli *HyperClient) HyperCmdBuild(args ...string) error {
	var opts struct {
		ImageName      string `long:"tag" short:"t" default:"" value-name:"\"\"" default-mask:"-" description:"Repository name (and optionally a tag) to be applied to the resulting image in case of success"`
		DockerfileName string `long:"file" short:"f" default:"" value-name:"\"\"" default-mask:"-" description:"Customized docker file"`
	}

	var parser = gflag.NewParser(&opts, gflag.Default)
	parser.Usage = "build [OPTIONS] PATH\n\nBuild a new image from the source code at PATH"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}

	if len(args) == 0 {
		return fmt.Errorf("%s: \"build\" requires a minimum of 1 argument, See 'hyperctl build --help'.", os.Args[0])
	}
	var (
		filename = ""
		context  archive.Archive
		name     = ""
	)
	root := args[0]
	if _, err := os.Stat(root); err != nil {
		return err
	}

	absRoot, err := filepath.Abs(root)
	if err != nil {
		return err
	}

	filename = opts.DockerfileName // path to Dockerfile

	if opts.DockerfileName == "" {
		// No -f/--file was specified so use the default
		opts.DockerfileName = api.DefaultDockerfileName
		filename = filepath.Join(absRoot, opts.DockerfileName)

		// Just to be nice ;-) look for 'dockerfile' too but only
		// use it if we found it, otherwise ignore this check
		if _, err = os.Lstat(filename); os.IsNotExist(err) {
			tmpFN := path.Join(absRoot, strings.ToLower(opts.DockerfileName))
			if _, err = os.Lstat(tmpFN); err == nil {
				opts.DockerfileName = strings.ToLower(opts.DockerfileName)
				filename = tmpFN
			}
		}
	}

	origDockerfile := opts.DockerfileName // used for error msg
	if filename, err = filepath.Abs(filename); err != nil {
		return err
	}

	// Verify that 'filename' is within the build context
	filename, err = symlink.FollowSymlinkInScope(filename, absRoot)
	if err != nil {
		return fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", origDockerfile, root)
	}

	// Now reset the dockerfileName to be relative to the build context
	opts.DockerfileName, err = filepath.Rel(absRoot, filename)
	if err != nil {
		return err
	}
	// And canonicalize dockerfile name to a platform-independent one
	opts.DockerfileName, err = archive.CanonicalTarNameForPath(opts.DockerfileName)
	if err != nil {
		return fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", opts.DockerfileName, err)
	}

	if _, err = os.Lstat(filename); os.IsNotExist(err) {
		return fmt.Errorf("Cannot locate Dockerfile: %s", origDockerfile)
	}
	var includes = []string{"."}

	f, err := os.Open(filepath.Join(root, ".dockerignore"))
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	defer f.Close()

	var excludes []string
	if err == nil {
		excludes, err = dockerignore.ReadAll(f)
		if err != nil {
			return err
		}
	}

	if err := ValidateContextDirectory(root, excludes); err != nil {
		return fmt.Errorf("Error checking context: '%s'.", err)
	}

	// If .dockerignore mentions .dockerignore or the Dockerfile
	// then make sure we send both files over to the daemon
	// because Dockerfile is, obviously, needed no matter what, and
	// .dockerignore is needed to know if either one needs to be
	// removed.  The deamon will remove them for us, if needed, after it
	// parses the Dockerfile.
	keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
	keepThem2, _ := fileutils.Matches(opts.DockerfileName, excludes)
	if keepThem1 || keepThem2 {
		includes = append(includes, ".dockerignore", opts.DockerfileName)
	}

	if err := ValidateContextDirectory(root, excludes); err != nil {
		return fmt.Errorf("Error checking context: '%s'.", err)
	}
	options := &archive.TarOptions{
		Compression:     archive.Uncompressed,
		ExcludePatterns: excludes,
		IncludeFiles:    includes,
	}
	context, err = archive.TarWithOptions(root, options)
	if err != nil {
		return err
	}
	var body io.Reader
	// Setup an upload progress bar
	// FIXME: ProgressReader shouldn't be this annoying to use
	if context != nil {
		var progBuff io.Writer = cli.out

		progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(progBuff, true)

		body = progress.NewProgressReader(context, progressOutput, 0, "", "Sending build context to Docker daemon")
	}

	if opts.ImageName == "" {
		// set a image name
		name = rand.RandStr(10, "alphanum")
	} else {
		name = opts.ImageName
		if _, err := reference.ParseNamed(name); err != nil {
			return err
		}
	}
	output, ctype, err := cli.client.Build(name, context != nil, body)
	if err != nil {
		return err
	}
	return cli.readStreamOutput(output, ctype, false, cli.out, cli.err)
}

// validateContextDirectory checks if all the contents of the directory
// can be read and returns an error if some files can't be read
// symlinks which point to non-existing files don't trigger an error
func ValidateContextDirectory(srcPath string, excludes []string) error {
	contextRoot := filepath.Join(srcPath, ".")

	return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
		// skip this directory/file if it's not in the path, it won't get added to the context
		if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
			return err
		} else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
			return err
		} else if skip {
			if f.IsDir() {
				return filepath.SkipDir
			}
			return nil
		}

		if err != nil {
			if os.IsPermission(err) {
				return fmt.Errorf("can't stat '%s'", filePath)
			}
			if os.IsNotExist(err) {
				return nil
			}
			return err
		}

		// skip checking if symlinks point to non-existing files, such symlinks can be useful
		// also skip named pipes, because they hanging on open
		if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
			return nil
		}

		if !f.IsDir() {
			currentFile, err := os.Open(filePath)
			if err != nil && os.IsPermission(err) {
				return fmt.Errorf("no permission to read from '%s'", filePath)
			}
			currentFile.Close()
		}
		return nil
	})
}


<|start_filename|>daemon/pod/servicediscovery.go<|end_filename|>
package pod

import (
	"fmt"
	"strings"

	"github.com/hyperhq/hypercontainer-utils/hlog"
	apitypes "github.com/hyperhq/hyperd/types"
)

const (
	// set default mode to masquerading
	// Others are `i` tunneling and `g` gatewaying
	DEFAULT_MODE   string = "m"
	DEFAULT_WEITHT int    = 1
	// Others are wrr|lc|wlc|lblc|lblcr|dh|sh|sed|nq
	DEFAULT_SCHEDULER = "rr"
)

type Services struct {
	p *XPod

	spec []*apitypes.UserService
}

func newServices(p *XPod, spec []*apitypes.UserService) *Services {
	return &Services{
		p:    p,
		spec: spec,
	}
}

func (s *Services) LogPrefix() string {
	return fmt.Sprintf("%s[Serv] ", s.p.LogPrefix())
}

func (s *Services) Log(level hlog.LogLevel, args ...interface{}) {
	hlog.HLog(level, s, 1, args...)
}

type serviceKey struct {
	IP       string
	Port     int32
	Protocol string
}

func generateIPVSCmd(service *apitypes.UserService, op string) ([]byte, error) {
	if service == nil {
		return nil, nil
	}

	var (
		cmd       string
		protoFlag string
	)
	cmds := []byte{}
	DEFAULT_POSTFIX := fmt.Sprintf("-%s -w %d", DEFAULT_MODE, DEFAULT_WEITHT)

	if strings.ToLower(service.Protocol) == "tcp" {
		protoFlag = "-t"
	} else if strings.ToLower(service.Protocol) == "udp" {
		protoFlag = "-u"
	} else {
		return nil, fmt.Errorf("unsupported service protocol type: %s", service.Protocol)
	}
	sConf := fmt.Sprintf("%s %s:%d", protoFlag, service.ServiceIP, service.ServicePort)
	switch op {
	case "add":
		if service.ServiceIP == "" || service.ServicePort == 0 {
			return nil, fmt.Errorf("invlide service format, missing service IP or Port")
		}
		cmd = fmt.Sprintf("-A %s -s %s\n", sConf, DEFAULT_SCHEDULER)
		cmds = append(cmds, cmd...)
		for _, b := range service.Hosts {
			cmd = fmt.Sprintf("-a %s -r %s:%d %s\n", sConf, b.HostIP, b.HostPort, DEFAULT_POSTFIX)
			cmds = append(cmds, cmd...)
		}
	case "del":
		cmd = fmt.Sprintf("-D %s\n", sConf)
		cmds = append(cmds, cmd...)
	default:
		return nil, fmt.Errorf("undefined operation type: %s", op)
	}
	return cmds, nil
}

// add will only add services in list that don't exist, else failed
func (s *Services) add(newServs []*apitypes.UserService) error {
	var err error
	// check if adding service conflict with existing ones
	exist := make(map[serviceKey]bool, s.size())
	for _, srv := range s.spec {
		exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
	}
	for _, srv := range newServs {
		if exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] {
			err = fmt.Errorf("service %v conflicts with existing ones", newServs)
			s.Log(ERROR, err)
			return err
		}
		exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
	}

	// if pod is running, convert service to patch and send to vm
	if s.p.IsRunning() {
		if err = s.commit(newServs, "add"); err != nil {
			return err
		}
	}
	s.spec = append(s.spec, newServs...)

	return nil
}

func (s *Services) del(srvs []*apitypes.UserService) error {
	var err error
	tbd := make(map[serviceKey]bool, len(srvs))
	for _, srv := range srvs {
		tbd[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
	}
	target := make([]*apitypes.UserService, 0, len(srvs))
	remain := make([]*apitypes.UserService, 0, s.size())
	for _, srv := range s.spec {
		if tbd[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] {
			s.Log(TRACE, "remove serivce %#v", srv)
			target = append(target, srv)
		} else {
			remain = append(remain, srv)
		}
	}

	if s.p.IsRunning() {
		if err = s.commit(target, "del"); err != nil {
			return err
		}
	}
	s.spec = remain

	return nil
}

// update removes services in list that already exist, and add with new ones
// or just add new ones if they are not exist already
func (s *Services) update(srvs []*apitypes.UserService) error {
	var err error
	// check if update service list conflicts
	tbd := make(map[serviceKey]bool, len(srvs))
	for _, srv := range srvs {
		key := serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}
		if tbd[key] {
			err = fmt.Errorf("given service list conflict: %v", srv)
			s.Log(ERROR, err)
			return err
		}
		tbd[key] = true
	}

	if s.p.IsRunning() {
		if err = s.commit(srvs, "update"); err != nil {
			return err
		}
	}
	s.spec = srvs

	return nil
}

func (s *Services) apply() error {
	return s.commit(s.spec, "add")
}

func (s *Services) commit(srvs []*apitypes.UserService, operation string) error {
	var (
		err   error
		patch []byte
	)
	if operation == "update" {
		// clear all rules first
		patch = append(patch, []byte("-C\n")...)
		operation = "add"
	}
	// generate patch
	for _, srv := range srvs {
		cmd, err := generateIPVSCmd(srv, operation)
		if err != nil {
			s.Log(ERROR, "faild to generate IPVS command: %v", err)
			return err
		}
		patch = append(patch, cmd...)
	}
	// send to vm
	if err = s.commitToVm(patch); err != nil {
		s.Log(ERROR, "faild to apply IPVS service patch: %v", err)
		return err
	}

	return nil
}

func (s *Services) commitToVm(patch []byte) error {
	s.Log(TRACE, "commit IPVS service patch: \n%s", string(patch))

	saveData, err := s.getFromVm()
	if err != nil {
		return err
	}

	clear := func() error {
		cmd := []string{"ipvsadm", "-C"}
		_, stderr, err := s.p.sandbox.HyperstartExecSync(cmd, nil)
		if err != nil {
			s.Log(ERROR, "clear ipvs rules failed: %v, %s", err, stderr)
			return err
		}

		return nil
	}

	apply := func(rules []byte) error {
		cmd := []string{"ipvsadm", "-R"}
		_, stderr, err := s.p.sandbox.HyperstartExecSync(cmd, rules)
		if err != nil {
			s.Log(ERROR, "apply ipvs rules failed: %v, %s", err, stderr)
			return err
		}

		return nil
	}

	if err = apply(patch); err != nil {
		// restore original ipvs services
		err1 := clear()
		if err1 != nil {
			s.Log(ERROR, "restore original ipvs services failed in clear stage: %v", err1)
			return err
		}
		err1 = apply(saveData)
		if err1 != nil {
			s.Log(ERROR, "restore original ipvs services failed in apply stage: %v", err1)
		}
		return err
	}

	return nil
}

func (s *Services) getFromVm() ([]byte, error) {
	cmd := []string{"ipvsadm", "-Ln"}
	stdout, stderr, err := s.p.sandbox.HyperstartExecSync(cmd, nil)
	if err != nil {
		s.Log(ERROR, "get ipvs service from vm failed: %v, %s", err, stderr)
		return nil, err
	}

	return stdout, nil
}

func (s *Services) size() int {
	if s.spec == nil {
		return 0
	}
	return len(s.spec)
}

func (s *Services) get() []*apitypes.UserService {
	return s.spec
}

func (p *XPod) GetServices() ([]*apitypes.UserService, error) {
	p.resourceLock.Lock()
	defer p.resourceLock.Unlock()

	return p.services.get(), nil
}

func (p *XPod) UpdateService(srvs []*apitypes.UserService) error {
	p.resourceLock.Lock()
	defer p.resourceLock.Unlock()

	if err := p.services.update(srvs); err != nil {
		p.Log(ERROR, "failed to update services: %v", err)
		return err
	}

	return p.savePodMeta()
}

func (p *XPod) AddService(srvs []*apitypes.UserService) error {
	p.resourceLock.Lock()
	defer p.resourceLock.Unlock()

	if err := p.services.add(srvs); err != nil {
		p.Log(ERROR, "failed to add services: %v", err)
		return err
	}

	return p.savePodMeta()
}

func (p *XPod) DeleteService(srvs []*apitypes.UserService) error {
	p.resourceLock.Lock()
	defer p.resourceLock.Unlock()

	if err := p.services.del(srvs); err != nil {
		p.Log(ERROR, "failed to delete service: %v", err)
		return err
	}

	return p.savePodMeta()
}


<|start_filename|>client/api/rmi.go<|end_filename|>
package api

import (
	"fmt"
	"net/url"
	"strconv"

	"github.com/hyperhq/hyperd/engine"
)

func (cli *Client) RemoveImage(image string, noprune, force bool) (*engine.Env, error) {
	v := url.Values{}
	v.Set("imageId", image)
	v.Set("noprune", strconv.FormatBool(noprune))
	v.Set("force", strconv.FormatBool(force))
	body, _, err := readBody(cli.call("DELETE", "/image?"+v.Encode(), nil, nil))
	if err != nil {
		return nil, fmt.Errorf("Error remove the image(%s): %s", image, err.Error())
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return nil, fmt.Errorf("Error remove the image(%s): %s", image, err.Error())
	}

	if _, err := out.Write(body); err != nil {
		return nil, fmt.Errorf("Error remove the image(%s): %s", image, err.Error())
	}
	out.Close()

	return remoteInfo, nil
}


<|start_filename|>daemon/pause.go<|end_filename|>
package daemon

import (
	"fmt"

	"github.com/golang/glog"
)

func (daemon Daemon) PausePod(podId string) error {
	p, ok := daemon.PodList.Get(podId)
	if !ok {
		return fmt.Errorf("Can not get Pod info with pod ID(%s)", podId)
	}

	return p.Pause()
}

func (daemon Daemon) PauseContainer(container string) error {
	glog.V(1).Infof("Get container id is %s", container)
	p, _, ok := daemon.PodList.GetByContainerIdOrName(container)
	if !ok {
		err := fmt.Errorf("cannot get container %s to pause", container)
		glog.Error(err)
		return err
	}

	return p.Pause()
}

func (daemon *Daemon) UnpausePod(podId string) error {
	p, ok := daemon.PodList.Get(podId)
	if !ok {
		return fmt.Errorf("Can not get Pod info with pod ID(%s)", podId)
	}

	return p.UnPause()
}

func (daemon *Daemon) UnpauseContainer(container string) error {
	glog.V(1).Infof("Get container id is %s", container)
	p, _, ok := daemon.PodList.GetByContainerIdOrName(container)
	if !ok {
		err := fmt.Errorf("cannot get container %s to pause", container)
		glog.Error(err)
		return err
	}

	return p.UnPause()
}


<|start_filename|>daemon/rm.go<|end_filename|>
package daemon

import (
	"fmt"

	"github.com/golang/glog"
)

const (
	E_NOT_FOUND       = -2
	E_UNDER_OPERATION = -1
	E_OK              = 0
)

func (daemon *Daemon) RemovePod(podId string) (int, string, error) {
	var (
		code  = E_OK
		cause = ""
		err   error
	)

	p, ok := daemon.PodList.Get(podId)
	if !ok {
		return E_NOT_FOUND, "", fmt.Errorf("Can not find that Pod(%s)", podId)
	}

	daemon.PodList.Release(podId)

	if p.IsAlive() {
		glog.V(1).Infof("remove pod %s, stop it firstly", podId)
		p.Stop(5)
	}

	p.Remove(true)

	return code, cause, err
}

func (daemon *Daemon) RemoveContainer(nameOrId string) error {
	p, id, ok := daemon.PodList.GetByContainerIdOrName(nameOrId)
	if !ok {
		err := fmt.Errorf("cannot find container %s", nameOrId)
		glog.Error(err)
		return err
	}

	return p.RemoveContainer(id)
}


<|start_filename|>client/api/errors.go<|end_filename|>
package api

import "errors"

var (
	ErrConnectionRefused = errors.New("Cannot connect to the Hyper daemon. Is 'hyperd' running on this host?")
)


<|start_filename|>client/api/load.go<|end_filename|>
package api

import (
	"encoding/json"
	"io"
	"net/url"
)

func (cli *Client) Load(body io.Reader, name string, refs map[string]string) (io.ReadCloser, string, error) {

	headers := map[string][]string{"Content-Type": {"application/x-tar"}}
	refsJSON, err := json.Marshal(refs)
	if err != nil {
		return nil, "", err
	}

	v := url.Values{
		"name": []string{name},
		"refs": []string{string(refsJSON)},
	}

	out, contenttype, err := cli.stream("POST", "/image/load?"+v.Encode(), body, headers)
	if err != nil {
		return nil, "", err
	}
	return out, contenttype, nil
}


<|start_filename|>daemon/daemonbuilder/builder.go<|end_filename|>
package daemonbuilder

import (
	"fmt"
	"io"
	"io/ioutil"

	"github.com/docker/docker/api"
	"github.com/docker/docker/builder"
	"github.com/docker/docker/image"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/httputils"
	"github.com/docker/docker/pkg/ioutils"
	"github.com/docker/docker/pkg/urlutil"
	"github.com/docker/docker/reference"
	"github.com/docker/docker/registry"
	"github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/container"
	"github.com/hyperhq/hyperd/daemon"
)

// Docker implements builder.Backend for the docker Daemon object.
type Docker struct {
	*daemon.Daemon
	OutOld      io.Writer
	AuthConfigs map[string]types.AuthConfig
	Archiver    *archive.Archiver
	hyper       *Hyper
}

type Hyper struct {
	CopyPods  map[string]string
	BasicPods map[string]string
	Ready     chan bool
}

// ensure Docker implements builder.Backend
var _ builder.Backend = Docker{}

func (d *Docker) InitHyper() {
	d.hyper = &Hyper{
		make(map[string]string),
		make(map[string]string),
		make(chan bool, 1),
	}
}

// Pull tells Docker to pull image referenced by `name`.
func (d Docker) Pull(name string) (builder.Image, error) {
	ref, err := reference.ParseNamed(name)
	if err != nil {
		return nil, err
	}
	ref = reference.WithDefaultTag(ref)

	pullRegistryAuth := &types.AuthConfig{}
	if len(d.AuthConfigs) > 0 {
		// The request came with a full auth config file, we prefer to use that
		repoInfo, err := d.Daemon.RegistryService.ResolveRepository(ref)
		if err != nil {
			return nil, err
		}

		resolvedConfig := registry.ResolveAuthConfig(
			d.AuthConfigs,
			repoInfo.Index,
		)
		pullRegistryAuth = &resolvedConfig
	}

	if err := d.Daemon.PullImage(ref, nil, pullRegistryAuth, ioutils.NopWriteCloser(d.OutOld)); err != nil {
		return nil, err
	}
	return d.GetImage(name)
}

// GetImage looks up a Docker image referenced by `name`.
func (d Docker) GetImage(name string) (builder.Image, error) {
	img, err := d.Daemon.GetImage(name)
	if err != nil {
		return nil, err
	}
	return imgWrap{img}, nil
}

// ContainerUpdateCmd updates Path and Args for the container with ID cID.
func (d Docker) ContainerUpdateCmd(cID string, cmd []string) error {
	c, err := d.Daemon.GetContainer(cID)
	if err != nil {
		return err
	}
	c.Path = cmd[0]
	c.Args = cmd[1:]
	return nil
}

// GetCachedImage returns a reference to a cached image whose parent equals `parent`
// and runconfig equals `cfg`. A cache miss is expected to return an empty ID and a nil error.
func (d Docker) GetCachedImage(imgID string, cfg *container.Config) (string, error) {
	cache, err := d.Daemon.ImageGetCached(image.ID(imgID), cfg)
	if cache == nil || err != nil {
		return "", err
	}
	return cache.ID().String(), nil
}

// Following is specific to builder contexts

// DetectContextFromRemoteURL returns a context and in certain cases the name of the dockerfile to be used
// irrespective of user input.
// progressReader is only used if remoteURL is actually a URL (not empty, and not a Git endpoint).
func DetectContextFromRemoteURL(r io.ReadCloser, remoteURL string, createProgressReader func(in io.ReadCloser) io.ReadCloser) (context builder.ModifiableContext, dockerfileName string, err error) {
	switch {
	case remoteURL == "":
		context, err = builder.MakeTarSumContext(r)
	case urlutil.IsGitURL(remoteURL):
		context, err = builder.MakeGitContext(remoteURL)
	case urlutil.IsURL(remoteURL):
		context, err = builder.MakeRemoteContext(remoteURL, map[string]func(io.ReadCloser) (io.ReadCloser, error){
			httputils.MimeTypes.TextPlain: func(rc io.ReadCloser) (io.ReadCloser, error) {
				dockerfile, err := ioutil.ReadAll(rc)
				if err != nil {
					return nil, err
				}

				// dockerfileName is set to signal that the remote was interpreted as a single Dockerfile, in which case the caller
				// should use dockerfileName as the new name for the Dockerfile, irrespective of any other user input.
				dockerfileName = api.DefaultDockerfileName

				// TODO: return a context without tarsum
				return archive.Generate(dockerfileName, string(dockerfile))
			},
			// fallback handler (tar context)
			"": func(rc io.ReadCloser) (io.ReadCloser, error) {
				return createProgressReader(rc), nil
			},
		})
	default:
		err = fmt.Errorf("remoteURL (%s) could not be recognized as URL", remoteURL)
	}
	return
}


<|start_filename|>client/kill.go<|end_filename|>
package client

import (
	"fmt"
	"strconv"
	"strings"
	"syscall"

	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdKill(args ...string) error {
	var opts struct {
		Pod    bool   `short:"p" long:"pod" default-mask:"-" description:"kill all containers in a pod"`
		Signal string `short:"s" long:"signal" value-name:"\"\"" description:"The signal to kill containers, default is 9"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "kill [OPTIONS] CONTAINER_ID|POD_ID\n\nSend kill signal to container or Pod"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}

	if len(args) == 0 {
		return fmt.Errorf("\"kill\" requires a minimum of 1 argument, please provide container ID.\n")
	}

	sig := 9
	if opts.Signal != "" {
		s, err := parseSignal(opts.Signal)
		if err != nil {
			return err
		}
		sig = int(s)
	}

	for i := range args {
		if opts.Pod {
			err = cli.client.KillPod(args[i], sig)
			if err != nil {
				fmt.Fprintf(cli.err, "failed to kill pod %s: %v", args[i], err)
			}
		} else {
			err = cli.client.KillContainer(args[i], sig)
			if err != nil {
				fmt.Fprintf(cli.err, "failed to kill container %s: %v", args[i], err)
			}
		}
	}

	return nil
}

func parseSignal(rawSignal string) (syscall.Signal, error) {
	s, err := strconv.Atoi(rawSignal)
	if err == nil {
		return syscall.Signal(s), nil
	}
	signal, ok := linuxSignalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")]
	if !ok {
		return -1, fmt.Errorf("unknown signal %q", rawSignal)
	}
	return signal, nil
}

var linuxSignalMap = map[string]syscall.Signal{
	"ABRT":   syscall.SIGABRT,
	"ALRM":   syscall.SIGALRM,
	"BUS":    syscall.SIGBUS,
	"CHLD":   syscall.SIGCHLD,
	"CLD":    syscall.SIGCLD,
	"CONT":   syscall.SIGCONT,
	"FPE":    syscall.SIGFPE,
	"HUP":    syscall.SIGHUP,
	"ILL":    syscall.SIGILL,
	"INT":    syscall.SIGINT,
	"IO":     syscall.SIGIO,
	"IOT":    syscall.SIGIOT,
	"KILL":   syscall.SIGKILL,
	"PIPE":   syscall.SIGPIPE,
	"POLL":   syscall.SIGPOLL,
	"PROF":   syscall.SIGPROF,
	"PWR":    syscall.SIGPWR,
	"QUIT":   syscall.SIGQUIT,
	"SEGV":   syscall.SIGSEGV,
	"STKFLT": syscall.SIGSTKFLT,
	"STOP":   syscall.SIGSTOP,
	"SYS":    syscall.SIGSYS,
	"TERM":   syscall.SIGTERM,
	"TRAP":   syscall.SIGTRAP,
	"TSTP":   syscall.SIGTSTP,
	"TTIN":   syscall.SIGTTIN,
	"TTOU":   syscall.SIGTTOU,
	"UNUSED": syscall.SIGUNUSED,
	"URG":    syscall.SIGURG,
	"USR1":   syscall.SIGUSR1,
	"USR2":   syscall.SIGUSR2,
	"VTALRM": syscall.SIGVTALRM,
	"WINCH":  syscall.SIGWINCH,
	"XCPU":   syscall.SIGXCPU,
	"XFSZ":   syscall.SIGXFSZ,
}


<|start_filename|>server/router/service/service.go<|end_filename|>
package service

import (
	"github.com/hyperhq/hyperd/server/router"
	"github.com/hyperhq/hyperd/server/router/local"
)

// serverRouter is a router to talk with the server controller.
type serviceRouter struct {
	backend Backend
	routes  []router.Route
}

// NewRouter initializes a new systemRouter
func NewRouter(b Backend) router.Router {
	r := &serviceRouter{
		backend: b,
	}

	r.routes = []router.Route{
		// GET
		local.NewGetRoute("/service/list", r.getServices),
		// POST
		local.NewPostRoute("/service/add", r.postServiceAdd),
		local.NewPostRoute("/service/update", r.postServiceUpdate),
		// PUT
		// DELETE
		local.NewDeleteRoute("/service", r.deleteService),
	}

	return r
}

// Routes return all the API routes dedicated to the docker system.
func (s *serviceRouter) Routes() []router.Route {
	return s.routes
}


<|start_filename|>client/commit.go<|end_filename|>
package client

import (
	"fmt"
	"os"
	"strings"

	gflag "github.com/jessevdk/go-flags"
)

/*
	-a, --author=       Author (e.g., "Hello World <<EMAIL>>")
	-c, --change=[]     Apply Dockerfile instruction to the created image
	-m, --message=      Commit message
	-p, --pause         Pause container during Commit
	-h, --help          Print usage
*/
func (cli *HyperClient) HyperCmdCommit(args ...string) error {
	var opts struct {
		Author  string   `short:"a" long:"author" default:"" value-name:"\"\"" description:"Author (e.g., \"Hello World <<EMAIL>>\")"`
		Change  []string `short:"c" long:"change" default:"" value-name:"[]" description:"Apply Dockerfile instruction to the created image"`
		Message string   `short:"m" long:"message" default:"" value-name:"\"\"" description:"Commit message"`
		Pause   bool     `short:"p" long:"pause" description:"Pause container during Commit"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)

	parser.Usage = "commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]\n\nCreate a new image from a container's changes"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("%s: \"commit\" requires a minimum of 1 argument, See 'hyperctl build --help'.", os.Args[0])
	}
	var (
		containerId string = ""
		repo        string = ""
	)
	if len(args) > 0 {
		containerId = args[0]
	}
	if len(args) > 1 {
		repo = args[1]
	}

	id, err := cli.client.Commit(containerId, repo, opts.Author, opts.Message, opts.Change, opts.Pause)
	if err != nil {
		return err
	}

	fmt.Fprintf(cli.out, "%s\n", id)
	return nil
}


<|start_filename|>vendor/github.com/hyperhq/runv/hypervisor/network/portmapper/portmapper.go<|end_filename|>
package portmapper

import (
	"fmt"
	"strings"
	"sync"

	"github.com/golang/glog"
)

type PortMap struct {
	containerIP   string
	containerPort int
}

func newPortMap(containerip string, containerport int) *PortMap {
	return &PortMap{
		containerIP:   containerip,
		containerPort: containerport,
	}
}

type PortSet map[int]*PortMap

type PortMapper struct {
	tcpMap PortSet
	udpMap PortSet
	mutex  sync.Mutex
}

func New() *PortMapper {
	return &PortMapper{PortSet{}, PortSet{}, sync.Mutex{}}
}

func (p *PortMapper) AllocateMap(protocol string, hostPort int,
	containerIP string, ContainerPort int) error {
	p.mutex.Lock()
	defer p.mutex.Unlock()

	var pset PortSet

	if strings.EqualFold(protocol, "udp") {
		pset = p.udpMap
	} else {
		pset = p.tcpMap
	}

	e, ok := pset[hostPort]
	if ok {
		return fmt.Errorf("Host port %d had already been used, %s %d",
			hostPort, e.containerIP, e.containerPort)
	}

	allocated := newPortMap(containerIP, ContainerPort)
	pset[hostPort] = allocated

	return nil
}

func (p *PortMapper) ReleaseMap(protocol string, hostPort int) error {
	p.mutex.Lock()
	defer p.mutex.Unlock()

	var pset PortSet

	if strings.EqualFold(protocol, "udp") {
		pset = p.udpMap
	} else {
		pset = p.tcpMap
	}

	_, ok := pset[hostPort]
	if !ok {
		glog.Errorf("Host port %d has not been used", hostPort)
	}

	delete(pset, hostPort)
	return nil
}


<|start_filename|>integration/client.go<|end_filename|>
package integration

import (
	"encoding/binary"
	"fmt"
	"io"
	"time"

	"github.com/hyperhq/hyperd/lib/promise"
	"github.com/hyperhq/hyperd/types"

	"github.com/docker/docker/pkg/stdcopy"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

// HyperClient is the gRPC client for hyperd
type HyperClient struct {
	client types.PublicAPIClient
	ctx    context.Context
}

// NewHyperClient creates a new *HyperClient
func NewHyperClient(server string) (*HyperClient, error) {
	conn, err := grpc.Dial(server, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
	if err != nil {
		return nil, err
	}

	return &HyperClient{
		client: types.NewPublicAPIClient(conn),
		ctx:    context.Background(),
	}, nil
}

// GetPodInfo gets pod info by podID
func (c *HyperClient) GetPodInfo(podID string) (*types.PodInfo, error) {
	request := types.PodInfoRequest{
		PodID: podID,
	}
	pod, err := c.client.PodInfo(c.ctx, &request)
	if err != nil {
		return nil, err
	}

	return pod.PodInfo, nil
}

// GetPodList get a list of Pods
func (c *HyperClient) GetPodList() ([]*types.PodListResult, error) {
	request := types.PodListRequest{}
	podList, err := c.client.PodList(
		c.ctx,
		&request,
	)
	if err != nil {
		return nil, err
	}

	return podList.PodList, nil
}

// GetVMList gets a list of VMs
func (c *HyperClient) GetVMList() ([]*types.VMListResult, error) {
	req := types.VMListRequest{}
	vmList, err := c.client.VMList(
		c.ctx,
		&req,
	)
	if err != nil {
		return nil, err
	}

	return vmList.VmList, nil
}

// GetContainerList gets a list of containers
func (c *HyperClient) GetContainerList() ([]*types.ContainerListResult, error) {
	req := types.ContainerListRequest{}
	containerList, err := c.client.ContainerList(
		c.ctx,
		&req,
	)
	if err != nil {
		return nil, err
	}

	return containerList.ContainerList, nil
}

// GetContainerInfo gets container info by container name or id
func (c *HyperClient) GetContainerInfo(container string) (*types.ContainerInfo, error) {
	req := types.ContainerInfoRequest{
		Container: container,
	}
	cinfo, err := c.client.ContainerInfo(
		c.ctx,
		&req,
	)
	if err != nil {
		return nil, err
	}

	return cinfo.ContainerInfo, nil
}

// GetContainerLogs gets container log by container name or id
func (c *HyperClient) GetContainerLogs(container string) ([]byte, error) {
	req := types.ContainerLogsRequest{
		Container:  container,
		Follow:     false,
		Timestamps: false,
		Tail:       "",
		Since:      "",
		Stdout:     true,
		Stderr:     true,
	}
	stream, err := c.client.ContainerLogs(
		c.ctx,
		&req,
	)
	if err != nil {
		return nil, err
	}

	ret := []byte{}
	for {
		res, err := stream.Recv()
		if err == io.EOF {
			if req.Follow == true {
				continue
			}
			break
		}
		if err != nil {
			return nil, err
		}
		ret = append(ret, res.Log...)
	}

	return ret, nil
}

type StreamExtractor interface {
	Extract(orig []byte) ([]byte, []byte, error)
}

type RawExtractor struct{}

const (
	// Stdin represents standard input stream type.
	Stdin stdcopy.StdType = iota
	// Stdout represents standard output stream type.
	Stdout
	// Stderr represents standard error steam type.
	Stderr

	stdWriterPrefixLen = 8
	stdWriterFdIndex   = 0
	stdWriterSizeIndex = 4
)

type StdcopyExtractor struct {
	readingHead bool
	current     stdcopy.StdType
	remain      int

	headbuf []byte
	headlen int
}

func NewExtractor(tty bool) StreamExtractor {
	if tty {
		return &RawExtractor{}
	}
	return &StdcopyExtractor{
		readingHead: true,
		headbuf:     make([]byte, stdWriterPrefixLen),
	}
}

func (r *RawExtractor) Extract(orig []byte) ([]byte, []byte, error) {
	return orig, nil, nil
}

func (s *StdcopyExtractor) Extract(orig []byte) ([]byte, []byte, error) {
	var (
		stdout = []byte{}
		stderr = []byte{}
	)
	for len(orig) > 0 {
		if s.readingHead {
			hrl := stdWriterPrefixLen - s.headlen //hrl -- head remain length
			if len(orig) < hrl {
				copy(s.headbuf[s.headlen:], orig)
				s.headlen += len(orig)
				return stdout, stderr, nil
			}

			copy(s.headbuf[s.headlen:], orig[:hrl])
			orig = orig[hrl:]
			s.headlen = 0

			stype := stdcopy.StdType(s.headbuf[stdWriterFdIndex])
			if stype != Stdout && stype != Stderr {
				return stdout, stderr, fmt.Errorf("invalid stream type %x", stype)
			}

			s.current = stype
			s.remain = int(binary.BigEndian.Uint32(s.headbuf[stdWriterSizeIndex : stdWriterSizeIndex+4]))
			s.readingHead = false
		}

		var (
			msg []byte
			ml  int
		)
		if len(orig) < s.remain {
			s.remain -= len(orig)
			ml = len(orig)
		} else {
			ml = s.remain
			s.readingHead = true
			s.remain = 0
		}

		msg = orig[:ml]
		orig = orig[ml:]

		switch s.current {
		case Stdout:
			stdout = append(stdout, msg...)
		case Stderr:
			stderr = append(stderr, msg...)
		}
	}
	return stdout, stderr, nil

}

// PostAttach attach to a container or pod by id
func (c *HyperClient) PostAttach(id string, tty bool) error {
	stream, err := c.client.Attach(c.ctx)
	if err != nil {
		return err
	}

	extractor := NewExtractor(tty)

	req := types.AttachMessage{
		ContainerID: id,
	}
	if err := stream.Send(&req); err != nil {
		return err
	}

	cmd := types.AttachMessage{
		Data: []byte("echo Hello Hyper\n"),
	}
	if err := stream.Send(&cmd); err != nil {
		return err
	}

	res, err := stream.Recv()
	if err != nil {
		return err
	}

	out, _, err := extractor.Extract(res.Data)
	if err != nil {
		return err
	}

	if string(out) != "Hello Hyper\n" {
		return fmt.Errorf("post attach response error\n")
	}

	return nil
}

// GetImageList gets a list of images
func (c *HyperClient) GetImageList() ([]*types.ImageInfo, error) {
	req := types.ImageListRequest{}
	imageList, err := c.client.ImageList(
		c.ctx,
		&req,
	)
	if err != nil {
		return nil, err
	}

	return imageList.ImageList, nil
}

// CreatePod creates a pod
func (c *HyperClient) CreatePod(spec *types.UserPod) (string, error) {
	req := types.PodCreateRequest{
		PodSpec: spec,
	}
	resp, err := c.client.PodCreate(
		c.ctx,
		&req,
	)
	if err != nil {
		return "", err
	}

	return resp.PodID, nil
}

// CreateContainer creates a container
func (c *HyperClient) CreateContainer(podID string, spec *types.UserContainer) (string, error) {
	req := types.ContainerCreateRequest{
		PodID:         podID,
		ContainerSpec: spec,
	}
	resp, err := c.client.ContainerCreate(c.ctx, &req)
	if err != nil {
		return "", err
	}

	return resp.ContainerID, nil
}

// RenameContainer renames a container
func (c *HyperClient) RenameContainer(oldName string, newName string) error {
	req := types.ContainerRenameRequest{
		OldContainerName: oldName,
		NewContainerName: newName,
	}
	_, err := c.client.ContainerRename(c.ctx, &req)

	if err != nil {
		return err
	}

	return nil
}

// RemovePod removes a pod by podID
func (c *HyperClient) RemovePod(podID string) error {
	_, err := c.client.PodRemove(
		c.ctx,
		&types.PodRemoveRequest{PodID: podID},
	)

	if err != nil {
		return err
	}

	return nil
}

// ContainerExecSignal sends signal to specified exec of specified container
func (c *HyperClient) ContainerExecSignal(container, execID string, sig int64) error {
	req := types.ExecSignalRequest{
		ContainerID: container,
		ExecID:      execID,
		Signal:      sig,
	}
	_, err := c.client.ExecSignal(c.ctx, &req)
	if err != nil {
		return err
	}

	return nil
}

// ContainerExecCreate creates exec in a container
func (c *HyperClient) ContainerExecCreate(container string, command []string, tty bool) (string, error) {
	req := types.ExecCreateRequest{
		ContainerID: container,
		Command:     command,
		Tty:         tty,
	}
	resp, err := c.client.ExecCreate(c.ctx, &req)
	if err != nil {
		return "", err
	}

	return resp.ExecID, nil
}

// ContainerExecStart starts exec in a container with input stream in and output stream out
func (c *HyperClient) ContainerExecStart(containerId, execId string, stdin io.ReadCloser, stdout, stderr io.Writer, tty bool) error {
	request := types.ExecStartRequest{
		ContainerID: containerId,
		ExecID:      execId,
	}
	stream, err := c.client.ExecStart(context.Background())
	if err != nil {
		return err
	}
	if err := stream.Send(&request); err != nil {
		return err
	}
	extractor := NewExtractor(tty)
	var recvStdoutError chan error
	if stdout != nil || stderr != nil {
		recvStdoutError = promise.Go(func() (err error) {
			for {
				in, err := stream.Recv()
				if err != nil && err != io.EOF {
					return err
				}
				if in != nil && in.Stdout != nil {
					so, se, ee := extractor.Extract(in.Stdout)
					if ee != nil {
						return ee
					}
					if len(so) > 0 {
						nw, ew := stdout.Write(so)
						if ew != nil {
							return ew
						}
						if nw != len(so) {
							return io.ErrShortWrite
						}
					}
					if len(se) > 0 {
						nw, ew := stdout.Write(se)
						if ew != nil {
							return ew
						}
						if nw != len(se) {
							return io.ErrShortWrite
						}

					}
				}
				if err == io.EOF {
					break
				}
			}
			return nil
		})
	}
	if stdin != nil {
		go func() error {
			defer stream.CloseSend()
			buf := make([]byte, 32)
			for {
				nr, err := stdin.Read(buf)
				if nr > 0 {
					if err := stream.Send(&types.ExecStartRequest{Stdin: buf[:nr]}); err != nil {
						return err
					}
				}
				if err == io.EOF {
					break
				}
				if err != nil {
					return err
				}
			}
			return nil
		}()
	}
	if stdout != nil || stderr != nil {
		if err := <-recvStdoutError; err != nil {
			return err
		}
	}

	return nil
}

// StartPod starts a pod by podID
func (c *HyperClient) StartPod(podID string) error {
	req := &types.PodStartRequest{
		PodID: podID,
	}

	_, err := c.client.PodStart(c.ctx, req)
	if err != nil {
		return err
	}

	return nil
}

// StopPod stops a pod
func (c *HyperClient) StopPod(podID string) (int, string, error) {
	resp, err := c.client.PodStop(c.ctx, &types.PodStopRequest{
		PodID: podID,
	})
	if err != nil {
		return -1, "", err
	}

	return int(resp.Code), resp.Cause, nil
}

// PausePod pauses a pod
func (c *HyperClient) PausePod(podID string) error {
	_, err := c.client.PodPause(c.ctx, &types.PodPauseRequest{
		PodID: podID,
	})
	if err != nil {
		return err
	}

	return nil
}

// UnpausePod unpauses a pod
func (c *HyperClient) UnpausePod(podID string) error {
	_, err := c.client.PodUnpause(c.ctx, &types.PodUnpauseRequest{
		PodID: podID,
	})
	if err != nil {
		return err
	}

	return nil
}

// PodSignal sends a signal to all containers of specified pod
func (c *HyperClient) PodSignal(podID string, signal int64) error {
	_, err := c.client.PodSignal(c.ctx, &types.PodSignalRequest{
		PodID:  podID,
		Signal: signal,
	})
	if err != nil {
		return err
	}

	return nil
}

// Wait gets exitcode by container and processId
func (c *HyperClient) Wait(container, processId string, noHang bool) (int32, error) {
	request := types.WaitRequest{
		Container: container,
		ProcessId: processId,
		NoHang:    noHang,
	}
	response, err := c.client.Wait(c.ctx, &request)
	if err != nil {
		return -1, err
	}

	return response.ExitCode, nil
}

func (c *HyperClient) PullImage(image, tag string, out io.Writer) error {
	request := types.ImagePullRequest{
		Image: image,
		Tag:   tag,
	}

	stream, err := c.client.ImagePull(c.ctx, &request)
	if err != nil {
		return err
	}

	for {
		res, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		if out != nil {
			n, err := out.Write(res.Data)
			if err != nil {
				return err
			}
			if n != len(res.Data) {
				return io.ErrShortWrite
			}
		}
	}

	return nil
}

func (c *HyperClient) RemoveImage(image string) error {
	_, err := c.client.ImageRemove(c.ctx, &types.ImageRemoveRequest{Image: image})
	return err
}

func (c *HyperClient) PushImage(repo, tag string, out io.Writer) error {
	request := types.ImagePushRequest{
		Repo: repo,
		Tag:  tag,
	}

	stream, err := c.client.ImagePush(c.ctx, &request)
	if err != nil {
		return err
	}

	for {
		res, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		if out != nil {
			n, err := out.Write(res.Data)
			if err != nil {
				return err
			}
			if n != len(res.Data) {
				return io.ErrShortWrite
			}
		}
	}

	return nil
}

// DeleteService deletes user service by podID and service content
func (c *HyperClient) DeleteService(podID string, services []*types.UserService) error {
	_, err := c.client.ServiceDelete(
		c.ctx,
		&types.ServiceDelRequest{PodID: podID, Services: services},
	)

	if err != nil {
		return err
	}
	return nil
}

// ListService lists user services by podID
func (c *HyperClient) ListService(podID string) ([]*types.UserService, error) {
	resp, err := c.client.ServiceList(
		c.ctx,
		&types.ServiceListRequest{PodID: podID},
	)

	if err != nil {
		return nil, err
	}

	return resp.Services, nil
}

// GetPodStats get stats of Pod by podID
func (c *HyperClient) GetPodStats(podID string) (*types.PodStats, error) {
	statsResponse, err := c.client.PodStats(
		c.ctx,
		&types.PodStatsRequest{PodID: podID},
	)

	if err != nil {
		return nil, err
	}

	return statsResponse.PodStats, nil
}

// AddService adds user service by podID and service content
func (c *HyperClient) AddService(podID string, services []*types.UserService) error {
	_, err := c.client.ServiceAdd(
		c.ctx,
		&types.ServiceAddRequest{PodID: podID, Services: services},
	)

	if err != nil {
		return err
	}

	return nil
}

// UpdateService updates user service by podID and service content
func (c *HyperClient) UpdateService(podID string, services []*types.UserService) error {
	_, err := c.client.ServiceUpdate(
		c.ctx,
		&types.ServiceUpdateRequest{PodID: podID, Services: services},
	)
	if err != nil {
		return err
	}

	return nil
}

// SetPodLabels sets labels to Pod by podID
func (c *HyperClient) SetPodLabels(podID string, override bool, labels map[string]string) error {
	_, err := c.client.SetPodLabels(
		c.ctx,
		&types.PodLabelsRequest{PodID: podID, Override: override, Labels: labels},
	)

	if err != nil {
		return err
	}

	return nil
}

// Info gets system info of hyperd
func (c *HyperClient) Info() (*types.InfoResponse, error) {
	info, err := c.client.Info(
		c.ctx,
		&types.InfoRequest{},
	)

	if err != nil {
		return nil, err
	}

	return info, nil
}

// Ping checks if hyperd is running (returns 'OK' on success)
func (c *HyperClient) Ping() (*types.PingResponse, error) {
	resp, err := c.client.Ping(
		c.ctx,
		&types.PingRequest{},
	)

	if err != nil {
		return nil, err
	}

	return resp, nil
}

// ContainerSignal sends a signal to specified container of specified pod
func (c *HyperClient) ContainerSignal(podID, containerID string, signal int64) error {
	_, err := c.client.ContainerSignal(c.ctx, &types.ContainerSignalRequest{
		PodID:       podID,
		ContainerID: containerID,
		Signal:      signal,
	})

	return err
}

// TTYResize resizes the tty of the specified container
func (c *HyperClient) TTYResize(containerID, execID string, height, width int32) error {
	_, err := c.client.TTYResize(c.ctx, &types.TTYResizeRequest{
		ContainerID: containerID,
		ExecID:      execID,
		Height:      height,
		Width:       width,
	})

	return err
}


<|start_filename|>server/server_unix.go<|end_filename|>
// +build freebsd linux

package server

import (
	"crypto/tls"
	"fmt"
	"net"
	"net/http"
	"strconv"

	"github.com/docker/go-connections/sockets"
	"github.com/golang/glog"

	systemdActivation "github.com/coreos/go-systemd/activation"
)

// newServer sets up the required HTTPServers and does protocol specific checking.
// newServer does not set any muxers, you should set it later to Handler field
func (s *Server) newServer(proto, addr string) ([]*HTTPServer, error) {
	var (
		err error
		ls  []net.Listener
	)
	switch proto {
	case "fd":
		ls, err = listenFD(addr, s.cfg.TLSConfig)
		if err != nil {
			return nil, err
		}
	case "tcp":
		l, err := s.initTCPSocket(addr)
		if err != nil {
			return nil, err
		}
		ls = append(ls, l)
	case "unix":
		l, err := sockets.NewUnixSocket(addr, s.cfg.SocketGroup)
		if err != nil {
			return nil, fmt.Errorf("can't create unix socket %s: %v", addr, err)
		}
		ls = append(ls, l)
	default:
		return nil, fmt.Errorf("Invalid protocol format: %q", proto)
	}
	var res []*HTTPServer
	for _, l := range ls {
		res = append(res, &HTTPServer{
			&http.Server{
				Addr: addr,
			},
			l,
		})
	}
	return res, nil
}

// listenFD returns the specified socket activated files as a slice of
// net.Listeners or all of the activated files if "*" is given.
func listenFD(addr string, tlsConfig *tls.Config) ([]net.Listener, error) {
	var (
		err       error
		listeners []net.Listener
	)
	// socket activation
	if tlsConfig != nil {
		listeners, err = systemdActivation.TLSListeners(false, tlsConfig)
	} else {
		listeners, err = systemdActivation.Listeners(false)
	}
	if err != nil {
		return nil, err
	}

	if len(listeners) == 0 {
		return nil, fmt.Errorf("No sockets found")
	}

	// default to all fds just like unix:// and tcp://
	if addr == "" || addr == "*" {
		return listeners, nil
	}

	fdNum, err := strconv.Atoi(addr)
	if err != nil {
		return nil, fmt.Errorf("failed to parse systemd address, should be number: %v", err)
	}
	fdOffset := fdNum - 3
	if len(listeners) < int(fdOffset)+1 {
		return nil, fmt.Errorf("Too few socket activated files passed in")
	}
	if listeners[fdOffset] == nil {
		return nil, fmt.Errorf("failed to listen on systemd activated file at fd %d", fdOffset+3)
	}
	for i, ls := range listeners {
		if i == fdOffset || ls == nil {
			continue
		}
		if err := ls.Close(); err != nil {
			glog.Errorf("Failed to close systemd activated file at fd %d: %v", fdOffset+3, err)
		}
	}
	return []net.Listener{listeners[fdOffset]}, nil
}


<|start_filename|>utils/utils_linux.go<|end_filename|>
// +build linux

package utils

import (
	"syscall"
)

var (
	MS_BIND uintptr = syscall.MS_BIND
)

func Mount(source string, target string, fstype string, flags uintptr, data string) error {
	if err := syscall.Mount(source, target, fstype, flags, data); err != nil {
		return err
	}
	return nil
}


<|start_filename|>client/save.go<|end_filename|>
package client

import (
	"errors"
	"fmt"
	"io"
	"os"
	"strings"

	runconfigopts "github.com/docker/docker/runconfig/opts"
	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdSave(args ...string) error {
	var opts struct {
		Output string   `short:"o" long:"output" value-name:"\"\"" description:"Write to a file, instead of STDOUT"`
		Format string   `short:"f" long:"format" value-name:"\"\"" description:"Specify the format of the output tar archive"`
		Refs   []string `short:"r" long:"references" value-name:"\"\"" description:"References to use when saving an OCI image layout tar archive"`
	}

	output := cli.out
	var parser = gflag.NewParser(&opts, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "save [OPTIONS] IMAGE [IMAGE...]\n\nSave one or more images to a tar archive (streamed to STDOUT by default)"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}

	if len(args) == 0 {
		return fmt.Errorf("\"save\" requires a minimum of 1 argument, please provide IMAGE ID.\n")
	}

	if opts.Output == "" && cli.isTerminalOut {
		return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
	}
	if opts.Output != "" {
		if output, err = os.Create(opts.Output); err != nil {
			return err
		}
	}

	images := args

	responseBody, err := cli.client.Save(images, opts.Format, runconfigopts.ConvertKVStringsToMap(opts.Refs))
	if err != nil {
		fmt.Fprintf(cli.err, err.Error()+"\n")
		return err
	}
	defer responseBody.Close()
	_, err = io.Copy(output, responseBody)
	return err
}


<|start_filename|>server/router/service/backend.go<|end_filename|>
package service

import (
	"github.com/hyperhq/hyperd/engine"
	apitypes "github.com/hyperhq/hyperd/types"
)

// Backend is the methods that need to be implemented to provide
// system specific functionality.
type Backend interface {
	CmdGetServices(podId string) ([]*apitypes.UserService, error)
	CmdAddService(podId, data string) (*engine.Env, error)
	CmdUpdateService(podId, services string) (*engine.Env, error)
	CmdDeleteService(podId, services string) (*engine.Env, error)
}


<|start_filename|>client/api/pause.go<|end_filename|>
package api

import (
	"net/url"

	"github.com/hyperhq/hyperd/engine"
)

func (cli *Client) PausePod(podId string) error {
	v := url.Values{}
	v.Set("podId", podId)

	body, _, err := readBody(cli.call("POST", "/pod/pause?"+v.Encode(), nil, nil))
	if err != nil {
		return err
	}

	out := engine.NewOutput()
	if _, err = out.AddEnv(); err != nil {
		return err
	}

	if _, err := out.Write(body); err != nil {
		return err
	}
	out.Close()

	return nil
}

func (cli *Client) UnpausePod(podId string) error {
	v := url.Values{}
	v.Set("podId", podId)

	body, _, err := readBody(cli.call("POST", "/pod/unpause?"+v.Encode(), nil, nil))
	if err != nil {
		return err
	}

	out := engine.NewOutput()
	if _, err = out.AddEnv(); err != nil {
		return err
	}

	if _, err := out.Write(body); err != nil {
		return err
	}
	out.Close()

	return nil
}


<|start_filename|>daemon/pod/sandbox.go<|end_filename|>
package pod

import (
	"github.com/hyperhq/hypercontainer-utils/hlog"
	"github.com/hyperhq/runv/factory"
	"github.com/hyperhq/runv/hypervisor"
)

const (
	maxReleaseRetry = 3
)

func startSandbox(f factory.Factory, cpu, mem int, kernel, initrd string) (vm *hypervisor.Vm, err error) {
	var (
		DEFAULT_CPU = 1
		DEFAULT_MEM = 128
	)

	if cpu <= 0 {
		cpu = DEFAULT_CPU
	}
	if mem <= 0 {
		mem = DEFAULT_MEM
	}

	if kernel == "" {
		hlog.Log(DEBUG, "get sandbox from factory: CPU: %d, Memory %d", cpu, mem)
		vm, err = f.GetVm(cpu, mem)
	} else {
		hlog.Log(DEBUG, "The create sandbox with: kernel=%s, initrd=%s, cpu=%d, memory=%d", kernel, initrd, cpu, mem)
		config := &hypervisor.BootConfig{
			CPU:    cpu,
			Memory: mem,
			Kernel: kernel,
			Initrd: initrd,
		}
		vm, err = hypervisor.GetVm("", config, false)
	}
	if err != nil {
		hlog.Log(ERROR, "failed to create a sandbox (cpu=%d, mem=%d kernel=%s initrd=%d): %v", cpu, mem, kernel, initrd, err)
	}

	return vm, err
}

func dissociateSandbox(sandbox *hypervisor.Vm, retry int) error {
	if sandbox == nil {
		return nil
	}

	err := sandbox.ReleaseVm()
	if err != nil {
		hlog.Log(WARNING, "SB[%s] failed to release sandbox: %v", sandbox.Id, err)
		hlog.Log(INFO, "SB[%s] shutdown because of failed release", sandbox.Id)
		sandbox.Kill()
		return err
	}
	return nil
}


<|start_filename|>vendor/github.com/docker/docker/daemon/execdriver/driver_unix.go<|end_filename|>
// +build !windows

package execdriver

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/docker/docker/daemon/execdriver/native/template"
	"github.com/docker/docker/pkg/idtools"
	"github.com/docker/docker/pkg/mount"
	"github.com/docker/go-units"
	"github.com/opencontainers/runc/libcontainer"
	"github.com/opencontainers/runc/libcontainer/cgroups/fs"
	"github.com/opencontainers/runc/libcontainer/configs"
	blkiodev "github.com/opencontainers/runc/libcontainer/configs"
)

// Mount contains information for a mount operation.
type Mount struct {
	Source      string `json:"source"`
	Destination string `json:"destination"`
	Writable    bool   `json:"writable"`
	Data        string `json:"data"`
	Propagation string `json:"mountpropagation"`
}

// Resources contains all resource configs for a driver.
// Currently these are all for cgroup configs.
type Resources struct {
	CommonResources

	// Fields below here are platform specific

	BlkioWeightDevice            []*blkiodev.WeightDevice   `json:"blkio_weight_device"`
	BlkioThrottleReadBpsDevice   []*blkiodev.ThrottleDevice `json:"blkio_throttle_read_bps_device"`
	BlkioThrottleWriteBpsDevice  []*blkiodev.ThrottleDevice `json:"blkio_throttle_write_bps_device"`
	BlkioThrottleReadIOpsDevice  []*blkiodev.ThrottleDevice `json:"blkio_throttle_read_iops_device"`
	BlkioThrottleWriteIOpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_write_iops_device"`
	MemorySwap                   int64                      `json:"memory_swap"`
	KernelMemory                 int64                      `json:"kernel_memory"`
	CPUQuota                     int64                      `json:"cpu_quota"`
	CpusetCpus                   string                     `json:"cpuset_cpus"`
	CpusetMems                   string                     `json:"cpuset_mems"`
	CPUPeriod                    int64                      `json:"cpu_period"`
	Rlimits                      []*units.Rlimit            `json:"rlimits"`
	OomKillDisable               bool                       `json:"oom_kill_disable"`
	MemorySwappiness             int64                      `json:"memory_swappiness"`
}

// ProcessConfig is the platform specific structure that describes a process
// that will be run inside a container.
type ProcessConfig struct {
	CommonProcessConfig

	// Fields below here are platform specific
	Privileged bool   `json:"privileged"`
	User       string `json:"user"`
	Console    string `json:"-"` // dev/console path
}

// Ipc settings of the container
// It is for IPC namespace setting. Usually different containers
// have their own IPC namespace, however this specifies to use
// an existing IPC namespace.
// You can join the host's or a container's IPC namespace.
type Ipc struct {
	ContainerID string `json:"container_id"` // id of the container to join ipc.
	HostIpc     bool   `json:"host_ipc"`
}

// Pid settings of the container
// It is for PID namespace setting. Usually different containers
// have their own PID namespace, however this specifies to use
// an existing PID namespace.
// Joining the host's PID namespace is currently the only supported
// option.
type Pid struct {
	HostPid bool `json:"host_pid"`
}

// UTS settings of the container
// It is for UTS namespace setting. Usually different containers
// have their own UTS namespace, however this specifies to use
// an existing UTS namespace.
// Joining the host's UTS namespace is currently the only supported
// option.
type UTS struct {
	HostUTS bool `json:"host_uts"`
}

// Network settings of the container
type Network struct {
	Mtu            int    `json:"mtu"`
	ContainerID    string `json:"container_id"` // id of the container to join network.
	NamespacePath  string `json:"namespace_path"`
	HostNetworking bool   `json:"host_networking"`
}

// Command wraps an os/exec.Cmd to add more metadata
type Command struct {
	CommonCommand

	// Fields below here are platform specific

	AllowedDevices     []*configs.Device `json:"allowed_devices"`
	AppArmorProfile    string            `json:"apparmor_profile"`
	AutoCreatedDevices []*configs.Device `json:"autocreated_devices"`
	CapAdd             []string          `json:"cap_add"`
	CapDrop            []string          `json:"cap_drop"`
	CgroupParent       string            `json:"cgroup_parent"` // The parent cgroup for this command.
	GIDMapping         []idtools.IDMap   `json:"gidmapping"`
	GroupAdd           []string          `json:"group_add"`
	Ipc                *Ipc              `json:"ipc"`
	OomScoreAdj        int               `json:"oom_score_adj"`
	Pid                *Pid              `json:"pid"`
	ReadonlyRootfs     bool              `json:"readonly_rootfs"`
	RemappedRoot       *User             `json:"remap_root"`
	SeccompProfile     string            `json:"seccomp_profile"`
	UIDMapping         []idtools.IDMap   `json:"uidmapping"`
	UTS                *UTS              `json:"uts"`
}

// SetRootPropagation sets the root mount propagation mode.
func SetRootPropagation(config *configs.Config, propagation int) {
	config.RootPropagation = propagation
}

// InitContainer is the initialization of a container config.
// It returns the initial configs for a container. It's mostly
// defined by the default template.
func InitContainer(c *Command) *configs.Config {
	container := template.New()

	container.Hostname = getEnv("HOSTNAME", c.ProcessConfig.Env)
	container.Cgroups.Name = c.ID
	container.Cgroups.Resources.AllowedDevices = c.AllowedDevices
	container.Devices = filterDevices(c.AutoCreatedDevices, (c.RemappedRoot.UID != 0))
	container.Rootfs = c.Rootfs
	container.Readonlyfs = c.ReadonlyRootfs
	// This can be overridden later by driver during mount setup based
	// on volume options
	SetRootPropagation(container, mount.RPRIVATE)
	container.Cgroups.Parent = c.CgroupParent

	// check to see if we are running in ramdisk to disable pivot root
	container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != ""

	return container
}

func filterDevices(devices []*configs.Device, userNamespacesEnabled bool) []*configs.Device {
	if !userNamespacesEnabled {
		return devices
	}

	filtered := []*configs.Device{}
	// if we have user namespaces enabled, these devices will not be created
	// because of the mknod limitation in the kernel for an unprivileged process.
	// Rather, they will be bind-mounted, which will only work if they exist;
	// check for existence and remove non-existent entries from the list
	for _, device := range devices {
		if _, err := os.Stat(device.Path); err == nil {
			filtered = append(filtered, device)
		}
	}
	return filtered
}

func getEnv(key string, env []string) string {
	for _, pair := range env {
		parts := strings.SplitN(pair, "=", 2)
		if parts[0] == key {
			return parts[1]
		}
	}
	return ""
}

// SetupCgroups setups cgroup resources for a container.
func SetupCgroups(container *configs.Config, c *Command) error {
	if c.Resources != nil {
		container.Cgroups.Resources.CpuShares = c.Resources.CPUShares
		container.Cgroups.Resources.Memory = c.Resources.Memory
		container.Cgroups.Resources.MemoryReservation = c.Resources.MemoryReservation
		container.Cgroups.Resources.MemorySwap = c.Resources.MemorySwap
		container.Cgroups.Resources.KernelMemory = c.Resources.KernelMemory
		container.Cgroups.Resources.CpusetCpus = c.Resources.CpusetCpus
		container.Cgroups.Resources.CpusetMems = c.Resources.CpusetMems
		container.Cgroups.Resources.CpuPeriod = c.Resources.CPUPeriod
		container.Cgroups.Resources.CpuQuota = c.Resources.CPUQuota
		container.Cgroups.Resources.BlkioWeight = c.Resources.BlkioWeight
		container.Cgroups.Resources.BlkioWeightDevice = c.Resources.BlkioWeightDevice
		container.Cgroups.Resources.BlkioThrottleReadBpsDevice = c.Resources.BlkioThrottleReadBpsDevice
		container.Cgroups.Resources.BlkioThrottleWriteBpsDevice = c.Resources.BlkioThrottleWriteBpsDevice
		container.Cgroups.Resources.BlkioThrottleReadIOPSDevice = c.Resources.BlkioThrottleReadIOpsDevice
		container.Cgroups.Resources.BlkioThrottleWriteIOPSDevice = c.Resources.BlkioThrottleWriteIOpsDevice
		container.Cgroups.Resources.OomKillDisable = c.Resources.OomKillDisable
		container.Cgroups.Resources.MemorySwappiness = c.Resources.MemorySwappiness
	}

	return nil
}

// Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo.
func getNetworkInterfaceStats(interfaceName string) (*libcontainer.NetworkInterface, error) {
	out := &libcontainer.NetworkInterface{Name: interfaceName}
	// This can happen if the network runtime information is missing - possible if the
	// container was created by an old version of libcontainer.
	if interfaceName == "" {
		return out, nil
	}
	type netStatsPair struct {
		// Where to write the output.
		Out *uint64
		// The network stats file to read.
		File string
	}
	// Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container.
	netStats := []netStatsPair{
		{Out: &out.RxBytes, File: "tx_bytes"},
		{Out: &out.RxPackets, File: "tx_packets"},
		{Out: &out.RxErrors, File: "tx_errors"},
		{Out: &out.RxDropped, File: "tx_dropped"},

		{Out: &out.TxBytes, File: "rx_bytes"},
		{Out: &out.TxPackets, File: "rx_packets"},
		{Out: &out.TxErrors, File: "rx_errors"},
		{Out: &out.TxDropped, File: "rx_dropped"},
	}
	for _, netStat := range netStats {
		data, err := readSysfsNetworkStats(interfaceName, netStat.File)
		if err != nil {
			return nil, err
		}
		*(netStat.Out) = data
	}
	return out, nil
}

// Reads the specified statistics available under /sys/class/net/<EthInterface>/statistics
func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
	data, err := ioutil.ReadFile(filepath.Join("/sys/class/net", ethInterface, "statistics", statsFile))
	if err != nil {
		return 0, err
	}
	return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
}

// Stats collects all the resource usage information from a container.
func Stats(containerDir string, containerMemoryLimit int64, machineMemory int64) (*ResourceStats, error) {
	f, err := os.Open(filepath.Join(containerDir, "state.json"))
	if err != nil {
		return nil, err
	}
	defer f.Close()

	type network struct {
		Type              string
		HostInterfaceName string
	}

	state := struct {
		CgroupPaths map[string]string `json:"cgroup_paths"`
		Networks    []network
	}{}

	if err := json.NewDecoder(f).Decode(&state); err != nil {
		return nil, err
	}
	now := time.Now()

	mgr := fs.Manager{Paths: state.CgroupPaths}
	cstats, err := mgr.GetStats()
	if err != nil {
		return nil, err
	}
	stats := &libcontainer.Stats{CgroupStats: cstats}
	// if the container does not have any memory limit specified set the
	// limit to the machines memory
	memoryLimit := containerMemoryLimit
	if memoryLimit == 0 {
		memoryLimit = machineMemory
	}
	for _, iface := range state.Networks {
		switch iface.Type {
		case "veth":
			istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
			if err != nil {
				return nil, err
			}
			stats.Interfaces = append(stats.Interfaces, istats)
		}
	}
	return &ResourceStats{
		Stats:       stats,
		Read:        now,
		MemoryLimit: memoryLimit,
	}, nil
}

// User contains the uid and gid representing a Unix user
type User struct {
	UID int `json:"root_uid"`
	GID int `json:"root_gid"`
}

// ExitStatus provides exit reasons for a container.
type ExitStatus struct {
	// The exit code with which the container exited.
	ExitCode int

	// Whether the container encountered an OOM.
	OOMKilled bool
}


<|start_filename|>lib/sysinfo/sysinfo_linux.go<|end_filename|>
// +build linux

package sysinfo

import (
	"bufio"
	"bytes"
	"io"
	"io/ioutil"
	"strconv"
	"strings"
)

var (
	cpuInfoProcLinuxFile = "/proc/cpuinfo"
	memInfoProcLinuxFile = "/proc/meminfo"
	etcOsRelease         = "/etc/os-release"
)

func getMemInfo() (*MemInfo, error) {
	mem := &MemInfo{}
	// read in whole meminfo file with cpu usage information ;"/proc/meminfo"
	contents, err := ioutil.ReadFile(memInfoProcLinuxFile)
	if err != nil {
		return nil, err
	}

	reader := bufio.NewReader(bytes.NewBuffer(contents))
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}

		fields := strings.Fields(string(line))
		fieldName := fields[0]

		if len(fields) == 3 {
			val, err := strconv.ParseUint(fields[1], 10, 64)
			if err != nil {
				return nil, err
			}
			switch fieldName {
			case "MemTotal:":
				mem.MemTotal = val
			case "MemFree:":
				mem.MemFree = val
			case "MemAvailable:":
				mem.MemAvailable = val
			case "Buffers:":
				mem.Buffers = val
			case "Cached:":
				mem.Cached = val
			case "SwapCached:":
				mem.SwapCached = val
			case "Active:":
				mem.Active = val
			case "Inactive:":
				mem.Inactive = val
			case "Active(anon):":
				mem.AnonActive = val
			case "Inactive(anon):":
				mem.AnonInactive = val
			case "Active(file):":
				mem.FileActive = val
			case "Inactive(file):":
				mem.FileInactive = val
			case "Unevictable:":
				mem.Unevictable = val
			case "Mlocked:":
				mem.Mlocked = val
			case "SwapTotal:":
				mem.SwapTotal = val
			case "SwapFree:":
				mem.SwapFree = val
			case "Dirty:":
				mem.Dirty = val
			case "Writeback:":
				mem.Writeback = val
			case "AnonPages:":
				mem.AnonPages = val
			case "Mapped:":
				mem.Mapped = val
			case "Shmem:":
				mem.Shmem = val
			case "Slab:":
				mem.Slab = val
			case "SReclaimable:":
				mem.SReclaimable = val
			case "SUnreclaim:":
				mem.SUnreclaim = val
			case "KernelStack:":
				mem.KernelStack = val
			case "PageTables:":
				mem.PageTables = val
			case "NFS_Unstable:":
				mem.NFS_Unstable = val
			case "Bounce:":
				mem.Bounce = val
			case "WritebackTmp:":
				mem.WritebackTmp = val
			case "CommitLimit:":
				mem.CommitLimit = val
			case "Committed_AS:":
				mem.Committed_AS = val
			case "VmallocTotal:":
				mem.VmallocTotal = val
			case "VmallocUsed:":
				mem.VmallocUsed = val
			case "VmallocChunk:":
				mem.VmallocChunk = val
			case "HardwareCorrupted:":
				mem.HardwareCorrupted = val
			case "AnonHugePages:":
				mem.AnonHugePages = val
			case "Hugepagesize:":
				mem.Hugepagesize = val
			case "DirectMap4k:":
				mem.DirectMap4k = val
			case "DirectMap2M:":
				mem.DirectMap2M = val
			case "DirectMap1G:":
				mem.DirectMap1G = val
			}
		}
	}
	return mem, nil
}

func getCpuInfo() (*CpuInfo, error) {
	return nil, nil
}

func getOSInfo() (*OSInfo, error) {
	osinfo := &OSInfo{}
	contents, err := ioutil.ReadFile(etcOsRelease)
	if err != nil {
		return nil, err
	}
	reader := bufio.NewReader(bytes.NewBuffer(contents))
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		if strings.Contains(string(line), "NAME") {
			osinfo.Name = string(line[bytes.IndexByte(line, '"')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "VERSION") {
			osinfo.Version = string(line[bytes.IndexByte(line, '"')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "PRETTY_NAME") {
			osinfo.PrettyName = string(line[bytes.IndexByte(line, '"')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "ID") {
			osinfo.Id = string(line[bytes.IndexByte(line, '=')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "ID_LIKE") {
			osinfo.IdLike = string(line[bytes.IndexByte(line, '=')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "VERSION_ID") {
			osinfo.VersionId = string(line[bytes.IndexByte(line, '"')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "HOME_URL") {
			osinfo.HomeURL = string(line[bytes.IndexByte(line, '"')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "SUPPORT_URL") {
			osinfo.SupportURL = string(line[bytes.IndexByte(line, '"')+1 : len(line)-1])
		}
		if strings.Contains(string(line), "BUG_REPORT_URL") {
			osinfo.BugURL = string(line[bytes.IndexByte(line, '"')+1 : len(line)-1])
		}
	}
	return osinfo, nil
}


<|start_filename|>utils/sync.go<|end_filename|>
package utils

import (
	"fmt"
	"sync"
	"time"
)

type Initializer struct {
	once sync.Once
	job  func()
}

func NewInitializer(fn func()) *Initializer {
	return &Initializer{
		job: fn,
	}
}

func (i *Initializer) Do() {
	i.once.Do(i.job)
}

type WaitGroupWithFail struct {
	sync.WaitGroup
	sync.Mutex

	errs []error
}

func (wg *WaitGroupWithFail) Wait() error {
	wg.WaitGroup.Wait()
	if len(wg.errs) > 0 {
		return fmt.Errorf("Errors: %v", wg.errs)
	}
	return nil
}

func (wg *WaitGroupWithFail) Fail(err error) {
	wg.Mutex.Lock()
	if wg.errs == nil {
		wg.errs = []error{}
	}
	wg.errs = append(wg.errs, err)
	wg.Mutex.Unlock()
	wg.WaitGroup.Done()
}

type FutureSet struct {
	waitList   map[string]bool
	resultChan chan struct {
		id  string
		err error
	}
	sync.Mutex
}

var (
	ErrTimeout = fmt.Errorf("timeout")
	BrokenChan = fmt.Errorf("Unexpected broken chan")
)

func NewFutureSet() *FutureSet {
	return &FutureSet{
		waitList: make(map[string]bool),
		resultChan: make(chan struct {
			id  string
			err error
		}, 1),
	}
}

func (fs *FutureSet) IsFinished() bool {
	return len(fs.waitList) == 0
}

func (fs *FutureSet) Add(id string, op func() error) {
	for fs.waitList[id] {
		id = id + RandStr(4, "alphanum")
	}

	fs.Lock()
	fs.waitList[id] = true
	fs.Unlock()

	go func() {
		err := op()
		fs.resultChan <- struct {
			id  string
			err error
		}{id, err}
	}()
}

func (fs *FutureSet) Wait(timeout time.Duration) error {
	var toc <-chan time.Time
	if int64(timeout) < 0 {
		toc = make(chan time.Time)
	} else {
		toc = time.After(timeout)
	}

	errs := map[string]error{}
	for len(fs.waitList) > 0 {
		select {
		case r, ok := <-fs.resultChan:
			if !ok {
				return BrokenChan
			}
			fs.Lock()
			delete(fs.waitList, r.id)
			fs.Unlock()
			if r.err != nil {
				errs[r.id] = r.err
			}
		case <-toc:
			return ErrTimeout
		}
	}
	if len(errs) > 0 {
		return fmt.Errorf("finished with errors: %v", errs)
	}

	return nil
}


<|start_filename|>daemon/servicediscovery.go<|end_filename|>
package daemon

import (
	"fmt"

	apitypes "github.com/hyperhq/hyperd/types"
)

func (daemon *Daemon) AddService(podId string, srvs []*apitypes.UserService) error {
	p, ok := daemon.PodList.Get(podId)
	if !ok {
		return fmt.Errorf("The pod(%s) can not be found, please create it first", podId)
	}

	return p.AddService(srvs)
}

func (daemon *Daemon) UpdateService(podId string, srvs []*apitypes.UserService) error {
	p, ok := daemon.PodList.Get(podId)
	if !ok {
		return fmt.Errorf("The pod(%s) can not be found, please create it first", podId)
	}

	return p.UpdateService(srvs)
}

func (daemon *Daemon) DeleteService(podId string, srvs []*apitypes.UserService) error {
	p, ok := daemon.PodList.Get(podId)
	if !ok {
		return fmt.Errorf("The pod(%s) can not be found, please create it first", podId)
	}

	return p.DeleteService(srvs)
}

func (daemon *Daemon) GetServices(podId string) ([]*apitypes.UserService, error) {
	p, ok := daemon.PodList.Get(podId)
	if !ok {
		return nil, fmt.Errorf("The pod(%s) can not be found, please create it first", podId)
	}

	return p.GetServices()
}


<|start_filename|>client/api/rpc/rpclient_demo.go<|end_filename|>
package main

import (
	"fmt"
	"os"

	"github.com/hyperhq/hyperd/types"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

const (
	server = "127.0.0.1:22318"
)

func main() {
	conn, err := grpc.Dial(server, grpc.WithInsecure())
	if err != nil {
		fmt.Printf("Connect server error: %v", err)
		os.Exit(1)
	}
	defer conn.Close()

	client := types.NewPublicAPIClient(conn)
	request := types.PodInfoRequest{
		PodID: "pod-zpIOTSAjmM",
	}
	response, err := client.PodInfo(context.Background(), &request)
	if err != nil {
		fmt.Printf("Get PodInfo error: %v", err)
		os.Exit(1)
	}

	fmt.Printf("Got response: %v", response)
}


<|start_filename|>daemon/tty.go<|end_filename|>
package daemon

import (
	"fmt"
	"github.com/golang/glog"
)

func (daemon *Daemon) TtyResize(containerId, execId string, h, w int) error {
	p, id, ok := daemon.PodList.GetByContainerIdOrName(containerId)
	if !ok {
		err := fmt.Errorf("cannot find container %s", containerId)
		glog.Error(err)
		return err
	}

	err := p.TtyResize(id, execId, h, w)
	if err != nil {
		return err
	}

	glog.V(1).Infof("Success to resize the tty!")
	return nil
}


<|start_filename|>daemon/daemondb/daemondb.go<|end_filename|>
package daemondb

import (
	"strings"

	"github.com/golang/glog"
	"github.com/syndtr/goleveldb/leveldb"
	"github.com/syndtr/goleveldb/leveldb/util"
)

type DaemonDB struct {
	db *leveldb.DB
}

type KVPair struct {
	K []byte
	V []byte
}

func NewDaemonDB(db_file string) (*DaemonDB, error) {
	db, err := leveldb.OpenFile(db_file, nil)
	if err != nil {
		glog.Errorf("open leveldb file failed, %s", err.Error())
		return nil, err
	}
	return &DaemonDB{db: db}, nil
}

// Composition Process
func (d *DaemonDB) LagecyDeleteVMByPod(id string) error {
	v, err := d.LagecyGetP2V(id)
	if err != nil {
		return err
	}
	d.LagecyDeleteP2V(id)
	if err := d.LagecyDeleteVM(v); err != nil {
		return err
	}
	return nil
}

// Pods podId and args
func (d *DaemonDB) LagecyGetPod(id string) ([]byte, error) {
	return d.Get(keyPod(id))
}

func (d *DaemonDB) LagecyUpdatePod(id string, data []byte) error {
	return d.Update(keyPod(id), data)
}

func (d *DaemonDB) LagecyDeletePod(id string) error {
	return d.db.Delete(keyPod(id), nil)
}

func (d *DaemonDB) LagecyListPod() ([][]byte, error) {
	return d.PrefixListKey(prefixPod(), func(key []byte) bool {
		return !strings.HasPrefix(string(key), POD_CONTAINER_PREFIX)
	})
}

func (d *DaemonDB) LagecyGetAllPods() chan *KVPair {
	return d.PrefixList2Chan(prefixPod(), func(key []byte) bool {
		return !strings.HasPrefix(string(key), POD_CONTAINER_PREFIX)
	})
}

// Pod Volumes
func (d *DaemonDB) UpdatePodVolume(podId, volname string, data []byte) error {
	return d.Update(keyVolume(podId, volname), data)
}

func (d *DaemonDB) GetPodVolume(podId, volname string) ([]byte, error) {
	return d.db.Get(keyVolume(podId, volname), nil)
}

func (d *DaemonDB) ListPodVolumes(podId string) ([][]byte, error) {
	return d.PrefixList(prefixVolume(podId), nil)
}

func (d *DaemonDB) DeletePodVolume(podId, volName string) error {
	return d.db.Delete(keyVolume(podId, volName), nil)
}

func (d *DaemonDB) DeletePodVolumes(podId string) error {
	return d.PrefixDelete(prefixVolume(podId))
}

// POD to Containers (string to string list)
func (d *DaemonDB) LagecyGetP2C(id string) ([]string, error) {
	glog.V(3).Info("try get container list for pod ", id)
	cl, err := d.Get(keyP2C(id))
	if err != nil || len(cl) == 0 {
		return []string{}, err
	}
	return strings.Split(string(cl), ":"), nil
}

func (d *DaemonDB) LagecyUpdateP2C(id string, containers []string) error {
	glog.V(3).Infof("try set container list for pod %s: %v", id, containers)
	return d.Update(keyP2C(id), []byte(strings.Join(containers, ":")))
}

func (d *DaemonDB) LagecyDeleteP2C(id string) error {
	return d.db.Delete(keyP2C(id), nil)
}

// POD to VM (string to string)
func (d *DaemonDB) LagecyGetP2V(id string) (string, error) {
	return d.GetString(keyP2V(id))
}

func (d *DaemonDB) LagecyUpdateP2V(id, vm string) error {
	return d.Update(keyP2V(id), []byte(vm))
}

func (d *DaemonDB) LagecyDeleteP2V(id string) error {
	return d.db.Delete(keyP2V(id), nil)
}

func (d *DaemonDB) LagecyDeleteAllP2V() error {
	return d.PrefixDelete(prefixP2V())
}

// VM DATA (string to data)
func (d *DaemonDB) LagecyGetVM(id string) ([]byte, error) {
	data, err := d.db.Get(keyVMData(id), nil)
	if err != nil {
		return []byte(""), err
	}
	return data, nil
}

func (d *DaemonDB) LagecyUpdateVM(id string, data []byte) error {
	return d.Update(keyVMData(id), data)
}

func (d *DaemonDB) LagecyDeleteVM(id string) error {
	return d.db.Delete(keyVMData(id), nil)
}

// Low level util
func (d *DaemonDB) Close() error {
	return d.db.Close()
}

func (d *DaemonDB) Delete(key []byte) error {
	return d.db.Delete(key, nil)
}

func (d *DaemonDB) Get(key []byte) ([]byte, error) {
	data, err := d.db.Get(key, nil)
	if err != nil {
		return []byte(""), err
	}
	return data, nil
}

func (d *DaemonDB) GetString(key []byte) (string, error) {
	data, err := d.db.Get(key, nil)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

func (d *DaemonDB) Update(key, data []byte) error {
	_, err := d.db.Get(key, nil)
	if err == nil {
		err = d.db.Delete(key, nil)
		if err != nil {
			return err
		}
	} else if err != leveldb.ErrNotFound {
		return err
	}

	err = d.db.Put(key, data, nil)
	if err != nil {
		return err
	}

	return nil
}

func (d *DaemonDB) PrefixDelete(prefix []byte) error {
	iter := d.db.NewIterator(util.BytesPrefix(prefix), nil)
	for iter.Next() {
		key := iter.Key()
		d.db.Delete(key, nil)
	}
	iter.Release()
	err := iter.Error()
	return err
}

type KeyFilter func([]byte) bool

func (d *DaemonDB) PrefixList(prefix []byte, keyFilter KeyFilter) ([][]byte, error) {
	var results [][]byte
	iter := d.db.NewIterator(util.BytesPrefix(prefix), nil)
	for iter.Next() {
		if keyFilter == nil || keyFilter(iter.Key()) {
			results = append(results, append([]byte{}, iter.Value()...))
		}
	}
	iter.Release()
	err := iter.Error()
	return results, err
}

func (d *DaemonDB) PrefixListKey(prefix []byte, keyFilter KeyFilter) ([][]byte, error) {
	var results [][]byte
	iter := d.db.NewIterator(util.BytesPrefix(prefix), nil)
	for iter.Next() {
		if keyFilter == nil || keyFilter(iter.Key()) {
			results = append(results, append([]byte{}, iter.Key()...))
		}
	}
	iter.Release()
	err := iter.Error()
	return results, err
}

func (d *DaemonDB) PrefixList2Chan(prefix []byte, keyFilter KeyFilter) chan *KVPair {
	ch := make(chan *KVPair, 128)
	if ch == nil {
		return ch
	}
	go func() {
		iter := d.db.NewIterator(util.BytesPrefix(prefix), nil)
		for iter.Next() {
			glog.V(3).Infof("got key from leveldb %s", string(iter.Key()))
			if keyFilter == nil || keyFilter(iter.Key()) {
				k := make([]byte, len(iter.Key()))
				v := make([]byte, len(iter.Value()))
				copy(k, iter.Key())
				copy(v, iter.Value())
				ch <- &KVPair{k, v}
			}
		}
		iter.Release()
		if err := iter.Error(); err != nil {
			ch <- nil
			glog.Error("Error occurs while iterate db with %v", prefix)
		}
		close(ch)
	}()

	return ch
}


<|start_filename|>client/api/pull.go<|end_filename|>
package api

import (
	"io"
	"net/http"
	"strings"

	"github.com/docker/engine-api/types"
	"net/url"
)

func (cli *Client) Pull(image string, authConfig types.AuthConfig) (io.ReadCloser, string, int, error) {

	v := url.Values{}
	v.Set("imageName", image)
	body, ctype, statusCode, err := cli.authRequest("POST", "/image/create?"+v.Encode(), nil, nil, authConfig)
	if err != nil {
		// Since errors in a stream appear after status 200 has been written,
		// we may need to change the status code.
		if strings.Contains(err.Error(), "Authentication is required") ||
			strings.Contains(err.Error(), "Status 401") ||
			strings.Contains(err.Error(), "status code 401") {
			statusCode = http.StatusUnauthorized
		}
	}
	return body, ctype, statusCode, err
}


<|start_filename|>client/start.go<|end_filename|>
package client

import (
	"fmt"
	"strings"

	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdStart(args ...string) error {
	var opts struct {
		Container bool `short:"c" long:"container" default-mask:"-" description:"start container"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "start [OPTIONS] POD_ID|CONTAINER_ID\n\nLaunch a created pod or container"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("\"start\" requires a minimum of 1 argument, please provide POD ID.\n")
	}
	var (
		id = args[0]
	)

	if !opts.Container {
		err = cli.client.StartPod(id)
		if err != nil {
			return err
		}
		fmt.Fprintf(cli.out, "Successfully started the Pod(%s)\n", id)
	} else {
		err = cli.client.StartContainer(id)
		if err != nil {
			return err
		}
		fmt.Fprintf(cli.out, "Successfully started container %s\n", id)
	}
	return nil
}


<|start_filename|>client/api/create.go<|end_filename|>
package api

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/hyperhq/hyperd/engine"
	"github.com/hyperhq/runv/hypervisor/types"
)

func (cli *Client) CreatePod(spec interface{}) (string, int, error) {
	body, statusCode, err := readBody(cli.call("POST", "/pod/create", spec, nil))
	if err != nil {
		return "", statusCode, err
	}
	if statusCode != http.StatusCreated && statusCode != http.StatusOK {
		return "", statusCode, err
	}

	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return "", statusCode, err
	}

	if _, err := out.Write(body); err != nil {
		return "", statusCode, fmt.Errorf("Error reading remote info: %s", err)
	}
	out.Close()
	errCode := remoteInfo.GetInt("Code")
	if errCode == types.E_OK {
		//fmt.Println("VM is successful to start!")
	} else {
		// case types.E_CONTEXT_INIT_FAIL:
		// case types.E_DEVICE_FAIL:
		// case types.E_QMP_INIT_FAIL:
		// case types.E_QMP_COMMAND_FAIL:
		if errCode != types.E_BAD_REQUEST &&
			errCode != types.E_FAILED {
			return "", statusCode, fmt.Errorf("Error code is %d", errCode)
		} else {
			return "", statusCode, fmt.Errorf("Cause is %s", remoteInfo.Get("Cause"))
		}
	}
	return remoteInfo.Get("ID"), statusCode, nil
}

func (cli *Client) CreateContainer(podID string, spec interface{}) (string, int, error) {
	v := url.Values{}
	v.Set("podId", podID)
	body, statusCode, err := readBody(cli.call("POST", "/container/create?"+v.Encode(), spec, nil))
	if err != nil {
		return "", statusCode, err
	}
	if statusCode != http.StatusCreated && statusCode != http.StatusOK {
		return "", statusCode, err
	}

	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return "", statusCode, err
	}

	if _, err := out.Write(body); err != nil {
		return "", statusCode, fmt.Errorf("Error reading remote info: %s", err)
	}
	out.Close()

	return remoteInfo.Get("ID"), statusCode, nil
}


<|start_filename|>storage/aufs/aufs_test.go<|end_filename|>
package aufs

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"strings"
	"testing"
)

var (
	aufsSupport   = false
	temp          = os.TempDir()
	aufsTempDir   = path.Join(temp, "aufs-test")
	sharedTempDir = path.Join(aufsTempDir, "shared")
	layersTempDir = path.Join(aufsTempDir, "layers")
	diffTempDir   = path.Join(aufsTempDir, "diff")
	testFile3     = fmt.Sprintf("%s/3", layersTempDir)
	testFile2     = fmt.Sprintf("%s/2", layersTempDir)
	testFile1     = fmt.Sprintf("%s/1", layersTempDir)
)

func init() {
	aufsSupport = supportAufs()
}

func InitDir() error {
	if err := os.MkdirAll(aufsTempDir, 0755); err != nil {
		return err
	}

	if err := os.MkdirAll(layersTempDir, 0755); err != nil {
		return err
	}

	if err := os.MkdirAll(diffTempDir, 0755); err != nil {
		return err
	}
	return nil
}

func Cleanup() error {
	if err := os.RemoveAll(aufsTempDir); err != nil {
		return err
	}

	return nil
}

func InitFile() error {
	file1Data := ""
	file2Data := "1\n"
	file3Data := "1\n2\n"

	if err := ioutil.WriteFile(testFile1, []byte(file1Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(testFile2, []byte(file2Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(testFile3, []byte(file3Data), 0755); err != nil {
		return err
	}

	return nil
}

func InitDiffFile() error {
	file1Data := "3"
	file2Data := "2"
	file3Data := "1"

	if err := os.MkdirAll(path.Join(diffTempDir, "1"), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(diffTempDir, "2"), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(diffTempDir, "3"), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "1")+"/1", []byte(file1Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "2")+"/2", []byte(file2Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "3")+"/3", []byte(file3Data), 0755); err != nil {
		return err
	}

	return nil
}

func supportAufs() bool {
	// We can try to modprobe aufs first before looking at
	// proc/filesystems for when aufs is supported
	if os.Getgid() == 0 {
		exec.Command("/bin/sh", "-c", "modprobe", "aufs").Run()
	}

	f, err := os.Open("/proc/filesystems")
	if err != nil {
		return false
	}
	defer f.Close()

	s := bufio.NewScanner(f)
	for s.Scan() {
		if strings.Contains(s.Text(), "aufs") {
			return true
		}
	}
	return false
}

func TestTempDirCreate(t *testing.T) {
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(aufsTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}

}

func TestGetParentIds(t *testing.T) {
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}

	parentIds, err := getParentIds(path.Join(layersTempDir, "3"))
	if err != nil {
		t.Fatalf("%s\n", err.Error())
	}
	if !(parentIds[0] == "1" && parentIds[1] == "2") {
		t.Fatalf("Error to find the parent IDs\n")
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}
}

func TestGetParentDiffPaths(t *testing.T) {
	if aufsSupport == false {
		return
	}
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}

	parentIdPaths, err := getParentDiffPaths("3", aufsTempDir)
	if err != nil {
		t.Fatalf("%s\n", err.Error())
	}
	if !(strings.Contains(parentIdPaths[0], fmt.Sprintf("%s/1", diffTempDir))) {
		t.Fatalf("Error to find the parent ID path\n")
	}
	if !(strings.Contains(parentIdPaths[1], fmt.Sprintf("%s/2", diffTempDir))) {
		t.Fatalf("Error to find the parent ID path\n")
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}
}

func TestAufsMount(t *testing.T) {
	if os.Getgid() != 0 {
		t.Errorf("This test case should be run in root group")
		return
	}
	t.Logf("aufs temp dir is %s", aufsTempDir)
	if aufsSupport == false {
		return
	}
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(aufsTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("layer files create failed")
		} else {
			t.Fatalf("layer files create failed, %s", err.Error())
		}
	}
	if err := InitDiffFile(); err != nil {
		t.Fatalf("Error during creating the diff data file: %s\n", err.Error())
	}
	if _, err := os.Stat(path.Join(diffTempDir, "3")); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("diff files create failed")
		} else {
			t.Fatalf("diff files create failed, %s", err.Error())
		}
	}
	if err := os.MkdirAll(sharedTempDir, 0755); err != nil {
		t.Fatalf("Shared dir create failed, %s", err.Error())
	}
	if _, err := os.Stat(sharedTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("shared dir create failed")
		} else {
			t.Fatalf("shared dir create failed, %s", err.Error())
		}
	}

	diffs, err := getParentDiffPaths("3", aufsTempDir)
	if err != nil {
		t.Fatalf("Error during getting parent diff paths: %s\n", err.Error())
	}

	t.Log("Mount the parent read-only images and container")
	if err := aufsMount(diffs, path.Join(diffTempDir, "3"), sharedTempDir, ""); err != nil {
		t.Fatalf("Error during mounting paths: %s\n", err.Error())
	}

	// verify the mount result
	t.Log("Verify the mount result")
	if _, err := os.Stat(path.Join(sharedTempDir, "1")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (1) does not mount successfully!")
	}
	if _, err := os.Stat(path.Join(sharedTempDir, "2")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (2) does not mount successfully!")
	}
	if _, err := os.Stat(path.Join(sharedTempDir, "3")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (3) does not mount successfully!")
	}

	if err := os.MkdirAll(path.Join(sharedTempDir, "haha"), 0755); err != nil {
		t.Fatalf("Error on mkdir in mounted target dir!")
	}
	if _, err := os.Stat(path.Join(diffTempDir, "3") + "/haha"); err != nil && os.IsNotExist(err) {
		t.Fatalf("The dir in mounted target dir does not exist!")
	}

	// Unmount the target dir and then remove it
	Unmount(sharedTempDir)
	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}
}

func TestMountContainerToShareDir(t *testing.T) {
	if os.Getgid() != 0 {
		t.Errorf("This test case should be run in root group")
		return
	}
	if aufsSupport == false {
		return
	}
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(aufsTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("layer files create failed")
		} else {
			t.Fatalf("layer files create failed, %s", err.Error())
		}
	}
	if err := InitDiffFile(); err != nil {
		t.Fatalf("Error during creating the diff data file: %s\n", err.Error())
	}
	if _, err := os.Stat(path.Join(diffTempDir, "3")); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("diff files create failed")
		} else {
			t.Fatalf("diff files create failed, %s", err.Error())
		}
	}
	if err := os.MkdirAll(sharedTempDir, 0755); err != nil {
		t.Fatalf("Shared dir create failed, %s", err.Error())
	}
	if _, err := os.Stat(sharedTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("shared dir create failed")
		} else {
			t.Fatalf("shared dir create failed, %s", err.Error())
		}
	}

	t.Log("Mount the parent read-only images and container")
	mountPoint, err := MountContainerToSharedDir("3", aufsTempDir, sharedTempDir, "")
	if err != nil {
		t.Fatalf("Error during mounting paths: %s\n", err.Error())
	}
	t.Logf(mountPoint)

	// verify the mount result
	t.Log("Verify the mount result")
	if _, err := os.Stat(path.Join(mountPoint, "1")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (1) does not mount successfully!")
	}
	if _, err := os.Stat(path.Join(mountPoint, "2")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (2) does not mount successfully!")
	}
	if _, err := os.Stat(path.Join(mountPoint, "3")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The file (3) does not mount successfully!")
	}

	if err := os.MkdirAll(path.Join(mountPoint, "haha"), 0755); err != nil {
		t.Fatalf("Error on mkdir in mounted target dir!")
	}
	if _, err := os.Stat(path.Join(mountPoint, "haha")); err != nil && os.IsNotExist(err) {
		t.Fatalf("The dir in mounted target dir does not exist!")
	}

	// Unmount the target dir and then remove it
	if err := Unmount(mountPoint); err != nil {
		t.Fatalf("Unmount error: %s", err.Error())
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}
}

func TestAttachFiles(t *testing.T) {
	if os.Getgid() != 0 {
		t.Errorf("This test case should be run in root group")
		return
	}
	if aufsSupport == false {
		return
	}
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(aufsTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("layer files create failed")
		} else {
			t.Fatalf("layer files create failed, %s", err.Error())
		}
	}
	if err := InitDiffFile(); err != nil {
		t.Fatalf("Error during creating the diff data file: %s\n", err.Error())
	}
	if _, err := os.Stat(path.Join(diffTempDir, "3")); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("diff files create failed")
		} else {
			t.Fatalf("diff files create failed, %s", err.Error())
		}
	}
	if err := os.MkdirAll(sharedTempDir, 0755); err != nil {
		t.Fatalf("Shared dir create failed, %s", err.Error())
	}
	if _, err := os.Stat(sharedTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("shared dir create failed")
		} else {
			t.Fatalf("shared dir create failed, %s", err.Error())
		}
	}

	t.Log("MountContainerToSharedDir do")
	mountPoint, err := MountContainerToSharedDir("3", aufsTempDir, sharedTempDir, "")
	if err != nil {
		t.Fatalf("Error during mounting paths: %s\n", err.Error())
	}

	t.Log("AttachFiles do")
	err = AttachFiles("3", "/etc/os-release", "/", sharedTempDir, "0755", "0", "0")
	if err != nil {
		t.Fatalf(err.Error())
	}

	t.Log("Verify the AttachFiles function execution result")
	if _, err := os.Stat(mountPoint + "/os-release"); err != nil && os.IsNotExist(err) {
		t.Fatalf("The dir in mounted target dir does not exist!")
	}

	// Unmount the target dir and then remove it
	if err := Unmount(mountPoint); err != nil {
		t.Fatalf("Unmount error: %s", err.Error())
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}
}


<|start_filename|>mac_installer/resources/conclusion.html<|end_filename|>
<html>

<head>
    <style type="text/css">
        body {
            font-family: Helvetica;
        }
        pre {
            font-family: Monaco;
            font-size: 10;
            color: 7f7f7f;
            width: 700px;
        }
    </style>
</head>

<body>

    <h1>Hyper for Mac installed</h1>

    <p>hyper shift with a daemon and a command line tool, to enable or disable the daemon, you can use</p>
    <pre>
sudo launchctl load /Library/LaunchDaemons/sh.hyper.hyper.plist
</pre>
    or

    <pre>
sudo launchctl unload /Library/LaunchDaemons/sh.hyper.hyper.plist
</pre>

<br/>
	<p>and play with the command line tool</p>
    <pre>
hyper help
</pre>

<br/>
	You can find more detailed information on our <a href="https://docs.hyper.sh">doc site</a>

</body>

</html>


<|start_filename|>storage/devicemapper/dm_nonsupport.go<|end_filename|>
// +build !linux

package devicemapper

import (
	"fmt"
	"io"
	"os/exec"
	"strings"
)

// For device mapper, we do not need to mount the container to sharedDir.
// All of we need to provide the block device name of container.
func MountContainerToSharedDir(containerId, sharedDir, devPrefix string) (string, error) {
	return "", nil
}

func InjectFile(src io.Reader, containerId, devPrefix, target, rootPath string, perm, uid, gid int) error {
	return fmt.Errorf("Unsupported, inject file to %s is not supported in current arch", target)
}

func CreateNewDevice(containerId, devPrefix, rootPath string) error {
	return nil
}

func AttachFiles(containerId, devPrefix, fromFile, toDir, rootPath, perm, uid, gid string) error {
	return nil
}

func ProbeFsType(device string) (string, error) {
	// The daemon will only be run on Linux platform, so 'file -s' command
	// will be used to test the type of filesystem which the device located.
	cmd := fmt.Sprintf("file -sL %s", device)
	command := exec.Command("/bin/sh", "-c", cmd)
	fileCmdOutput, err := command.CombinedOutput()
	if err != nil {
		return "", nil
	}

	if strings.Contains(strings.ToLower(string(fileCmdOutput)), "ext") {
		return "ext4", nil
	}
	if strings.Contains(strings.ToLower(string(fileCmdOutput)), "xfs") {
		return "xfs", nil
	}

	return "", fmt.Errorf("Unknown filesystem type on %s", device)
}

type DeviceMapper struct {
	Datafile         string
	Metadatafile     string
	DataLoopFile     string
	MetadataLoopFile string
	Size             int
	PoolName         string
}

func CreatePool(dm *DeviceMapper) error {
	return nil
}

func CreateVolume(poolName, volName, dev_id string, size int, restore bool) error {
	return nil
}

func DeleteVolume(dm *DeviceMapper, dev_id int) error {
	return nil
}

func DMCleanup(dm *DeviceMapper) error {
	return nil
}


<|start_filename|>client/version.go<|end_filename|>
package client

import (
	"fmt"
	"os"

	"github.com/hyperhq/hyperd/utils"
)

func (cli *HyperClient) HyperCmdVersion(args ...string) error {
	fmt.Fprintf(cli.out, "The %s version is %s\n", os.Args[0], utils.VERSION)
	return nil
}


<|start_filename|>client/api/save.go<|end_filename|>
package api

import (
	"encoding/json"
	"io"
	"net/url"
)

func (cli *Client) Save(imageIDs []string, format string, refs map[string]string) (io.ReadCloser, error) {
	refsJSON, err := json.Marshal(refs)
	if err != nil {
		return nil, err
	}

	v := url.Values{
		"names":  imageIDs,
		"format": []string{format},
		"refs":   []string{string(refsJSON)},
	}

	resp, _, err := cli.call("GET", "/images/save?"+v.Encode(), nil, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}


<|start_filename|>storage/volumes.go<|end_filename|>
package storage

import (
	"os"
	"path"
	"path/filepath"
	"runtime"
	"syscall"

	"github.com/golang/glog"
	"github.com/hyperhq/hyperd/utils"
)

func CreateVFSVolume(podId, shortName string) (string, error) {
	volName := path.Join("/var/tmp/hyper", podId, shortName)
	if _, err := os.Stat(volName); err != nil && os.IsNotExist(err) {
		if err := os.MkdirAll(volName, os.FileMode(0777)); err != nil {
			return "", err
		}
	}
	return volName, nil
}

func MountVFSVolume(src, sharedDir string) (string, error) {
	var flags uintptr = utils.MS_BIND

	mountSharedDir := utils.RandStr(10, "alpha")
	targetDir := path.Join(sharedDir, mountSharedDir)
	glog.V(1).Infof("trying to bind dir %s to %s", src, targetDir)

	stat, err := os.Stat(src)
	if err != nil {
		glog.Error("Cannot stat volume Source ", err.Error())
		return "", err
	}

	if runtime.GOOS == "linux" {
		base := filepath.Dir(targetDir)
		if err := os.MkdirAll(base, 0755); err != nil && !os.IsExist(err) {
			glog.Errorf("error to create dir %s for volume %s", base, src)
			return "", err
		}

		if stat.IsDir() {
			if err := os.MkdirAll(targetDir, 0755); err != nil && !os.IsExist(err) {
				glog.Errorf("error to create dir %s for volume %s", targetDir, src)
				return "", err
			}
		} else if f, err := os.Create(targetDir); err != nil && !os.IsExist(err) {
			glog.Errorf("error to create file %s for volume %s", targetDir, src)
			return "", err
		} else if err == nil {
			f.Close()
		}
	}

	if err := utils.Mount(src, targetDir, "none", flags, "--bind"); err != nil {
		glog.Errorf("bind dir %s failed: %s", src, err.Error())
		return "", err
	}

	return mountSharedDir, nil
}

func UmountVFSVolume(vol, sharedDir string) error {
	mount := path.Join(sharedDir, vol)

	err := syscall.Unmount(mount, 0)
	if err != nil {
		glog.Warningf("Cannot umount volume %s: %s", mount, err.Error())
		err = syscall.Unmount(mount, syscall.MNT_DETACH)
		if err != nil {
			glog.Warningf("Cannot lazy umount volume %s: %s", mount, err.Error())
			return err
		}
	}

	os.Remove(mount)
	return nil
}


<|start_filename|>vendor/github.com/docker/libnetwork/iptables/iptables.go<|end_filename|>
package iptables

import (
	"errors"
	"fmt"
	"net"
	"os/exec"
	"strconv"
	"strings"
	"sync"

	"github.com/Sirupsen/logrus"
)

// Action signifies the iptable action.
type Action string

// Table refers to Nat, Filter or Mangle.
type Table string

const (
	// Append appends the rule at the end of the chain.
	Append Action = "-A"
	// Delete deletes the rule from the chain.
	Delete Action = "-D"
	// Insert inserts the rule at the top of the chain.
	Insert Action = "-I"
	// Nat table is used for nat translation rules.
	Nat Table = "nat"
	// Filter table is used for filter rules.
	Filter Table = "filter"
	// Mangle table is used for mangling the packet.
	Mangle Table = "mangle"
)

var (
	iptablesPath  string
	supportsXlock = false
	// used to lock iptables commands if xtables lock is not supported
	bestEffortLock sync.Mutex
	// ErrIptablesNotFound is returned when the rule is not found.
	ErrIptablesNotFound = errors.New("Iptables not found")
)

// ChainInfo defines the iptables chain.
type ChainInfo struct {
	Name        string
	Table       Table
	HairpinMode bool
}

// ChainError is returned to represent errors during ip table operation.
type ChainError struct {
	Chain  string
	Output []byte
}

func (e ChainError) Error() string {
	return fmt.Sprintf("Error iptables %s: %s", e.Chain, string(e.Output))
}

func initCheck() error {

	if iptablesPath == "" {
		path, err := exec.LookPath("iptables")
		if err != nil {
			return ErrIptablesNotFound
		}
		iptablesPath = path
		supportsXlock = exec.Command(iptablesPath, "--wait", "-L", "-n").Run() == nil
	}
	return nil
}

// NewChain adds a new chain to ip table.
func NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error) {
	c := &ChainInfo{
		Name:        name,
		Table:       table,
		HairpinMode: hairpinMode,
	}
	if string(c.Table) == "" {
		c.Table = Filter
	}

	// Add chain if it doesn't exist
	if _, err := Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil {
		if output, err := Raw("-t", string(c.Table), "-N", c.Name); err != nil {
			return nil, err
		} else if len(output) != 0 {
			return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output)
		}
	}
	return c, nil
}

// ProgramChain is used to add rules to a chain
func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error {
	if c.Name == "" {
		return fmt.Errorf("Could not program chain, missing chain name.")
	}

	switch c.Table {
	case Nat:
		preroute := []string{
			"-m", "addrtype",
			"--dst-type", "LOCAL",
			"-j", c.Name}
		if !Exists(Nat, "PREROUTING", preroute...) && enable {
			if err := c.Prerouting(Append, preroute...); err != nil {
				return fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err)
			}
		} else if Exists(Nat, "PREROUTING", preroute...) && !enable {
			if err := c.Prerouting(Delete, preroute...); err != nil {
				return fmt.Errorf("Failed to remove docker in PREROUTING chain: %s", err)
			}
		}
		output := []string{
			"-m", "addrtype",
			"--dst-type", "LOCAL",
			"-j", c.Name}
		if !hairpinMode {
			output = append(output, "!", "--dst", "127.0.0.0/8")
		}
		if !Exists(Nat, "OUTPUT", output...) && enable {
			if err := c.Output(Append, output...); err != nil {
				return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
			}
		} else if Exists(Nat, "OUTPUT", output...) && !enable {
			if err := c.Output(Delete, output...); err != nil {
				return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
			}
		}
	case Filter:
		if bridgeName == "" {
			return fmt.Errorf("Could not program chain %s/%s, missing bridge name.",
				c.Table, c.Name)
		}
		link := []string{
			"-o", bridgeName,
			"-j", c.Name}
		if !Exists(Filter, "FORWARD", link...) && enable {
			insert := append([]string{string(Insert), "FORWARD"}, link...)
			if output, err := Raw(insert...); err != nil {
				return err
			} else if len(output) != 0 {
				return fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output)
			}
		} else if Exists(Filter, "FORWARD", link...) && !enable {
			del := append([]string{string(Delete), "FORWARD"}, link...)
			if output, err := Raw(del...); err != nil {
				return err
			} else if len(output) != 0 {
				return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output)
			}

		}
	}
	return nil
}

// RemoveExistingChain removes existing chain from the table.
func RemoveExistingChain(name string, table Table) error {
	c := &ChainInfo{
		Name:  name,
		Table: table,
	}
	if string(c.Table) == "" {
		c.Table = Filter
	}
	return c.Remove()
}

// Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error {
	daddr := ip.String()
	if ip.IsUnspecified() {
		// iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
		// want "0.0.0.0/0". "0/0" is correctly interpreted as "any
		// value" by both iptables and ip6tables.
		daddr = "0/0"
	}
	args := []string{"-t", string(Nat), string(action), c.Name,
		"-p", proto,
		"-d", daddr,
		"--dport", strconv.Itoa(port),
		"-j", "DNAT",
		"--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))}
	if !c.HairpinMode {
		args = append(args, "!", "-i", bridgeName)
	}
	if output, err := Raw(args...); err != nil {
		return err
	} else if len(output) != 0 {
		return ChainError{Chain: "FORWARD", Output: output}
	}

	if output, err := Raw("-t", string(Filter), string(action), c.Name,
		"!", "-i", bridgeName,
		"-o", bridgeName,
		"-p", proto,
		"-d", destAddr,
		"--dport", strconv.Itoa(destPort),
		"-j", "ACCEPT"); err != nil {
		return err
	} else if len(output) != 0 {
		return ChainError{Chain: "FORWARD", Output: output}
	}

	if output, err := Raw("-t", string(Nat), string(action), "POSTROUTING",
		"-p", proto,
		"-s", destAddr,
		"-d", destAddr,
		"--dport", strconv.Itoa(destPort),
		"-j", "MASQUERADE"); err != nil {
		return err
	} else if len(output) != 0 {
		return ChainError{Chain: "FORWARD", Output: output}
	}

	return nil
}

// Link adds reciprocal ACCEPT rule for two supplied IP addresses.
// Traffic is allowed from ip1 to ip2 and vice-versa
func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error {
	if output, err := Raw("-t", string(Filter), string(action), c.Name,
		"-i", bridgeName, "-o", bridgeName,
		"-p", proto,
		"-s", ip1.String(),
		"-d", ip2.String(),
		"--dport", strconv.Itoa(port),
		"-j", "ACCEPT"); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables forward: %s", output)
	}
	if output, err := Raw("-t", string(Filter), string(action), c.Name,
		"-i", bridgeName, "-o", bridgeName,
		"-p", proto,
		"-s", ip2.String(),
		"-d", ip1.String(),
		"--sport", strconv.Itoa(port),
		"-j", "ACCEPT"); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables forward: %s", output)
	}
	return nil
}

// Prerouting adds linking rule to nat/PREROUTING chain.
func (c *ChainInfo) Prerouting(action Action, args ...string) error {
	a := []string{"-t", string(Nat), string(action), "PREROUTING"}
	if len(args) > 0 {
		a = append(a, args...)
	}
	if output, err := Raw(a...); err != nil {
		return err
	} else if len(output) != 0 {
		return ChainError{Chain: "PREROUTING", Output: output}
	}
	return nil
}

// Output adds linking rule to an OUTPUT chain.
func (c *ChainInfo) Output(action Action, args ...string) error {
	a := []string{"-t", string(c.Table), string(action), "OUTPUT"}
	if len(args) > 0 {
		a = append(a, args...)
	}
	if output, err := Raw(a...); err != nil {
		return err
	} else if len(output) != 0 {
		return ChainError{Chain: "OUTPUT", Output: output}
	}
	return nil
}

// Remove removes the chain.
func (c *ChainInfo) Remove() error {
	// Ignore errors - This could mean the chains were never set up
	if c.Table == Nat {
		c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
		c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name)
		c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6

		c.Prerouting(Delete)
		c.Output(Delete)
	}
	Raw("-t", string(c.Table), "-F", c.Name)
	Raw("-t", string(c.Table), "-X", c.Name)
	return nil
}

// Exists checks if a rule exists
func Exists(table Table, chain string, rule ...string) bool {
	if string(table) == "" {
		table = Filter
	}

	// iptables -C, --check option was added in v.1.4.11
	// http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt

	// try -C
	// if exit status is 0 then return true, the rule exists
	if _, err := Raw(append([]string{
		"-t", string(table), "-C", chain}, rule...)...); err == nil {
		return true
	}

	// parse "iptables -S" for the rule (this checks rules in a specific chain
	// in a specific table)
	ruleString := strings.Join(rule, " ")
	ruleString = chain + " " + ruleString
	existingRules, _ := exec.Command(iptablesPath, "-t", string(table), "-S", chain).Output()

	return strings.Contains(string(existingRules), ruleString)
}

// Raw calls 'iptables' system command, passing supplied arguments.
func Raw(args ...string) ([]byte, error) {
	if firewalldRunning {
		output, err := Passthrough(Iptables, args...)
		if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") {
			return output, err
		}
	}
	return raw(args...)
}

func raw(args ...string) ([]byte, error) {
	if err := initCheck(); err != nil {
		return nil, err
	}
	if supportsXlock {
		args = append([]string{"--wait"}, args...)
	} else {
		bestEffortLock.Lock()
		defer bestEffortLock.Unlock()
	}

	logrus.Debugf("%s, %v", iptablesPath, args)

	output, err := exec.Command(iptablesPath, args...).CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
	}

	// ignore iptables' message about xtables lock
	if strings.Contains(string(output), "waiting for it to exit") {
		output = []byte("")
	}

	return output, err
}

// RawCombinedOutput inernally calls the Raw function and returns a non nil
// error if Raw returned a non nil error or a non empty output
func RawCombinedOutput(args ...string) error {
	if output, err := Raw(args...); err != nil || len(output) != 0 {
		return fmt.Errorf("%s (%v)", string(output), err)
	}
	return nil
}

// RawCombinedOutputNative behave as RawCombinedOutput with the difference it
// will always invoke `iptables` binary
func RawCombinedOutputNative(args ...string) error {
	if output, err := raw(args...); err != nil || len(output) != 0 {
		return fmt.Errorf("%s (%v)", string(output), err)
	}
	return nil
}

// ExistChain checks if a chain exists
func ExistChain(chain string, table Table) bool {
	if _, err := Raw("-t", string(table), "-L", chain); err == nil {
		return true
	}
	return false
}


<|start_filename|>daemon/kill.go<|end_filename|>
package daemon

import (
	"fmt"
	"syscall"

	"github.com/golang/glog"
)

func (daemon *Daemon) KillContainer(name string, sig int64) error {
	p, id, ok := daemon.PodList.GetByContainerIdOrName(name)
	if !ok {
		return fmt.Errorf("can not find container %s", name)
	}

	glog.V(1).Infof("found container %s to kill, signal %d", name, sig)
	if p.IsContainerRunning(id) {
		return p.KillContainer(id, sig)
	}

	glog.V(1).Infof("container %s not in alive status, ignore kill", name)
	return nil
}

func (daemon *Daemon) KillPodContainers(podName, container string, sig int64) error {
	var err error

	p, ok := daemon.PodList.Get(podName)
	if !ok {
		err = fmt.Errorf("can not find pod %s", podName)
		glog.Error(err)
		return err
	}

	containers := []string{}
	if container != "" {
		cid, ok := p.ContainerName2Id(container)
		if !ok {
			err = fmt.Errorf("can not get container %s in pod %s", container, podName)
			glog.Error(err)
			return err
		}
		containers = append(containers, cid)
	} else {
		if syscall.Signal(sig) == syscall.SIGKILL {
			p.ForceQuit()
			glog.Infof("force kill sandbox for pod %s", podName)
			return nil
		}
		containers = p.ContainerIds()
	}

	for _, cid := range containers {
		if p.IsContainerRunning(cid) {
			e := p.KillContainer(cid, sig)
			if e != nil {
				glog.Error(e)
				err = e
			}
		}
	}
	return err
}


<|start_filename|>client/utils.go<|end_filename|>
package client

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"os/signal"
	"syscall"

	apitype "github.com/hyperhq/hyperd/types"
	"github.com/hyperhq/hyperd/utils"
	"github.com/hyperhq/runv/lib/term"

	"github.com/docker/docker/pkg/jsonmessage"
	"github.com/docker/docker/pkg/stdcopy"
	"github.com/docker/docker/registry"
	"github.com/docker/engine-api/types"
	registrytypes "github.com/docker/engine-api/types/registry"
	"gopkg.in/yaml.v2"
	"net/http"
)

type AuthRequest func(authConfig types.AuthConfig) (io.ReadCloser, string, int, error)

func (cli *HyperClient) requestWithLogin(index *registrytypes.IndexInfo, op AuthRequest, opTag string) (io.ReadCloser, string, int, error) {

	authConfig := registry.ResolveAuthConfig(cli.configFile.AuthConfigs, index)
	body, ctype, statusCode, err := op(authConfig)
	if statusCode == http.StatusUnauthorized {
		fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", opTag)
		if err = cli.HyperCmdLogin(registry.GetAuthConfigKey(index)); err != nil {
			return nil, "", -1, err
		}
		authConfig = registry.ResolveAuthConfig(cli.configFile.AuthConfigs, index)
		return op(authConfig)
	}
	return body, ctype, statusCode, err
}

func (cli *HyperClient) readStreamOutput(body io.ReadCloser, contentType string, setRawTerminal bool, stdout, stderr io.Writer) error {
	defer body.Close()

	if utils.MatchesContentType(contentType, "application/json") {
		return jsonmessage.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut, nil)
	}
	if stdout != nil || stderr != nil {
		// When TTY is ON, use regular copy
		var err error
		if setRawTerminal {
			_, err = io.Copy(stdout, body)
		} else {
			_, err = stdcopy.StdCopy(stdout, stderr, body)
		}
		return err
	}
	return nil
}

func (cli *HyperClient) resizeTty(containerId, execId string) {
	height, width := cli.getTtySize()
	if height == 0 && width == 0 {
		return
	}
	cli.client.WinResize(containerId, execId, height, width)
}

func (cli *HyperClient) monitorTtySize(containerId, execId string) error {
	//cli.resizeTty(id, tag)

	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, syscall.SIGWINCH)
	go func() {
		for range sigchan {
			cli.resizeTty(containerId, execId)
		}
	}()
	return nil
}

func (cli *HyperClient) getTtySize() (int, int) {
	if !cli.isTerminalOut {
		return 0, 0
	}
	ws, err := term.GetWinsize(cli.outFd)
	if err != nil {
		fmt.Printf("Error getting size: %s", err.Error())
		if ws == nil {
			return 0, 0
		}
	}
	return int(ws.Height), int(ws.Width)
}

func (cli *HyperClient) GetTag() string {
	return utils.RandStr(8, "alphanum")
}

func (cli *HyperClient) ConvertYamlToJson(yamlBody []byte, container bool) ([]byte, error) {
	var (
		body interface{}
	)
	if container {
		var userContainer apitype.UserContainer
		if err := yaml.Unmarshal(yamlBody, &userContainer); err != nil {
			return []byte(""), err
		}
		body = &userContainer
	} else {
		var userPod apitype.UserPod
		if err := yaml.Unmarshal(yamlBody, &userPod); err != nil {
			return []byte(""), err
		}
		body = &userPod
	}
	jsonBody, err := json.Marshal(body)
	if err != nil {
		return []byte(""), err
	}
	return jsonBody, nil
}


<|start_filename|>daemon/daemondb/keys.go<|end_filename|>
package daemondb

import (
	"fmt"
)

const (
	VM_KEY            = "vmdata-%s"
	POD_KEY           = "pod-%s"
	POD_VM_KEY        = "vm-%s"
	POD_CONTAINER_KEY = "pod-container-%s"
	POD_VOLUME_KEY    = "vol-%s-%s"

	POD_PREFIX           = "pod-"
	POD_CONTAINER_PREFIX = "pod-container-"
	POD_VOLUME_PREFIX    = "vol-%s"
	POD_VM_PREFIX        = "vm-"
)

//the id is a vm id
//and the content is vm data content
func keyVMData(id string) []byte {
	return []byte(fmt.Sprintf(VM_KEY, id))
}

// the id is a pod id
// and the db content is the vm id
func keyP2V(id string) []byte {
	return []byte(fmt.Sprintf(POD_VM_KEY, id))
}

// the id is a pod id
// and the db containt is the containers separated by comma
func keyP2C(id string) []byte {
	return []byte(fmt.Sprintf(POD_CONTAINER_KEY, id))
}

func keyPod(id string) []byte {
	return []byte(fmt.Sprintf(POD_KEY, id))
}

func keyVolume(pod string, volume string) []byte {
	return []byte(fmt.Sprintf(POD_VOLUME_KEY, pod, volume))
}

func prefixPod() []byte {
	return []byte(POD_PREFIX)
}

func prefixP2V() []byte {
	return []byte(POD_VM_PREFIX)
}

// the id is pod id
func prefixVolume(podId string) []byte {
	return []byte(fmt.Sprintf(POD_VOLUME_PREFIX, podId))
}


<|start_filename|>client/pause.go<|end_filename|>
package client

import (
	"fmt"
	"strings"

	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdPause(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "pause Pod\n\nPause the pod"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("Can not accept the 'pause' command without Pod ID!")
	}

	return cli.client.PausePod(args[0])
}


<|start_filename|>daemon/legacy/userpod_test.go<|end_filename|>
package legacy

import (
	"testing"

	"github.com/hyperhq/hyperd/utils"
)

func TestRandStr(t *testing.T) {
	r1 := utils.RandStr(10, "alphanum")
	r2 := utils.RandStr(10, "alphanum")
	r3 := utils.RandStr(10, "alphanum")

	if r1 == r2 || r1 == r3 || r2 == r3 {
		t.Fatal("The RandStr function should not return same string!")
	}
}

func TestProcessPodFile(t *testing.T) {
	fakeJsonFile := "test.pod"
	if _, err := ProcessPodFile(fakeJsonFile); err == nil {
		t.Fatal("The ProcessPodFile should return an error while getting a non-exist file!\n")
	}
}

func TestProcessPodBytes(t *testing.T) {
	jsonStr := `{ "id": "test-container-create-1", "containers" : [{ "name": "web", "image": "tomcat:latest" }], "resource": { "vcpu": 1, "memory": 512 }, "files": [], "volumes": [] }`
	if _, err := ProcessPodBytes([]byte(jsonStr)); err != nil {
		t.Fatal("The ProcessPodBytes function return an error while processing a right json string!")
	}

	jsonStrWithoutId := `{ "id": "", "containers" : [{ "name": "web", "image": "tomcat:latest" }], "resource": { "vcpu": 1, "memory": 512 }, "files": [], "volumes": [] }`
	userPod, err := ProcessPodBytes([]byte(jsonStrWithoutId))
	if err != nil {
		t.Fatal("The ProcessPodBytes function return an error while processing a right json string without id name!")
	}
	if userPod.Name == "" {
		t.Fatal("The ProcessPodBytes function do not create an ID name for that pod!\n")
	}
	jsonStrWithoutName := `{ "id": "test-container-create-1", "containers" : [{ "name": "web", "image": "" }], "resource": { "vcpu": 1, "memory": 512 }, "files": [], "volumes": [] }`
	userPod, err = ProcessPodBytes([]byte(jsonStrWithoutName))
	if err == nil {
		t.Fatal("The ProcessPodBytes function should return an error while processing a json string without image name!")
	}
}


<|start_filename|>daemon/legacy/userpod.go<|end_filename|>
package legacy

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/hyperhq/hyperd/utils"
)

// Pod Data Structure
type UserUser struct {
	Name             string   `json:"name"`
	Group            string   `json:"group"`
	AdditionalGroups []string `json:"additionalGroups,omitempty"`
}

type UserContainerPort struct {
	HostPort      int    `json:"hostPort"`
	ContainerPort int    `json:"containerPort"`
	ServicePort   int    `json:"servicePort"`
	Protocol      string `json:"protocol"`
}

type UserEnvironmentVar struct {
	Env   string `json:"env"`
	Value string `json:"value"`
}

type UserVolumeReference struct {
	Path     string `json:"path"`
	Volume   string `json:"volume"`
	ReadOnly bool   `json:"readOnly"`
}

type UserFileReference struct {
	Path     string `json:"path"`
	Filename string `json:"filename"`
	Perm     string `json:"perm"`
	User     string `json:"user"`
	Group    string `json:"group"`
}

type UserContainer struct {
	Name          string                `json:"name"`
	Image         string                `json:"image"`
	User          UserUser              `json:"user,omitempty"`
	Command       []string              `json:"command"`
	Workdir       string                `json:"workdir"`
	Entrypoint    []string              `json:"entrypoint"`
	Tty           bool                  `json:"tty,omitempty"`
	Sysctl        map[string]string     `json:"sysctl,omitempty"`
	Labels        map[string]string     `json:"labels"`
	Ports         []UserContainerPort   `json:"ports"`
	Envs          []UserEnvironmentVar  `json:"envs"`
	Volumes       []UserVolumeReference `json:"volumes"`
	Files         []UserFileReference   `json:"files"`
	RestartPolicy string                `json:"restartPolicy"`
}

type UserResource struct {
	Vcpu   int `json:"vcpu"`
	Memory int `json:"memory"`
}

type UserFile struct {
	Name     string `json:"name"`
	Encoding string `json:"encoding"`
	Uri      string `json:"uri"`
	Contents string `json:"content"`
}

type UserVolumeOption struct {
	Monitors    []string `json:"monitors"`
	User        string   `json:"user"`
	Keyring     string   `json:"keyring"`
	BytesPerSec int      `json:"bytespersec"`
	Iops        int      `json:"iops"`
}

type UserVolume struct {
	Name   string           `json:"name"`
	Source string           `json:"source"`
	Driver string           `json:"driver"`
	Option UserVolumeOption `json:"option,omitempty"`
}

type UserInterface struct {
	Bridge string `json:"bridge"`
	Ip     string `json:"ip"`
	Ifname string `json:"ifname,omitempty"`
	Mac    string `json:"mac,omitempty"`
	Gw     string `json:"gateway,omitempty"`
}

type UserServiceBackend struct {
	HostIP   string `json:"hostip"`
	HostPort int    `json:"hostport"`
}

type UserService struct {
	ServiceIP   string               `json:"serviceip"`
	ServicePort int                  `json:"serviceport"`
	Protocol    string               `json:"protocol"`
	Hosts       []UserServiceBackend `json:"hosts"`
}

type PodLogConfig struct {
	Type   string            `json:"type"`
	Config map[string]string `json:"config"`
}

type PortmappingWhiteList struct {
	InternalNetworks []string `json:"internalNetworks,omitempty"`
	ExternalNetworks []string `json:"externalNetworks,omitempty"`
}

type UserPod struct {
	Name                  string                `json:"id"`
	Hostname              string                `json:"hostname"`
	Containers            []UserContainer       `json:"containers"`
	Resource              UserResource          `json:"resource"`
	Files                 []UserFile            `json:"files"`
	Volumes               []UserVolume          `json:"volumes"`
	Interfaces            []UserInterface       `json:"interfaces,omitempty"`
	Labels                map[string]string     `json:"labels"`
	Services              []UserService         `json:"services,omitempty"`
	LogConfig             PodLogConfig          `json:"log"`
	Dns                   []string              `json:"dns,omitempty"`
	PortmappingWhiteLists *PortmappingWhiteList `json:"portmappingWhiteLists,omitempty"`
	Tty                   bool                  `json:"tty"`
	Type                  string                `json:"type"`
	RestartPolicy         string
}

func ProcessPodFile(jsonFile string) (*UserPod, error) {
	if _, err := os.Stat(jsonFile); err != nil && os.IsNotExist(err) {
		return nil, err
	}
	body, err := ioutil.ReadFile(jsonFile)
	if err != nil {
		return nil, err
	}
	return ProcessPodBytes(body)
}

func ProcessPodBytes(body []byte) (*UserPod, error) {
	var userPod UserPod
	if err := json.Unmarshal(body, &userPod); err != nil {
		return nil, err
	}

	// we need to validate the given POD file
	if userPod.Name == "" {
		userPod.Name = utils.RandStr(10, "alphanum")
	}

	if userPod.Resource.Vcpu == 0 {
		userPod.Resource.Vcpu = 1
	}
	if userPod.Resource.Memory == 0 {
		userPod.Resource.Memory = 128
	}

	var (
		vol UserVolume
		num = 0
	)
	for i, v := range userPod.Containers {
		if v.Image == "" {
			return nil, fmt.Errorf("Please specific your image for your container, it can not be null!\n")
		}
		userPod.Containers[i].Tty = v.Tty || userPod.Tty
		num++
	}
	if num == 0 {
		return nil, fmt.Errorf("Please correct your POD file, the container section can not be null!\n")
	}
	for _, vol = range userPod.Volumes {
		if vol.Name == "" {
			return nil, fmt.Errorf("Hyper ERROR: please specific your volume name, it can not be null!\n")
		}
	}

	if userPod.Labels == nil {
		userPod.Labels = make(map[string]string)
	}

	return &userPod, nil
}


<|start_filename|>client/login.go<|end_filename|>
package client

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/docker/docker/registry"
	"github.com/docker/engine-api/types"
	"github.com/hyperhq/runv/lib/term"

	gflag "github.com/jessevdk/go-flags"
)

// CmdLogin logs in or registers a user to a Docker registry service.
//
// If no server is specified, the user will be logged into or registered to the registry's index server.
//
// Usage: docker login SERVER
func (cli *HyperClient) HyperCmdLogin(args ...string) error {
	var opts struct {
		Email    string `short:"e" long:"email" default:"" value-name:"\"\"" description:"Email"`
		Username string `short:"u" long:"username" default:"" value-name:"\"\"" description:"Username"`
		Password string `short:"p" long:"password" default:"" value-name:"\"\"" description:"Password"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)
	parser.Usage = "login [SERVER]\n\nRegister or log in to a Docker registry server, if no server is\nspecified \"" + registry.IndexServer + "\" is the default."
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	username := opts.Username
	password := opts.Password
	email := opts.Email
	serverAddress := registry.IndexServer
	if len(args) > 0 {
		serverAddress = args[0]
	}

	promptDefault := func(prompt string, configDefault string) {
		if configDefault == "" {
			fmt.Fprintf(cli.out, "%s: ", prompt)
		} else {
			fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault)
		}
	}

	readInput := func(in io.Reader, out io.Writer) string {
		reader := bufio.NewReader(in)
		line, _, err := reader.ReadLine()
		if err != nil {
			fmt.Fprintln(out, err.Error())
			os.Exit(1)
		}
		return string(line)
	}

	authconfig, ok := cli.configFile.AuthConfigs[serverAddress]
	if !ok {
		authconfig = types.AuthConfig{}
	}

	if username == "" {
		promptDefault("Username", authconfig.Username)
		username = readInput(cli.in, cli.out)
		username = strings.Trim(username, " ")
		if username == "" {
			username = authconfig.Username
		}
	}
	// Assume that a different username means they may not want to use
	// the password or email from the config file, so prompt them
	if username != authconfig.Username {
		if password == "" {
			oldState, err := term.SaveState(cli.inFd)
			if err != nil {
				return err
			}
			fmt.Fprintf(cli.out, "Password: ")
			term.DisableEcho(cli.inFd, oldState)

			password = readInput(cli.in, cli.out)
			fmt.Fprint(cli.out, "\n")

			term.RestoreTerminal(cli.inFd, oldState)
			if password == "" {
				return fmt.Errorf("Error : Password Required")
			}
		}

		if email == "" {
			promptDefault("Email", authconfig.Email)
			email = readInput(cli.in, cli.out)
			if email == "" {
				email = authconfig.Email
			}
		}
	} else {
		// However, if they don't override the username use the
		// password or email from the cmd line if specified. IOW, allow
		// then to change/override them.  And if not specified, just
		// use what's in the config file
		if password == "" {
			password = <PASSWORD>
		}
		if email == "" {
			email = authconfig.Email
		}
	}
	authconfig.Username = username
	authconfig.Password = password
	authconfig.Email = email
	authconfig.ServerAddress = serverAddress
	cli.configFile.AuthConfigs[serverAddress] = authconfig

	var response types.AuthResponse
	remove, err := cli.client.Login(cli.configFile.AuthConfigs[serverAddress], &response)
	if remove {
		delete(cli.configFile.AuthConfigs, serverAddress)
		if err2 := cli.configFile.Save(); err2 != nil {
			fmt.Fprintf(cli.out, "WARNING: could not save config file: %v\n", err2)
		}
		return err
	}
	if err != nil {
		return err
	}

	if err := cli.configFile.Save(); err != nil {
		return fmt.Errorf("Error saving config file: %v", err)
	}
	fmt.Fprintf(cli.out, "WARNING: login credentials saved in %s\n", cli.configFile.Filename())

	if response.Status != "" {
		fmt.Fprintf(cli.out, "%s\n", response.Status)
	}
	return nil
}


<|start_filename|>utils/utils_darwin.go<|end_filename|>
// +build darwin

package utils

import (
	"syscall"
)

var (
	MS_BIND uintptr = 0
)

func Mount(source string, target string, fstype string, flags uintptr, data string) error {
	// bind mount is treated as hard link
	if err := syscall.Link(source, target); err != nil {
		return err
	}
	return nil
}


<|start_filename|>daemon/rename.go<|end_filename|>
package daemon

import (
	"fmt"

	"github.com/golang/glog"
)

func (daemon *Daemon) ContainerRename(oldname, newname string) error {
	p, id, ok := daemon.PodList.GetByContainerIdOrName(oldname)
	if !ok {
		err := fmt.Errorf("caonnot find pod contains container %s to rename", oldname)
		glog.Error(err)
		return err
	}

	p.RenameContainer(id, newname)
	return nil
}


<|start_filename|>utils/names.go<|end_filename|>
package utils

import (
	"regexp"
	"strings"
)

const (
	Dns1123LabelFmt           = "[a-z0-9]([-a-z0-9]*[a-z0-9])?"
	dns1123LabelMaxLength int = 63
)

var (
	dns1123LabelRegexp = regexp.MustCompile("^" + Dns1123LabelFmt + "$")
)

func IsDNSLabel(value string) bool {
	return IsDNS1123Label(value)
}

// IsDNS1123Label tests for a string that conforms to the definition of a label in
// DNS (RFC 1123).
func IsDNS1123Label(value string) bool {
	return len(value) <= dns1123LabelMaxLength && dns1123LabelRegexp.MatchString(value)
}

func ParseImageRepoTag(image string) (repo, name, tag string) {
	all := strings.SplitN(image, ":", 2)

	tag = ""
	if len(all) > 1 {
		tag = all[1]
	}

	i := strings.LastIndex(all[0], "/")
	if i >= 0 {
		repo = all[0][:i]
		name = all[0][i+1:]
	} else {
		repo = ""
		name = all[0]
	}

	return repo, name, tag
}


<|start_filename|>client/rm.go<|end_filename|>
package client

import (
	"fmt"
	"strings"

	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdRm(args ...string) error {
	var opts struct {
		Container bool `short:"c" long:"container" default-mask:"-" description:"stop container"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)
	parser.Usage = "rm [OPTIONS] CONTAINER|POD [CONTAINER|POD...]\n\nRemove one or more containers/pods"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("\"rm\" requires a minimum of 1 argument, please provide POD ID.\n")
	}
	for _, id := range args {
		if opts.Container {
			err := cli.client.RemoveContainer(id)
			if err == nil {
				fmt.Fprintf(cli.out, "container %s is successfully deleted!\n", id)
			} else {
				fmt.Fprintf(cli.err, "container %s delete failed: %v\n", id, err)
			}
		} else {
			err := cli.client.RmPod(id)
			if err == nil {
				fmt.Fprintf(cli.out, "Pod(%s) is successfully deleted!\n", id)
			} else {
				fmt.Fprintf(cli.err, "Pod(%s) delete failed: %v\n", id, err)
			}
		}
	}
	return nil
}


<|start_filename|>daemon/images.go<|end_filename|>
package daemon

import (
	"io"

	"github.com/hyperhq/hyperd/image/tarexport"
)

// ExportImage exports a list of images to the given output stream. The
// exported images are archived into a tar when written to the output
// stream. All images with the given tag and all versions containing
// the same tag are exported. names is the set of tags to export, and
// outStream is the writer which the images are written to.
func (daemon *Daemon) ExportImage(names []string, format string, refs map[string]string, outStream io.Writer) error {
	imageExporter := tarexport.NewTarExporter(daemon.ImageStore(), daemon.LayerStore(), daemon.ReferenceStore())
	return imageExporter.Save(names, format, refs, outStream)
}

// LoadImage uploads a set of images into the repository. This is the
// complement of ImageExport.  The input stream is an uncompressed tar
// ball containing images and metadata.
func (daemon *Daemon) LoadImage(inTar io.ReadCloser, name string, refs map[string]string, outStream io.Writer) error {
	imageExporter := tarexport.NewTarExporter(daemon.ImageStore(), daemon.LayerStore(), daemon.ReferenceStore())
	return imageExporter.Load(inTar, name, refs, outStream)
}


<|start_filename|>client/push.go<|end_filename|>
package client

import (
	"fmt"
	"io"
	"strings"

	"github.com/docker/docker/reference"
	"github.com/docker/docker/registry"
	"github.com/docker/engine-api/types"
	gflag "github.com/jessevdk/go-flags"
)

// CmdPush pushes an image or repository to the registry.
//
// Usage: hyperctl push NAME[:TAG]
func (cli *HyperClient) HyperCmdPush(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "push NAME[:TAG]\n\nPush an image to a Docker registry server"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	// we need to get the image name which will be used to create a container
	if len(args) == 0 {
		return fmt.Errorf("\"push\" requires a minimum of 1 argument, please provide the image name.")
	}
	name := args[0]

	ref, err := reference.ParseNamed(name)
	if err != nil {
		return err
	}

	var tag string
	switch x := ref.(type) {
	case reference.Canonical:
		return fmt.Errorf("cannot push a digest reference")
	case reference.NamedTagged:
		tag = x.Tag()
	}

	// Resolve the Repository name from fqn to RepositoryInfo
	repoInfo, err := registry.ParseRepositoryInfo(ref)
	if err != nil {
		return err
	}
	// Resolve the Auth config relevant for this server
	authConfig := registry.ResolveAuthConfig(cli.configFile.AuthConfigs, repoInfo.Index)
	// If we're not using a custom registry, we know the restrictions
	// applied to repository names and can warn the user in advance.
	// Custom repositories can have different rules, and we must also
	// allow pushing by image ID.
	if repoInfo.Official {
		username := authConfig.Username
		if username == "" {
			username = "<user>"
		}
		return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository to <user>/<repo> (ex: %s/%s)", username, ref.Name())
	}

	push := func(auth types.AuthConfig) (io.ReadCloser, string, int, error) {
		return cli.client.Push(tag, repoInfo.String(), auth)
	}

	body, ctype, _, err := cli.requestWithLogin(repoInfo.Index, push, "push")
	if err != nil {
		return err
	}

	return cli.readStreamOutput(body, ctype, cli.isTerminalOut, cli.out, cli.err)
}


<|start_filename|>client/api/logs.go<|end_filename|>
package api

import (
	"io"
	"net/http"
	"net/url"
	"strconv"
)

func (cli *Client) ContainerLogs(container, since string, timestamp, follow, stdout, stderr bool, tail string) (io.ReadCloser, string, error) {
	v := url.Values{}
	v.Set("container", container)
	v.Set("stdout", strconv.FormatBool(stdout))
	v.Set("stderr", strconv.FormatBool(stderr))
	v.Set("since", since)
	v.Set("timestamps", strconv.FormatBool(timestamp))
	v.Set("follow", strconv.FormatBool(follow))
	v.Set("tail", tail)

	headers := http.Header(make(map[string][]string))
	out, contenttype, err := cli.stream("GET", "/container/logs?"+v.Encode(), nil, headers)
	if err != nil {
		return nil, "", err
	}
	return out, contenttype, nil
}


<|start_filename|>client/logout.go<|end_filename|>
package client

import (
	"fmt"
	"strings"

	"github.com/docker/docker/registry"

	gflag "github.com/jessevdk/go-flags"
)

// CmdLogout logs a user out from a Docker registry.
//
// If no server is specified, the user will be logged out from the registry's index server.
//
// Usage: hyperctl logout [SERVER]
func (cli *HyperClient) HyperCmdLogout(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "logout [SERVER]\n\nLog out from a Docker registry, if no server is\nspecified \"" + registry.IndexServer + "\" is the default."
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	serverAddress := registry.IndexServer
	if len(args) > 0 {
		serverAddress = args[0]
	}

	if _, ok := cli.configFile.AuthConfigs[serverAddress]; !ok {
		fmt.Fprintf(cli.out, "Not logged in to %s\n", serverAddress)
	} else {
		fmt.Fprintf(cli.out, "Remove login credentials for %s\n", serverAddress)
		delete(cli.configFile.AuthConfigs, serverAddress)

		if err := cli.configFile.Save(); err != nil {
			return fmt.Errorf("Failed to save docker config: %v", err)
		}
	}
	return nil
}


<|start_filename|>client/api/build.go<|end_filename|>
package api

import (
	"io"
	"net/http"
	"net/url"
)

func (cli *Client) Build(name string, hasBody bool, body io.Reader) (io.ReadCloser, string, error) {
	v := url.Values{}
	v.Set("name", name)
	headers := http.Header(make(map[string][]string))
	if hasBody {
		headers.Set("Content-Type", "application/tar")
	}
	out, contenttype, err := cli.stream("POST", "/image/build?"+v.Encode(), body, headers)
	if err != nil {
		return nil, "", err
	}
	return out, contenttype, nil
}


<|start_filename|>vendor/github.com/hyperhq/runv/api/handler.go<|end_filename|>
package api

type SandboxHandler interface {
}


<|start_filename|>client/api/vm.go<|end_filename|>
package api

import (
	"fmt"
	"net/url"
	"strconv"

	"github.com/hyperhq/hyperd/engine"
	"github.com/hyperhq/runv/hypervisor/types"
)

func (cli *Client) CreateVm(cpu, mem int, async bool) (id string, err error) {
	var (
		body       []byte
		remoteInfo *engine.Env
	)

	v := url.Values{}
	if cpu > 0 {
		v.Set("cpu", strconv.Itoa(cpu))
	}
	if mem > 0 {
		v.Set("mem", strconv.Itoa(mem))
	}
	if async {
		v.Set("async", "yes")
	}

	body, _, err = readBody(cli.call("POST", "/vm/create?"+v.Encode(), nil, nil))
	if err != nil {
		return id, err
	}

	out := engine.NewOutput()
	remoteInfo, err = out.AddEnv()
	if err != nil {
		return id, err
	}

	if _, err = out.Write(body); err != nil {
		err = fmt.Errorf("Error reading remote info: %v", err)
		return id, err
	}
	out.Close()
	errCode := remoteInfo.GetInt("Code")
	if errCode != types.E_OK {
		if errCode != types.E_BAD_REQUEST &&
			errCode != types.E_FAILED {
			err = fmt.Errorf("Error code is %d", errCode)
		} else {
			err = fmt.Errorf("Cause is %s", remoteInfo.Get("Cause"))
		}
	} else {
		id = remoteInfo.Get("ID")
	}

	return id, err
}

func (cli *Client) RmVm(vm string) (err error) {
	var (
		body       []byte
		remoteInfo *engine.Env
	)

	v := url.Values{}
	v.Set("vm", vm)
	body, _, err = readBody(cli.call("DELETE", "/vm?"+v.Encode(), nil, nil))
	if err != nil {
		return fmt.Errorf("Error to remove vm(%s), %s", vm, err.Error())
	}

	out := engine.NewOutput()
	remoteInfo, err = out.AddEnv()
	if err != nil {
		return err
	}

	if _, err = out.Write(body); err != nil {
		err = fmt.Errorf("Error reading remote info: %v", err)
		return err
	}
	out.Close()
	errCode := remoteInfo.GetInt("Code")
	if errCode != types.E_OK {
		if errCode != types.E_BAD_REQUEST &&
			errCode != types.E_FAILED {
			err = fmt.Errorf("Error code is %d", errCode)
		} else {
			err = fmt.Errorf("Cause is %s", remoteInfo.Get("Cause"))
		}
	}

	return err
}


<|start_filename|>daemon/exec.go<|end_filename|>
package daemon

import (
	"fmt"
	"io"

	"github.com/golang/glog"
)

func (daemon *Daemon) ExitCode(containerId, execId string) (int, error) {

	p, id, ok := daemon.PodList.GetByContainerIdOrName(containerId)
	if !ok {
		err := fmt.Errorf("cannot find container %s", containerId)
		glog.Error(err)
		return 255, err
	}

	glog.V(1).Infof("Get Exec Code for container %s", containerId)

	code, err := p.GetExitCode(id, execId)
	return int(code), err
}

func (daemon *Daemon) CreateExec(containerId, cmd string, terminal bool) (string, error) {

	p, id, ok := daemon.PodList.GetByContainerIdOrName(containerId)
	if !ok {
		err := fmt.Errorf("cannot find container %s", containerId)
		glog.Error(err)
		return "", err
	}

	glog.V(1).Infof("Create Exec for container %s", containerId)
	return p.CreateExec(id, cmd, terminal)
}

func (daemon *Daemon) StartExec(stdin io.ReadCloser, stdout io.WriteCloser, containerId, execId string) error {
	p, id, ok := daemon.PodList.GetByContainerIdOrName(containerId)
	if !ok {
		err := fmt.Errorf("cannot find container %s", containerId)
		glog.Error(err)
		return err
	}

	glog.V(1).Infof("Start Exec for container %s", containerId)
	return p.StartExec(stdin, stdout, id, execId)
}

func (daemon *Daemon) KillExec(containerId string, execId string, signal int64) error {
	p, _, ok := daemon.PodList.GetByContainerIdOrName(containerId)
	if !ok {
		err := fmt.Errorf("cannot find container %s", containerId)
		glog.Error(err)
		return err
	}

	glog.V(1).Infof("Kill Exec for container %s", containerId)
	return p.KillExec(execId, signal)
}

func (daemon *Daemon) ExecVM(podID, cmd string, stdin io.ReadCloser, stdout, stderr io.WriteCloser) (int, error) {
	glog.V(3).Infof("Starting ExecVM for pod %s", podID)
	p, ok := daemon.PodList.Get(podID)
	if !ok {
		err := fmt.Errorf("cannot find pod %s", podID)
		glog.Error(err)
		return -1, err
	}

	return p.ExecVM(cmd, stdin, stdout, stderr)
}


<|start_filename|>daemon/info.go<|end_filename|>
package daemon

import (
	"fmt"

	"github.com/golang/glog"

	"github.com/hyperhq/hyperd/daemon/pod"
	"github.com/hyperhq/hyperd/types"
)

func (daemon *Daemon) GetPodInfo(podName string) (*types.PodInfo, error) {
	var (
		p  *pod.XPod
		ok bool
	)
	p, ok = daemon.PodList.Get(podName)
	if !ok {
		return &types.PodInfo{}, fmt.Errorf("Can not get Pod info with pod ID(%s)", podName)
	}

	return p.Info()
}

func (daemon *Daemon) GetPodStats(podId string) (interface{}, error) {
	var (
		p  *pod.XPod
		ok bool
	)
	p, ok = daemon.PodList.Get(podId)
	if !ok {
		return nil, fmt.Errorf("Can not get Pod stats with pod ID(%s)", podId)
	}

	if !p.IsRunning() {
		return nil, fmt.Errorf("Can not get pod stats for non-running pod (%s)", podId)
	}

	if stats := p.Stats(); stats != nil {
		return stats, nil
	}

	return nil, fmt.Errorf("Stats for pod %s is nil", podId)
}

func (daemon *Daemon) GetContainerInfo(name string) (*types.ContainerInfo, error) {
	if name == "" {
		return &types.ContainerInfo{}, fmt.Errorf("Empty container name")
	}
	glog.V(3).Infof("GetContainerInfo of %s", name)

	p, id, ok := daemon.PodList.GetByContainerIdOrName(name)
	if !ok {
		return &types.ContainerInfo{}, fmt.Errorf("Can not find container by name(%s)", name)
	}

	return p.ContainerInfo(id)
}


<|start_filename|>server/router/service/service_routes.go<|end_filename|>
package service

import (
	"net/http"

	"github.com/hyperhq/hyperd/server/httputils"
	"golang.org/x/net/context"
)

func (s *serviceRouter) getServices(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	data, err := s.backend.CmdGetServices(r.Form.Get("podId"))
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, data)
}

func (s *serviceRouter) postServiceAdd(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	podId := r.Form.Get("podId")
	services := r.Form.Get("services")

	data, err := s.backend.CmdAddService(podId, services)
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, data)
}

func (s *serviceRouter) postServiceUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	podId := r.Form.Get("podId")
	services := r.Form.Get("services")

	data, err := s.backend.CmdUpdateService(podId, services)
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, data)
}

func (s *serviceRouter) deleteService(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	podId := r.Form.Get("podId")
	services := r.Form.Get("services")

	data, err := s.backend.CmdDeleteService(podId, services)
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, data)
}


<|start_filename|>daemon/stop.go<|end_filename|>
package daemon

import (
	"fmt"

	"github.com/golang/glog"
)

func (daemon *Daemon) StopPod(podId string) (int, string, error) {
	glog.Infof("Prepare to stop the POD: %s", podId)
	// find the vm id which running POD, and stop it
	p, ok := daemon.PodList.Get(podId)
	if !ok {
		glog.Errorf("Can not find pod(%s)", podId)
		return -1, "", fmt.Errorf("Can not find pod(%s)", podId)
	}

	err := p.Stop(5)
	if err != nil {
		glog.Error(err)

		p.ForceQuit()
	}

	return 0, "", nil
}

func (daemon *Daemon) StopContainer(container string, graceful int) error {
	p, id, ok := daemon.PodList.GetByContainerIdOrName(container)
	if !ok {
		return fmt.Errorf("can not found container %s", container)
	}

	return p.StopContainer(id, graceful)
}


<|start_filename|>client/api/client.go<|end_filename|>
package api

import (
	"crypto/tls"
	"net"
	"net/http"
	"time"
)

type Client struct {
	proto     string
	addr      string
	scheme    string
	tlsConfig *tls.Config
	transport *http.Transport
}

func NewClient(proto, addr string, tlsConfig *tls.Config) *Client {
	var (
		scheme = "http"
	)

	if tlsConfig != nil {
		scheme = "https"
	}

	// The transport is created here for reuse during the client session
	tran := &http.Transport{
		TLSClientConfig: tlsConfig,
	}

	// Why 32? See issue 8035
	timeout := 32 * time.Second
	if proto == "unix" {
		// no need in compressing for local communications
		tran.DisableCompression = true
		tran.Dial = func(_, _ string) (net.Conn, error) {
			return net.DialTimeout(proto, addr, timeout)
		}
	} else {
		tran.Proxy = http.ProxyFromEnvironment
		tran.Dial = (&net.Dialer{Timeout: timeout}).Dial
	}

	return &Client{
		proto:     proto,
		addr:      addr,
		scheme:    scheme,
		transport: tran,
	}
}


<|start_filename|>server/router/container/backend.go<|end_filename|>
package container

import (
	"io"

	"github.com/docker/engine-api/types"
	"github.com/hyperhq/hyperd/daemon"
	"github.com/hyperhq/hyperd/engine"
)

type Backend interface {
	CmdGetContainerInfo(container string) (interface{}, error)
	CmdGetContainerLogs(name string, c *daemon.ContainerLogsConfig) error
	CmdExitCode(container, tag string) (int, error)
	CmdCreateContainer(podId string, containerArgs []byte) (string, error)
	CmdStartContainer(containerId string) (*engine.Env, error)
	CmdKillContainer(name string, sig int64) (*engine.Env, error)
	CmdStopContainer(name string) (*engine.Env, error)
	CmdRemoveContainer(name string) (*engine.Env, error)
	CmdContainerRename(oldName, newName string) (*engine.Env, error)
	CmdAttach(in io.ReadCloser, out io.WriteCloser, id string) error
	CmdCommitImage(name string, cfg *types.ContainerCommitConfig) (*engine.Env, error)
	CmdTtyResize(podId, tag string, h, w int) error
	CreateExec(id, cmd string, terminal bool) (string, error)
	StartExec(stdin io.ReadCloser, stdout io.WriteCloser, containerId, execId string) error
	ExecVM(podID, cmd string, stdin io.ReadCloser, stdout, stderr io.WriteCloser) (int, error)
}


<|start_filename|>mac_installer/dist/opt/hyper/examples/Dockerfile<|end_filename|>
From busybox

COPY *.pod /opt/


<|start_filename|>vendor/google.golang.org/grpc/metadata/metadata.go<|end_filename|>
/*
 *
 * Copyright 2014, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

// Package metadata define the structure of the metadata supported by gRPC library.
// Please refer to http://www.grpc.io/docs/guides/wire.html for more information about custom-metadata.
package metadata

import (
	"encoding/base64"
	"fmt"
	"strings"

	"golang.org/x/net/context"
)

const (
	binHdrSuffix = "-bin"
)

// encodeKeyValue encodes key and value qualified for transmission via gRPC.
// Transmitting binary headers violates HTTP/2 spec.
// TODO(zhaoq): Maybe check if k is ASCII also.
func encodeKeyValue(k, v string) (string, string) {
	k = strings.ToLower(k)
	if strings.HasSuffix(k, binHdrSuffix) {
		val := base64.StdEncoding.EncodeToString([]byte(v))
		v = string(val)
	}
	return k, v
}

// DecodeKeyValue returns the original key and value corresponding to the
// encoded data in k, v.
// If k is a binary header and v contains comma, v is split on comma before decoded,
// and the decoded v will be joined with comma before returned.
func DecodeKeyValue(k, v string) (string, string, error) {
	if !strings.HasSuffix(k, binHdrSuffix) {
		return k, v, nil
	}
	vvs := strings.Split(v, ",")
	for i, vv := range vvs {
		val, err := base64.StdEncoding.DecodeString(vv)
		if err != nil {
			return "", "", err
		}
		vvs[i] = string(val)
	}
	return k, strings.Join(vvs, ","), nil
}

// MD is a mapping from metadata keys to values. Users should use the following
// two convenience functions New and Pairs to generate MD.
type MD map[string][]string

// New creates a MD from given key-value map.
// Keys are automatically converted to lowercase. And for keys having "-bin" as suffix, their values will be applied Base64 encoding.
func New(m map[string]string) MD {
	md := MD{}
	for k, v := range m {
		key, val := encodeKeyValue(k, v)
		md[key] = append(md[key], val)
	}
	return md
}

// Pairs returns an MD formed by the mapping of key, value ...
// Pairs panics if len(kv) is odd.
// Keys are automatically converted to lowercase. And for keys having "-bin" as suffix, their values will be appplied Base64 encoding.
func Pairs(kv ...string) MD {
	if len(kv)%2 == 1 {
		panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv)))
	}
	md := MD{}
	var k string
	for i, s := range kv {
		if i%2 == 0 {
			k = s
			continue
		}
		key, val := encodeKeyValue(k, s)
		md[key] = append(md[key], val)
	}
	return md
}

// Len returns the number of items in md.
func (md MD) Len() int {
	return len(md)
}

// Copy returns a copy of md.
func (md MD) Copy() MD {
	return Join(md)
}

// Join joins any number of MDs into a single MD.
// The order of values for each key is determined by the order in which
// the MDs containing those values are presented to Join.
func Join(mds ...MD) MD {
	out := MD{}
	for _, md := range mds {
		for k, v := range md {
			out[k] = append(out[k], v...)
		}
	}
	return out
}

type mdKey struct{}

// NewContext creates a new context with md attached.
func NewContext(ctx context.Context, md MD) context.Context {
	return context.WithValue(ctx, mdKey{}, md)
}

// FromContext returns the MD in ctx if it exists.
// The returned md should be immutable, writing to it may cause races.
// Modification should be made to the copies of the returned md.
func FromContext(ctx context.Context) (md MD, ok bool) {
	md, ok = ctx.Value(mdKey{}).(MD)
	return
}


<|start_filename|>client/api/request.go<|end_filename|>
package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/hyperhq/hyperd/utils"

	"github.com/docker/engine-api/types"
)

func (cli *Client) call(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) {
	params, err := cli.encodeData(data)
	if err != nil {
		return nil, -1, err
	}

	if data != nil {
		if headers == nil {
			headers = make(map[string][]string)
		}
		headers["Content-Type"] = []string{"application/json"}
	}

	body, _, statusCode, err := cli.httpRequest(method, path, params, headers)
	return body, statusCode, err
}

func (cli *Client) stream(method, path string, in io.Reader, headers map[string][]string) (io.ReadCloser, string, error) {
	body, contentType, _, err := cli.httpRequest(method, path, in, headers)
	if err != nil {
		return nil, "", err
	}
	return body, contentType, err
}

func (cli *Client) authRequest(method, path string, in io.Reader, headers map[string][]string, auth types.AuthConfig) (io.ReadCloser, string, int, error) {
	headers, err := cli.AuthHeader(headers, auth)
	if err != nil {
		return nil, "", -1, err
	}
	return cli.httpRequest(method, path, in, headers)
}

func (cli *Client) HTTPClient() *http.Client {
	return &http.Client{Transport: cli.transport}
}

func (cli *Client) encodeData(data interface{}) (*bytes.Buffer, error) {
	params := bytes.NewBuffer(nil)
	if data != nil {
		buf, err := json.Marshal(data)
		if err != nil {
			return nil, err
		}
		if _, err := params.Write(buf); err != nil {
			return nil, err
		}
	}
	return params, nil
}

func (cli *Client) httpRequest(method, path string, in io.Reader, headers map[string][]string) (io.ReadCloser, string, int, error) {
	expectedPayload := (method == "POST" || method == "PUT" || method == "DELETE")
	if expectedPayload && in == nil {
		in = bytes.NewReader([]byte{})
	}
	req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", utils.VERSION, path), in)
	if err != nil {
		return nil, "", -1, err
	}
	req.Header.Set("User-Agent", "Hyper-Client/"+utils.VERSION)
	req.URL.Host = cli.addr
	req.URL.Scheme = cli.scheme

	if headers != nil {
		for k, v := range headers {
			req.Header[k] = v
		}
	}

	if expectedPayload && req.Header.Get("Content-Type") == "" {
		req.Header.Set("Content-Type", "text/plain")
	}

	resp, err := cli.HTTPClient().Do(req)
	statusCode := -1
	if resp != nil {
		statusCode = resp.StatusCode
	}
	if err != nil {
		if strings.Contains(err.Error(), "connection refused") {
			return nil, "", statusCode, ErrConnectionRefused
		}

		return nil, "", statusCode, fmt.Errorf("An error occurred trying to connect: %v", err)
	}

	if statusCode < 200 || statusCode >= 400 {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, "", statusCode, err
		}
		if len(body) == 0 {
			return nil, "", statusCode, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(statusCode), req.URL)
		}
		return nil, "", statusCode, fmt.Errorf("Error from daemon's response: %s", bytes.TrimSpace(body))
	}

	return resp.Body, resp.Header.Get("Content-Type"), statusCode, nil
}

func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
	if stream != nil {
		defer stream.Close()
	}
	if err != nil {
		return nil, statusCode, err
	}
	if stream == nil {
		return nil, statusCode, err
	}
	body, err := ioutil.ReadAll(stream)
	if err != nil {
		return nil, -1, err
	}
	return body, statusCode, nil
}


<|start_filename|>client/api/stop.go<|end_filename|>
package api

import (
	"fmt"
	"net/url"
	"strings"

	"github.com/hyperhq/hyperd/engine"
)

func (cli *Client) StopContainer(container string) error {
	v := url.Values{}
	v.Set("container", container)

	_, _, err := readBody(cli.call("POST", "/container/stop?"+v.Encode(), nil, nil))
	if err != nil {
		return err
	}
	return nil
}

func (cli *Client) StopPod(podId, stopVm string) (int, string, error) {
	v := url.Values{}
	v.Set("podId", podId)
	v.Set("stopVm", stopVm)
	body, _, err := readBody(cli.call("POST", "/pod/stop?"+v.Encode(), nil, nil))
	if err != nil {
		if strings.Contains(err.Error(), "leveldb: not found") {
			return -1, "", fmt.Errorf("Can not find that POD ID to stop, please check your POD ID!")
		}
		return -1, "", err
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return -1, "", err
	}

	if _, err := out.Write(body); err != nil {
		return -1, "", err
	}
	out.Close()
	// This 'ID' stands for pod ID
	// This 'Code' should be E_SHUTDOWN
	// THis 'Cause' ..
	if remoteInfo.Exists("ID") {
		// TODO ...
	}
	return remoteInfo.GetInt("Code"), remoteInfo.Get("Cause"), nil
}


<|start_filename|>server/router/container/container_routes.go<|end_filename|>
package container

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/docker/docker/builder/dockerfile"
	"github.com/docker/docker/pkg/ioutils"
	"github.com/docker/docker/runconfig"
	"github.com/docker/docker/utils"
	"github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/container"
	timetypes "github.com/docker/engine-api/types/time"
	"github.com/golang/glog"
	"github.com/hyperhq/hyperd/daemon"
	"github.com/hyperhq/hyperd/engine"
	"github.com/hyperhq/hyperd/server/httputils"
	"golang.org/x/net/context"
)

func (c *containerRouter) getContainerInfo(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	data, err := c.backend.CmdGetContainerInfo(r.Form.Get("container"))
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, data)
}

func (c *containerRouter) getContainerLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	// Args are validated before the stream starts because when it starts we're
	// sending HTTP 200 by writing an empty chunk of data to tell the client that
	// daemon is going to stream. By sending this initial HTTP 200 we can't report
	// any error after the stream starts (i.e. container not found, wrong parameters)
	// with the appropriate status code.
	stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
	if !(stdout || stderr) {
		return fmt.Errorf("Bad parameters: you must choose at least one stream")
	}

	var since time.Time
	if r.Form.Get("since") != "" {
		s, n, err := timetypes.ParseTimestamps(r.Form.Get("since"), 0)
		if err != nil {
			return err
		}
		since = time.Unix(s, n)
	}

	var closeNotifier <-chan bool
	if notifier, ok := w.(http.CloseNotifier); ok {
		closeNotifier = notifier.CloseNotify()
	}

	containerName := r.Form.Get("container")
	/*
		if !s.backend.Exists(containerName) {
			return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
		}
	*/
	// write an empty chunk of data (this is to ensure that the
	// HTTP Response is sent immediately, even if the container has
	// not yet produced any data)
	w.WriteHeader(http.StatusOK)
	if flusher, ok := w.(http.Flusher); ok {
		flusher.Flush()
	}

	output := ioutils.NewWriteFlusher(w)
	defer output.Close()

	logsConfig := &daemon.ContainerLogsConfig{
		Follow:     httputils.BoolValue(r, "follow"),
		Timestamps: httputils.BoolValue(r, "timestamps"),
		Since:      since,
		Tail:       r.Form.Get("tail"),
		UseStdout:  stdout,
		UseStderr:  stderr,
		OutStream:  output,
		Stop:       closeNotifier,
	}

	if err := c.backend.CmdGetContainerLogs(containerName, logsConfig); err != nil {
		// The client may be expecting all of the data we're sending to
		// be multiplexed, so send it through OutStream, which will
		// have been set up to handle that if needed.
		fmt.Fprintf(logsConfig.OutStream, "Error running logs job: %s\n", utils.GetErrorMessage(err))
	}

	return nil
}

func (c *containerRouter) postContainerCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	if err := httputils.CheckForJSON(r); err != nil {
		return err
	}

	podId := r.Form.Get("podId")
	if podId == "" {
		return fmt.Errorf("podId is required to create a new container")
	}

	containerArgs, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}

	glog.V(1).Infof("Create container %s in pod %s", string(containerArgs), podId)

	containterID, err := c.backend.CmdCreateContainer(podId, containerArgs)
	if err != nil {
		return err
	}

	v := &engine.Env{}
	v.SetJson("ID", containterID)
	return v.WriteJSON(w, http.StatusCreated)
}

func (c *containerRouter) postContainerStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	cname := r.Form.Get("container")
	env, err := c.backend.CmdStartContainer(cname)
	if err != nil {
		return err
	}

	return env.WriteJSON(w, http.StatusOK)
}

func (c *containerRouter) postContainerKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	sigterm := int64(15)
	cname := r.Form.Get("container")
	signal, err := httputils.Int64ValueOrDefault(r, "signal", sigterm)
	if err != nil {
		signal = sigterm
	}

	env, err := c.backend.CmdKillContainer(cname, signal)

	if err != nil {
		return err
	}

	return env.WriteJSON(w, http.StatusCreated)
}

func (c *containerRouter) postContainerStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	cname := r.Form.Get("container")
	env, err := c.backend.CmdStopContainer(cname)
	if err != nil {
		return err
	}

	return env.WriteJSON(w, http.StatusOK)
}

func (c *containerRouter) postContainerRemove(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	cname := r.Form.Get("container")
	env, err := c.backend.CmdRemoveContainer(cname)
	if err != nil {
		return err
	}

	return env.WriteJSON(w, http.StatusNoContent)
}

func (c *containerRouter) postContainerCommit(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	cname := r.Form.Get("container")
	pause := httputils.BoolValue(r, "pause")

	config, _, _, err := runconfig.DecodeContainerConfig(r.Body)
	if err != nil && err != io.EOF { //Do not fail if body is empty.
		return err
	}
	if config == nil {
		config = &container.Config{}
	}

	newConfig, err := dockerfile.BuildFromConfig(config, r.Form["changes"])
	if err != nil {
		return err
	}

	commitCfg := &types.ContainerCommitConfig{
		Pause:        pause,
		Repo:         r.Form.Get("repo"),
		Tag:          r.Form.Get("tag"),
		Author:       r.Form.Get("author"),
		Comment:      r.Form.Get("comment"),
		Config:       newConfig,
		MergeConfigs: true,
	}

	env, err := c.backend.CmdCommitImage(cname, commitCfg)
	if err != nil {
		return err
	}

	return env.WriteJSON(w, http.StatusOK)
}

func (c *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	newName := r.Form.Get("newName")
	oldName := r.Form.Get("oldName")
	env, err := c.backend.CmdContainerRename(oldName, newName)
	if err != nil {
		return err
	}

	return env.WriteJSON(w, http.StatusOK)
}


<|start_filename|>image/tarexport/save-oci.go<|end_filename|>
package tarexport

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"runtime"

	"github.com/docker/docker/image"
	"github.com/docker/docker/layer"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/system"
	"github.com/docker/docker/reference"
	"github.com/opencontainers/go-digest"
	imgspec "github.com/opencontainers/image-spec/specs-go"
	ociv1 "github.com/opencontainers/image-spec/specs-go/v1"
)

type layerInfo struct {
	digest digest.Digest
	size   int64
}

type ociSaveSession struct {
	*tarexporter
	refs         map[string]string
	images       map[image.ID]*imageDescriptor
	name         string
	savedImages  map[image.ID]ociv1.Manifest // cache image.ID -> manifest bytes
	diffIDsCache map[layer.DiffID]*layerInfo
	outDir       string
	index        ociv1.ImageIndex
}

func getRefs(irefs map[string]string) (map[string]string, map[string]reference.NamedTagged, error) {
	refs := make(map[string]string)
	reversed := make(map[string]reference.NamedTagged)
	for image, ref := range irefs {
		r, err := reference.ParseNamed(image)
		if err != nil {
			return nil, nil, err
		}
		if _, ok := r.(reference.Canonical); ok {
			continue // a digest reference it's unique, no need for a --ref
		}
		tagged, ok := r.(reference.NamedTagged)
		if !ok {
			return nil, nil, fmt.Errorf("ref %q is not name tagged", ref)
		}
		if !ociRefRegexp.MatchString(ref) {
			return nil, nil, fmt.Errorf(`invalid reference "%s=%s", reference must not include characters outside of the set of "A" to "Z", "a" to "z", "0" to "9", the hyphen "-", the dot ".", and the underscore "_"`, image, ref)
		}
		refs[tagged.String()] = ref
		reversed[ref] = tagged
	}
	return refs, reversed, nil
}

var ociRefRegexp = regexp.MustCompile(`^([A-Za-z0-9._-]+)+$`)

func (l *tarexporter) parseOCINames(names []string, irefs map[string]string) (map[image.ID]*imageDescriptor, error) {
	refs, _, err := getRefs(irefs)
	if err != nil {
		return nil, err
	}
	imgDescr := make(map[image.ID]*imageDescriptor)
	tags := make(map[string]bool)

	addAssoc := func(id image.ID, ref reference.Named) error {
		if _, ok := imgDescr[id]; !ok {
			imgDescr[id] = &imageDescriptor{}
		}

		if ref != nil {
			var tagged reference.NamedTagged
			var ok bool
			if _, ok = ref.(reference.Canonical); ok {
				return nil
			}

			if tagged, ok = ref.(reference.NamedTagged); !ok {
				var err error
				if tagged, err = reference.WithTag(ref, reference.DefaultTag); err != nil {
					return err
				}
			}

			r, ok := refs[tagged.String()]
			if ok {
				var err error
				if tagged, err = reference.WithTag(tagged, r); err != nil {
					return err
				}
			}

			for _, t := range imgDescr[id].refs {
				if tagged.String() == t.String() {
					return nil
				}
			}

			if tags[tagged.Tag()] {
				return fmt.Errorf("unable to include unique references %q in OCI image", tagged.Tag())
			}

			tags[tagged.Tag()] = true

			imgDescr[id].refs = append(imgDescr[id].refs, tagged)
		}

		return nil
	}

	// TODO(runcom): same as docker-save except the error return in addAssoc
	// and the tags map above.
	for _, name := range names {
		ref, err := reference.ParseNamed(name)
		if err != nil {
			return nil, err
		}
		if ref.Name() == string(digest.Canonical) {
			imgID, err := l.is.Search(name)
			if err != nil {
				return nil, err
			}
			addAssoc(imgID, nil)
			continue
		}
		if reference.IsNameOnly(ref) {
			assocs := l.rs.ReferencesByName(ref)
			for _, assoc := range assocs {
				if err := addAssoc(assoc.ImageID, assoc.Ref); err != nil {
					return nil, err
				}
			}
			if len(assocs) == 0 {
				imgID, err := l.is.Search(name)
				if err != nil {
					return nil, err
				}
				if err := addAssoc(imgID, nil); err != nil {
					return nil, err
				}
			}
			continue
		}
		id, err := l.rs.Get(ref)
		if err != nil {
			return nil, err
		}
		if err := addAssoc(id, ref); err != nil {
			return nil, err
		}
	}
	return imgDescr, nil
}

func (s *ociSaveSession) save(outStream io.Writer) error {
	s.diffIDsCache = make(map[layer.DiffID]*layerInfo)
	s.savedImages = make(map[image.ID]ociv1.Manifest)
	s.index = ociv1.ImageIndex{
		Versioned: imgspec.Versioned{
			SchemaVersion: 2,
		},
	}
	tempDir, err := ioutil.TempDir("", "oci-export-")
	if err != nil {
		return err
	}
	defer os.RemoveAll(tempDir)

	s.outDir = tempDir

	if err := ioutil.WriteFile(filepath.Join(tempDir, "oci-layout"), []byte(`{"imageLayoutVersion": "1.0.0"}`), 0644); err != nil {
		return err
	}

	for id, info := range s.images {
		for _, i := range info.refs {
			// TODO(runcom): handle foreign srcs like save.go
			if err := s.saveImage(id, i.Tag()); err != nil {
				return err
			}
		}
		if len(info.refs) == 0 {
			// TODO(runcom): handle foreign srcs like save.go
			if err := s.saveImage(id, digest.Digest(id).Hex()); err != nil {
				return err
			}
		}
	}

	indexJSON, err := json.Marshal(s.index)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(filepath.Join(tempDir, "index.json"), indexJSON, 0644); err != nil {
		return err
	}

	fs, err := archive.Tar(tempDir, archive.Uncompressed)
	if err != nil {
		return err
	}
	defer fs.Close()

	_, err = io.Copy(outStream, fs)
	return err
}

func (s *ociSaveSession) saveImage(id image.ID, ref string) error {
	if m, ok := s.savedImages[id]; ok {
		if err := s.saveManifest(ref, m); err != nil {
			return err
		}
		return nil
	}

	img, err := s.is.Get(id)
	if err != nil {
		return err
	}

	if len(img.RootFS.DiffIDs) == 0 {
		return fmt.Errorf("empty export - not implemented")
	}

	configFile, err := blobPath(s.outDir, digest.Digest(id))
	if err != nil {
		return err
	}
	if err := ensureParentDirectoryExists(configFile); err != nil {
		return err
	}
	if err := ioutil.WriteFile(configFile, img.RawJSON(), 0644); err != nil {
		return err
	}
	if err := system.Chtimes(configFile, img.Created, img.Created); err != nil {
		return err
	}

	// TODO(runcom): there should likely be a manifest builder (like docker/distribution)
	m := ociv1.Manifest{
		Versioned: imgspec.Versioned{
			SchemaVersion: 2,
		},
		Config: ociv1.Descriptor{
			MediaType: ociv1.MediaTypeImageConfig,
			Digest:    digest.Digest(img.ID()),
			Size:      int64(len(img.RawJSON())),
		},
	}

	for i := range img.RootFS.DiffIDs {
		rootFS := *img.RootFS
		rootFS.DiffIDs = rootFS.DiffIDs[:i+1]

		l, err := s.ls.Get(rootFS.ChainID())
		if err != nil {
			return err
		}
		defer layer.ReleaseAndLog(s.ls, l)

		var (
			digest digest.Digest
			size   int64
		)
		if i, ok := s.diffIDsCache[l.DiffID()]; ok {
			digest = i.digest
			size = i.size
		} else {
			lInfo, err := s.saveLayer(l)
			if err != nil {
				return err
			}
			digest = lInfo.digest
			size = lInfo.size
		}

		descriptor := ociv1.Descriptor{
			MediaType: ociv1.MediaTypeImageLayer,
			Digest:    digest,
			Size:      size,
		}
		m.Layers = append(m.Layers, descriptor)
	}

	if err := s.saveManifest(ref, m); err != nil {
		return err
	}

	s.savedImages[id] = m

	return nil
}

func (s *ociSaveSession) saveManifest(ref string, ociMan ociv1.Manifest) error {
	b, err := json.Marshal(ociMan)
	if err != nil {
		return err
	}
	d := digest.FromBytes(b)
	desc := ociv1.Descriptor{}
	desc.Digest = d
	desc.Size = int64(len(b))
	desc.MediaType = ociv1.MediaTypeImageManifest

	blobPath, err := blobPath(s.outDir, d)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(blobPath, b, 0644); err != nil {
		return err
	}
	annotations := make(map[string]string)
	annotations["org.opencontainers.ref.name"] = ref
	desc.Annotations = annotations
	s.index.Manifests = append(s.index.Manifests, ociv1.ManifestDescriptor{
		Descriptor: desc,
		Platform: ociv1.Platform{
			Architecture: runtime.GOARCH,
			OS:           runtime.GOOS,
		},
	})
	return nil
}

func (s *ociSaveSession) saveLayer(l layer.Layer) (*layerInfo, error) {
	arch, err := l.TarStream()
	if err != nil {
		return nil, err
	}
	defer arch.Close()

	blobFile, err := ioutil.TempFile(s.outDir, "oci-blob")
	if err != nil {
		return nil, err
	}
	defer os.RemoveAll(blobFile.Name())

	digester := digest.Canonical.Digester()
	tee := io.TeeReader(arch, digester.Hash())

	size, err := io.Copy(blobFile, tee)
	if err != nil {
		return nil, err
	}
	computedDigest := digester.Digest()
	if err := blobFile.Sync(); err != nil {
		return nil, err
	}
	if err := blobFile.Chmod(0644); err != nil {
		return nil, err
	}
	blobPath, err := blobPath(s.outDir, computedDigest)
	if err != nil {
		return nil, err
	}
	if err := ensureParentDirectoryExists(blobPath); err != nil {
		return nil, err
	}
	if err := os.Rename(blobFile.Name(), blobPath); err != nil {
		return nil, err
	}
	li := &layerInfo{digest: computedDigest, size: size}
	s.diffIDsCache[l.DiffID()] = li
	return li, nil
}

func ensureDirectoryExists(path string) error {
	if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
		if err := os.MkdirAll(path, 0755); err != nil {
			return err
		}
	}
	return nil
}

// ensureParentDirectoryExists ensures the parent of the supplied path exists.
func ensureParentDirectoryExists(path string) error {
	return ensureDirectoryExists(filepath.Dir(path))
}

func blobPath(tmp string, digest digest.Digest) (string, error) {
	if err := digest.Validate(); err != nil {
		return "", fmt.Errorf("unexpected digest reference %s: %v", digest.String(), err)
	}
	return filepath.Join(tmp, "blobs", digest.Algorithm().String(), digest.Hex()), nil
}


<|start_filename|>storage/devicemapper/dm_test.go<|end_filename|>
package devicemapper

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"strings"
	"syscall"
	"testing"
)

var (
	poolName         = "dm-1:1-1234567-pool"
	tempDir          = os.TempDir()
	dmRootDir        = path.Join(tempDir, "devicemapper")
	datafile         = dmRootDir + "/data"
	metadatafile     = dmRootDir + "/meta_data"
	dataLoopFile     = "/dev/loop7"
	metadataLoopFile = "/dev/loop6"
	containerId      = "123"
	devPrefix        = poolName[:strings.Index(poolName, "-pool")]
)

// Do some init work, such as creating a dm pool
func Init() error {
	// Create the root dir for devicemapper
	if err := os.MkdirAll(dmRootDir, 0755); err != nil {
		return err
	}

	// Create data file and metadata file
	parms := fmt.Sprintf("dd if=/dev/zero of=%s bs=1G count=1", datafile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	parms = fmt.Sprintf("dd if=/dev/zero of=%s bs=128M count=1", metadatafile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}

	// Setup the loop device for data and metadata files
	parms = fmt.Sprintf("losetup %s %s", dataLoopFile, datafile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	parms = fmt.Sprintf("losetup %s %s", metadataLoopFile, metadatafile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}

	// Make filesystem for data loop device and metadata loop device
	parms = fmt.Sprintf("mkfs.ext4 %s", dataLoopFile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	parms = fmt.Sprintf("mkfs.ext4 %s", metadataLoopFile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}

	// Zero the loop device
	parms = fmt.Sprintf("dd if=/dev/zero of=%s bs=1G count=1", dataLoopFile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	parms = fmt.Sprintf("dd if=/dev/zero of=%s bs=128M count=1", metadataLoopFile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}

	// Create the thin pool for test
	parms = fmt.Sprintf("dmsetup create %s --table '0 2097152 thin-pool %s %s 128 0'", poolName, metadataLoopFile, dataLoopFile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	parms = fmt.Sprintf("dmsetup message /dev/mapper/%s 0 'create_thin' 0", poolName)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}

	// Write the container's device metadata
	if err := os.MkdirAll(path.Join(dmRootDir, "metadata"), 0755); err != nil {
		return err
	}
	// Write the container's device mnt
	if err := os.MkdirAll(path.Join(dmRootDir, "mnt"), 0755); err != nil {
		return err
	}

	jsondata := jsonMetadata{
		Device_id:      0,
		Size:           262144,
		Transaction_id: 2,
		Initialized:    false,
	}
	body, err := json.Marshal(jsondata)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(dmRootDir+"/metadata/"+containerId, body, 0755); err != nil {
		return err
	}
	return nil
}

// Delete the pool which is created in 'Init' function
func Cleanup() error {
	var parms string
	parms = fmt.Sprintf("dmsetup remove -f \"/dev/mapper/%s-%s\"", devPrefix, containerId)
	if output, err := exec.Command("/bin/sh", "-c", parms).Output(); err != nil {
		//fmt.Printf("Exec (%s) failed: %s\n", parms, string(output))
		_ = output
		return err
	}

	// Delete the thin pool for test
	parms = fmt.Sprintf("dmsetup remove \"/dev/mapper/%s\"", poolName)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	// Delete the loop device
	parms = fmt.Sprintf("losetup -d %s", metadataLoopFile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	parms = fmt.Sprintf("losetup -d %s", dataLoopFile)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		return err
	}
	if err := os.RemoveAll(dmRootDir); err != nil {
		return err
	}
	return nil
}

func TestCreateNewDevice(t *testing.T) {
	Cleanup()
	if err := Init(); err != nil {
		t.Fatalf(err.Error())
	}

	if err := CreateNewDevice(containerId, devPrefix, dmRootDir); err != nil {
		t.Fatalf(err.Error())
	}

	if _, err := os.Stat("/dev/mapper/" + devPrefix + "-" + containerId); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Create device for container failed")
		} else {
			t.Fatalf("Create device for container failed, %s", err.Error())
		}
	}

	if err := Cleanup(); err != nil {
		t.Fatalf(err.Error())
	}
}

func TestProbeFsType(t *testing.T) {
	Cleanup()
	if err := Init(); err != nil {
		t.Fatalf(err.Error())
	}

	if err := CreateNewDevice(containerId, devPrefix, dmRootDir); err != nil {
		t.Fatalf(err.Error())
	}

	devFullName := "/dev/mapper/" + devPrefix + "-" + containerId
	var parms string
	parms = fmt.Sprintf("mkfs.ext4 \"%s\"", devFullName)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		t.Fatalf(err.Error())
	}
	fstype, err := ProbeFsType("/dev/dm-1")
	if err != nil {
		t.Fatalf(err.Error())
	}

	if fstype == "" {
		t.Error("Failed to check the device filesystem type!")
	}

	defer func() {
		if err := Cleanup(); err != nil {
			t.Fatalf(err.Error())
		}
	}()
}

func TestAttachFiles(t *testing.T) {
	Cleanup()
	if err := Init(); err != nil {
		t.Fatalf(err.Error())
	}
	if err := CreateNewDevice(containerId, devPrefix, dmRootDir); err != nil {
		t.Fatalf(err.Error())
	}
	parms := fmt.Sprintf("mkfs.ext4 \"/dev/mapper/%s-%s\"", devPrefix, containerId)
	if err := exec.Command("/bin/sh", "-c", parms).Run(); err != nil {
		t.Fatalf(err.Error())
	}

	var (
		flags       uintptr = syscall.MS_MGC_VAL
		idMountPath         = path.Join(dmRootDir, "mnt", containerId)
		rootFs              = path.Join(idMountPath, "rootfs")
		toDir               = "/"
		targetDir           = path.Join(rootFs, toDir)
		devFullName         = "/dev/mapper/" + devPrefix + "-" + containerId
	)
	if err := AttachFiles(containerId, devPrefix, "/etc/os-release", toDir, dmRootDir, "0755", "0", "0"); err != nil {
		t.Fatalf(err.Error())
	}

	fstype, err := ProbeFsType("/dev/mapper/dm-1:1-1234567-123")
	if err != nil {
		t.Fatalf(err.Error())
	}
	options := ""
	if fstype == "xfs" {
		// XFS needs nouuid or it can't mount filesystems with the same fs
		options = joinMountOptions(options, "nouuid")
	}

	err = syscall.Mount(devFullName, idMountPath, fstype, flags, joinMountOptions("discard", options))
	if err != nil && err == syscall.EINVAL {
		err = syscall.Mount(devFullName, idMountPath, fstype, flags, options)
	}
	if err != nil {
		t.Fatalf("Error mounting '%s' on '%s': %s", devFullName, idMountPath, err)
	}
	targetFile := targetDir + "/os-release"
	if _, err := os.Stat(targetFile); err != nil {
		t.Log(targetFile)
		t.Fatalf(err.Error())
	}
	syscall.Unmount(idMountPath, syscall.MNT_DETACH)
	defer func() {
		if err := Cleanup(); err != nil {
			t.Fatalf(err.Error())
		}
	}()
}


<|start_filename|>server/router/system/system_routes.go<|end_filename|>
package system

import (
	"encoding/json"
	"net/http"

	"github.com/docker/engine-api/types"
	"github.com/hyperhq/hyperd/engine"
	"github.com/hyperhq/hyperd/server/httputils"
	"golang.org/x/net/context"
)

func pingHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	_, err := w.Write([]byte{'O', 'K'})
	return err
}

func (s *systemRouter) getInfo(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	info, err := s.backend.CmdSystemInfo()
	if err != nil {
		return err
	}

	env := &engine.Env{}
	status := [][2]string{}

	env.Set("ID", info.ID)
	env.SetInt("Containers", int(info.Containers))
	env.SetInt("Images", int(info.Images))
	env.Set("Driver", info.Driver)
	env.Set("DockerRootDir", info.DockerRootDir)
	env.Set("IndexServerAddress", info.IndexServerAddress)
	env.Set("ExecutionDriver", info.ExecutionDriver)
	env.SetInt64("MemTotal", info.MemTotal)
	env.SetInt64("Pods", info.Pods)
	env.Set("Operating System", info.OperatingSystem)

	for _, driverStatus := range info.Dstatus {
		status = append(status, [2]string{driverStatus.Name, driverStatus.Status})
	}
	env.SetJson("DriverStatus", status)

	if info.Name != "" {
		env.SetJson("Name", info.Name)
	}

	return env.WriteJSON(w, http.StatusOK)
}

func (s *systemRouter) getVersion(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	env := s.backend.CmdSystemVersion()
	return env.WriteJSON(w, http.StatusOK)
}

func (s *systemRouter) postAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	var config *types.AuthConfig
	err := json.NewDecoder(r.Body).Decode(&config)
	r.Body.Close()
	if err != nil {
		return err
	}
	status, err := s.backend.CmdAuthenticateToRegistry(config)
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, &types.AuthResponse{Status: status})
}


<|start_filename|>daemon/pod/volume.go<|end_filename|>
package pod

import (
	"fmt"
	"sync"

	"github.com/hyperhq/hypercontainer-utils/hlog"
	apitypes "github.com/hyperhq/hyperd/types"
	"github.com/hyperhq/hyperd/utils"
	runv "github.com/hyperhq/runv/api"
)

type VolumeState int32

const (
	S_VOLUME_CREATED VolumeState = iota
	S_VOLUME_INSERTING
	S_VOLUME_INSERTED
	S_VOLUME_ERROR
)

type Volume struct {
	p *XPod

	spec     *apitypes.UserVolume
	descript *runv.VolumeDescription
	status   VolumeState

	insertSubscribers []*utils.WaitGroupWithFail

	sync.RWMutex
}

func newVolume(p *XPod, spec *apitypes.UserVolume) *Volume {
	return &Volume{
		p:                 p,
		spec:              spec,
		insertSubscribers: []*utils.WaitGroupWithFail{},
	}
}

func (v *Volume) LogPrefix() string {
	return fmt.Sprintf("%sVol[%s] ", v.p.LogPrefix(), v.spec.Name)
}

func (v *Volume) Log(level hlog.LogLevel, args ...interface{}) {
	hlog.HLog(level, v, 1, args...)
}

func (v *Volume) getStatus() VolumeState {
	v.RLock()
	s := v.status
	v.RUnlock()
	return s
}

func (v *Volume) Info() *apitypes.PodVolume {
	return &apitypes.PodVolume{
		Name:   v.spec.Name,
		Source: v.spec.Source,
		Driver: v.spec.Format,
	}
}

// add() try to mount the volume and add it to the sandbox
func (v *Volume) add() error {
	changed, err := v.transit(
		S_VOLUME_INSERTING,
		map[VolumeState]bool{S_VOLUME_CREATED: true},                            // from created to inserting
		map[VolumeState]bool{S_VOLUME_INSERTING: true, S_VOLUME_INSERTED: true}, //ignore if inserting or inserted already
	)
	if !changed { // already logged in v.transit method
		return err
	}

	defer func() {
		if err != nil {
			v.setInsertFail(err)
		}
	}()

	err = v.mount()
	if err != nil {
		v.Log(ERROR, "failed to mount volume: %v", err)
		return err
	}
	defer func() {
		if err != nil {
			v.umount()
		}
	}()

	err = v.insert()
	if err != nil {
		v.Log(ERROR, "failed to mount volume: %v", err)
		return err
	}

	//only from inserting to inserted
	v.setInserted()
	return nil
}

// insert() should only called by add(), and not expose to outside
// the class.
func (v *Volume) insert() error {
	v.Log(DEBUG, "insert volume to sandbox")
	r := v.p.sandbox.AddVolume(v.descript)
	if !r.IsSuccess() {
		err := fmt.Errorf("failed to insert: %s", r.Message())
		v.Log(ERROR, err)
		return err
	}

	v.Log(INFO, "volume inserted")
	return nil
}

func (v *Volume) removeFromSandbox() error {
	removed, err := v.tryRemoveFromSandbox()
	if err != nil {
		return err
	}
	if !removed {
		err := fmt.Errorf("volume is in use, could not be removed")
		v.Log(ERROR, err)
		return err
	}
	v.Log(INFO, "volume removed from sandbox")
	return nil
}

func (v *Volume) tryRemoveFromSandbox() (bool, error) {
	var (
		removed bool
		err     error
	)
	r := v.p.sandbox.RemoveVolume(v.spec.Name)
	removed = r.IsSuccess()
	if !removed && (r.Message() != "in use") {
		err = fmt.Errorf("failed to remove vol from sandbox: %s", r.Message())
		v.Log(ERROR, err)
	}

	if removed {
		v.Lock()
		v.status = S_VOLUME_CREATED
		v.Unlock()
	}
	v.Log(INFO, "volume remove from sandbox (removed: %v)", removed)
	return removed, err
}

// mount() should only called by add(), and not expose to outside
// the class.
func (v *Volume) mount() error {
	var (
		err error
	)

	v.Log(DEBUG, "mount volume")
	sharedDir := v.p.sandboxShareDir()
	v.descript, err = ProbeExistingVolume(v.spec, sharedDir)
	if err != nil {
		v.Log(ERROR, "volume probe/mount failed: %v", err)
		return err
	}

	return nil
}

func (v *Volume) umount() error {
	var err error
	if v.descript != nil {
		err = UmountExistingVolume(v.descript.Fstype, v.descript.Source, v.p.sandboxShareDir())
	}
	v.Lock()
	v.status = S_VOLUME_CREATED
	if err != nil {
		v.status = S_VOLUME_ERROR
	}
	v.Unlock()
	return err
}

func (v *Volume) subscribeInsert(wg *utils.WaitGroupWithFail) error {
	v.Log(TRACE, "subcribe volume insert")
	v.Lock()
	defer v.Unlock()
	if v.status == S_VOLUME_INSERTED {
		v.Log(DEBUG, "the subscribed volume has been inserted, need nothing.")
		return nil
	} else if v.status == S_VOLUME_ERROR {
		err := fmt.Errorf("volume %s is in ERROR state", v.spec.Name)
		v.Log(ERROR, err)
		return err
	}
	wg.Add(1)
	v.insertSubscribers = append(v.insertSubscribers, wg)
	v.Log(DEBUG, "subscribe the volume")
	return nil
}

func (v *Volume) transit(to VolumeState, from, ignore map[VolumeState]bool) (changed bool, err error) {
	v.Lock()
	changed, err = v.unlockedTransit(to, from, ignore)
	v.Unlock()
	return changed, err
}

func (v *Volume) setInserted() {
	v.Lock()
	//only from inserting to inserted
	v.unlockedTransit(S_VOLUME_INSERTED, map[VolumeState]bool{S_VOLUME_INSERTING: true}, map[VolumeState]bool{})
	if v.insertSubscribers != nil {
		for _, wg := range v.insertSubscribers {
			wg.Done()
		}
		v.insertSubscribers = []*utils.WaitGroupWithFail{}
	}
	v.Unlock()
}

func (v *Volume) setInsertFail(err error) {
	v.Lock()
	v.unlockedTransit(S_VOLUME_ERROR, map[VolumeState]bool{S_VOLUME_INSERTING: true}, map[VolumeState]bool{})
	if v.insertSubscribers != nil {
		for _, wg := range v.insertSubscribers {
			wg.Fail(err)
		}
		v.insertSubscribers = []*utils.WaitGroupWithFail{}
	}
	v.Unlock()
}

func (v *Volume) unlockedTransit(to VolumeState, from, ignore map[VolumeState]bool) (bool, error) {
	if ignore[v.status] || v.status == to {
		v.Log(DEBUG, "does not transit volume from state %v to %v, ignored", v.status, to)
		return false, nil
	} else if from[v.status] {
		v.Log(DEBUG, "transit volume from state %v to %v, ok", v.status, to)
		v.status = to
		return true, nil
	}
	err := fmt.Errorf("cannot transit volume from state %v to %v", v.status, to)
	v.Log(ERROR, err)
	return false, err
}


<|start_filename|>client/api/list.go<|end_filename|>
package api

import (
	"fmt"
	"net/url"
	"strings"

	"github.com/hyperhq/hyperd/engine"
)

func (cli *Client) GetContainerByPod(podId string) (string, error) {
	v := url.Values{}
	v.Set("item", "container")
	v.Set("pod", podId)
	body, _, err := readBody(cli.call("GET", "/list?"+v.Encode(), nil, nil))
	if err != nil {
		return "", err
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return "", err
	}

	if _, err := out.Write(body); err != nil {
		fmt.Printf("Error reading remote info: %s", err)
		return "", err
	}
	out.Close()
	var containerResponse = []string{}
	containerResponse = remoteInfo.GetList("cData")
	for _, c := range containerResponse {
		fields := strings.Split(c, ":")
		if len(fields) < 4 {
			fmt.Printf("can not parse container string: %s", c)
			continue
		}
		containerId := fields[0]
		if podId == fields[2] {
			return containerId, nil
		}
	}

	return "", fmt.Errorf("Container not found")
}

func (cli *Client) List(item, pod, vm string) (*engine.Env, error) {
	v := url.Values{}
	v.Set("item", item)
	if pod != "" {
		v.Set("pod", pod)
	}
	if vm != "" {
		v.Set("vm", vm)
	}
	body, _, err := readBody(cli.call("GET", "/list?"+v.Encode(), nil, nil))
	if err != nil {
		return nil, err
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return nil, err
	}

	if _, err := out.Write(body); err != nil {
		fmt.Printf("Error reading remote info: %s", err)
		return nil, err
	}
	out.Close()

	return remoteInfo, nil
}


<|start_filename|>client/api/attach.go<|end_filename|>
package api

import (
	"fmt"
	"io"
	"net/url"
)

func (cli *Client) Attach(container string, tty bool, stdin io.ReadCloser, stdout, stderr io.Writer) error {
	v := url.Values{}
	v.Set("container", container)

	err := cli.hijackRequest("attach", &v, tty, stdin, stdout, stderr)
	if err != nil {
		fmt.Printf("attach failed: %s\n", err.Error())
		return err
	}
	return nil
}
