Windows: Exec driver

Signed-off-by: John Howard <jhoward@microsoft.com>
This commit is contained in:
John Howard 2015-05-27 13:15:14 -07:00
parent 4893ecc112
commit 9ae9d4c87a
51 changed files with 3482 additions and 85 deletions

View file

@ -5,6 +5,7 @@ import (
"io"
"net/url"
"os"
"runtime"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/opts"
@ -103,6 +104,13 @@ func (cli *DockerCli) CmdRun(args ...string) error {
sigProxy = false
}
// Telling the Windows daemon the initial size of the tty during start makes
// a far better user experience rather than relying on subsequent resizes
// to cause things to catch up.
if runtime.GOOS == "windows" {
hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = cli.getTtySize()
}
createResponse, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
if err != nil {
return err

View file

@ -74,6 +74,7 @@ type CommonContainer struct {
MountLabel, ProcessLabel string
RestartCount int
UpdateDns bool
HasBeenStartedBefore bool
MountPoints map[string]*mountPoint
Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility
@ -286,6 +287,7 @@ func (container *Container) Run() error {
if err := container.Start(); err != nil {
return err
}
container.HasBeenStartedBefore = true
container.WaitStop(-1 * time.Second)
return nil
}

View file

@ -92,11 +92,12 @@ func populateCommand(c *Container, env []string) error {
// TODO Windows. Further refactoring required (privileged/user)
processConfig := execdriver.ProcessConfig{
Privileged: c.hostConfig.Privileged,
Entrypoint: c.Path,
Arguments: c.Args,
Tty: c.Config.Tty,
User: c.Config.User,
Privileged: c.hostConfig.Privileged,
Entrypoint: c.Path,
Arguments: c.Args,
Tty: c.Config.Tty,
User: c.Config.User,
ConsoleSize: c.hostConfig.ConsoleSize,
}
processConfig.Env = env
@ -116,6 +117,7 @@ func populateCommand(c *Container, env []string) error {
ProcessConfig: processConfig,
ProcessLabel: c.GetProcessLabel(),
MountLabel: c.GetMountLabel(),
FirstStart: !c.HasBeenStartedBefore,
}
return nil

View file

@ -138,13 +138,14 @@ type Mount struct {
type ProcessConfig struct {
exec.Cmd `json:"-"`
Privileged bool `json:"privileged"`
User string `json:"user"`
Tty bool `json:"tty"`
Entrypoint string `json:"entrypoint"`
Arguments []string `json:"arguments"`
Terminal Terminal `json:"-"` // standard or tty terminal
Console string `json:"-"` // dev/console path
Privileged bool `json:"privileged"`
User string `json:"user"`
Tty bool `json:"tty"`
Entrypoint string `json:"entrypoint"`
Arguments []string `json:"arguments"`
Terminal Terminal `json:"-"` // standard or tty terminal
Console string `json:"-"` // dev/console path
ConsoleSize [2]int `json:"-"` // h,w of initial console size
}
// TODO Windows: Factor out unused fields such as LxcConfig, AppArmorProfile,
@ -175,4 +176,7 @@ type Command struct {
LxcConfig []string `json:"lxc_config"`
AppArmorProfile string `json:"apparmor_profile"`
CgroupParent string `json:"cgroup_parent"` // The parent cgroup for this command.
FirstStart bool `json:"first_start"`
LayerPaths []string `json:"layer_paths"` // Windows needs to know the layer paths and folder for a command
LayerFolder string `json:"layer_folder"`
}

View file

@ -13,7 +13,7 @@ import (
func NewDriver(name string, options []string, root, libPath, initPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) {
switch name {
case "windows":
return windows.NewDriver(root, initPath)
return windows.NewDriver(root, initPath, options)
}
return nil, fmt.Errorf("unknown exec driver %s", name)
}

View file

@ -0,0 +1,36 @@
// +build windows
package windows
import (
"errors"
"github.com/docker/docker/daemon/execdriver"
)
func checkSupportedOptions(c *execdriver.Command) error {
// Windows doesn't support read-only root filesystem
if c.ReadonlyRootfs {
return errors.New("Windows does not support the read-only root filesystem option")
}
// Windows doesn't support username
if c.ProcessConfig.User != "" {
return errors.New("Windows does not support the username option")
}
// Windows doesn't support custom lxc options
if c.LxcConfig != nil {
return errors.New("Windows does not support lxc options")
}
// Windows doesn't support ulimit
if c.Resources.Rlimits != nil {
return errors.New("Windows does not support ulimit options")
}
// TODO Windows: Validate other fields which Windows doesn't support, factor
// out where applicable per platform.
return nil
}

View file

@ -0,0 +1,7 @@
// +build windows
package windows
func (d *driver) Clean(id string) error {
return nil
}

View file

@ -0,0 +1,144 @@
// +build windows
package windows
import (
"errors"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/daemon/execdriver"
"github.com/docker/docker/pkg/stringid"
"github.com/microsoft/hcsshim"
"github.com/natefinch/npipe"
)
func (d *driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
var (
inListen, outListen, errListen *npipe.PipeListener
term execdriver.Terminal
err error
randomID string = stringid.GenerateRandomID()
serverPipeFormat, clientPipeFormat string
pid uint32
exitCode int32
)
active := d.activeContainers[c.ID]
if active == nil {
return -1, fmt.Errorf("Exec - No active container exists with ID %s", c.ID)
}
createProcessParms := hcsshim.CreateProcessParams{
EmulateConsole: processConfig.Tty, // Note NOT c.ProcessConfig.Tty
WorkingDirectory: c.WorkingDir,
}
// Configure the environment for the process // Note NOT c.ProcessConfig.Tty
createProcessParms.Environment = setupEnvironmentVariables(processConfig.Env)
// We use another unique ID here for each exec instance otherwise it
// may conflict with the pipe name being used by RUN.
// We use a different pipe name between real and dummy mode in the HCS
if dummyMode {
clientPipeFormat = `\\.\pipe\docker-exec-%[1]s-%[2]s-%[3]s`
serverPipeFormat = clientPipeFormat
} else {
clientPipeFormat = `\\.\pipe\docker-exec-%[2]s-%[3]s`
serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-exec-%[2]s-%[3]s`
}
// Connect stdin
if pipes.Stdin != nil {
stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stdin")
createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stdin")
// Listen on the named pipe
inListen, err = npipe.Listen(stdInPipe)
if err != nil {
logrus.Errorf("stdin failed to listen on %s %s ", stdInPipe, err)
return -1, err
}
defer inListen.Close()
// Launch a goroutine to do the accept. We do this so that we can
// cause an otherwise blocking goroutine to gracefully close when
// the caller (us) closes the listener
go stdinAccept(inListen, stdInPipe, pipes.Stdin)
}
// Connect stdout
stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stdout")
createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stdout")
outListen, err = npipe.Listen(stdOutPipe)
if err != nil {
logrus.Errorf("stdout failed to listen on %s %s", stdOutPipe, err)
return -1, err
}
defer outListen.Close()
go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout)
// No stderr on TTY. Note NOT c.ProcessConfig.Tty
if !processConfig.Tty {
// Connect stderr
stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stderr")
createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stderr")
errListen, err = npipe.Listen(stdErrPipe)
if err != nil {
logrus.Errorf("Stderr failed to listen on %s %s", stdErrPipe, err)
return -1, err
}
defer errListen.Close()
go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr)
}
// While this should get caught earlier, just in case, validate that we
// have something to run.
if processConfig.Entrypoint == "" {
err = errors.New("No entrypoint specified")
logrus.Error(err)
return -1, err
}
// Build the command line of the process
createProcessParms.CommandLine = processConfig.Entrypoint
for _, arg := range processConfig.Arguments {
logrus.Debugln("appending ", arg)
createProcessParms.CommandLine += " " + arg
}
logrus.Debugln("commandLine: ", createProcessParms.CommandLine)
// Start the command running in the container.
pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms)
if err != nil {
logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
return -1, err
}
// Note NOT c.ProcessConfig.Tty
if processConfig.Tty {
term = NewTtyConsole(c.ID, pid)
} else {
term = NewStdConsole()
}
processConfig.Terminal = term
// Invoke the start callback
if startCallback != nil {
startCallback(&c.ProcessConfig, int(pid))
}
if exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid); err != nil {
logrus.Errorf("Failed to WaitForProcessInComputeSystem %s", err)
return -1, err
}
// TODO Windows - Do something with this exit code
logrus.Debugln("Exiting Run() with ExitCode 0", c.ID)
return int(exitCode), nil
}

View file

@ -0,0 +1,10 @@
// +build windows
package windows
import "fmt"
func (d *driver) GetPidsForContainer(id string) ([]int, error) {
// TODO Windows: Implementation required.
return nil, fmt.Errorf("GetPidsForContainer: GetPidsForContainer() not implemented")
}

View file

@ -0,0 +1,23 @@
// +build windows
package windows
import "github.com/docker/docker/daemon/execdriver"
type info struct {
ID string
driver *driver
}
func (d *driver) Info(id string) execdriver.Info {
return &info{
ID: id,
driver: d,
}
}
func (i *info) IsRunning() bool {
var running bool
running = true // TODO Need an HCS API
return running
}

View file

@ -0,0 +1,82 @@
// +build windows
package windows
import (
"io"
"github.com/Sirupsen/logrus"
"github.com/natefinch/npipe"
)
// stdinAccept runs as a go function. It waits for the container system
// to accept our offer of a named pipe for stdin. Once accepted, if we are
// running "attached" to the container (eg docker run -i), then we spin up
// a further thread to copy anything from the client into the container.
//
// Important design note. This function is run as a go function for a very
// good reason. The named pipe Accept call is blocking until one of two things
// happen. Either someone connects to it, or it is forcibly closed. Let's
// assume that no-one connects to it, the only way otherwise the Run()
// method would continue is by closing it. However, as that would be the same
// thread, it can't close it. Hence we run as another thread allowing Run()
// to close the named pipe.
func stdinAccept(inListen *npipe.PipeListener, pipeName string, copyfrom io.ReadCloser) {
// Wait for the pipe to be connected to by the shim
logrus.Debugln("stdinAccept: Waiting on ", pipeName)
stdinConn, err := inListen.Accept()
if err != nil {
logrus.Errorf("Failed to accept on pipe %s %s", pipeName, err)
return
}
logrus.Debugln("Connected to ", stdinConn.RemoteAddr())
// Anything that comes from the client stdin should be copied
// across to the stdin named pipe of the container.
if copyfrom != nil {
go func() {
defer stdinConn.Close()
logrus.Debugln("Calling io.Copy on stdin")
bytes, err := io.Copy(stdinConn, copyfrom)
logrus.Debugf("Finished io.Copy on stdin bytes=%d err=%s pipe=%s", bytes, err, stdinConn.RemoteAddr())
}()
} else {
defer stdinConn.Close()
}
}
// stdouterrAccept runs as a go function. It waits for the container system to
// accept our offer of a named pipe - in fact two of them - one for stdout
// and one for stderr (we are called twice). Once the named pipe is accepted,
// if we are running "attached" to the container (eg docker run -i), then we
// spin up a further thread to copy anything from the containers output channels
// to the client.
func stdouterrAccept(outerrListen *npipe.PipeListener, pipeName string, copyto io.Writer) {
// Wait for the pipe to be connected to by the shim
logrus.Debugln("out/err: Waiting on ", pipeName)
outerrConn, err := outerrListen.Accept()
if err != nil {
logrus.Errorf("Failed to accept on pipe %s %s", pipeName, err)
return
}
logrus.Debugln("Connected to ", outerrConn.RemoteAddr())
// Anything that comes from the container named pipe stdout/err should be copied
// across to the stdout/err of the client
if copyto != nil {
go func() {
defer outerrConn.Close()
logrus.Debugln("Calling io.Copy on ", pipeName)
bytes, err := io.Copy(copyto, outerrConn)
logrus.Debugf("Copied %d bytes from pipe=%s", bytes, outerrConn.RemoteAddr())
if err != nil {
// Not fatal, just debug log it
logrus.Debugf("Error hit during copy %s", err)
}
}()
} else {
defer outerrConn.Close()
}
}

View file

@ -0,0 +1,17 @@
// +build windows
package windows
import (
"fmt"
"github.com/docker/docker/daemon/execdriver"
)
func (d *driver) Pause(c *execdriver.Command) error {
return fmt.Errorf("Windows: Containers cannot be paused")
}
func (d *driver) Unpause(c *execdriver.Command) error {
return fmt.Errorf("Windows: Containers cannot be paused")
}

View file

@ -0,0 +1,271 @@
// +build windows
package windows
// Note this is alpha code for the bring up of containers on Windows.
import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/daemon/execdriver"
"github.com/microsoft/hcsshim"
"github.com/natefinch/npipe"
)
type layer struct {
Id string
Path string
}
type defConfig struct {
DefFile string
}
type networkConnection struct {
NetworkName string
EnableNat bool
}
type networkSettings struct {
MacAddress string
}
type device struct {
DeviceType string
Connection interface{}
Settings interface{}
}
type containerInit struct {
SystemType string
Name string
IsDummy bool
VolumePath string
Devices []device
IgnoreFlushesDuringBoot bool
LayerFolderPath string
Layers []layer
}
func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
var (
term execdriver.Terminal
err error
inListen, outListen, errListen *npipe.PipeListener
)
// Make sure the client isn't asking for options which aren't supported
err = checkSupportedOptions(c)
if err != nil {
return execdriver.ExitStatus{ExitCode: -1}, err
}
cu := &containerInit{
SystemType: "Container",
Name: c.ID,
IsDummy: dummyMode,
VolumePath: c.Rootfs,
IgnoreFlushesDuringBoot: c.FirstStart,
LayerFolderPath: c.LayerFolder,
}
for i := 0; i < len(c.LayerPaths); i++ {
cu.Layers = append(cu.Layers, layer{
Id: hcsshim.NewGUID(c.LayerPaths[i]).ToString(),
Path: c.LayerPaths[i],
})
}
if c.Network.Interface != nil {
// TODO Windows: Temporary
c.Network.Interface.Bridge = "Virtual Switch"
dev := device{
DeviceType: "Network",
Connection: &networkConnection{
NetworkName: c.Network.Interface.Bridge,
EnableNat: false,
},
}
if c.Network.Interface.MacAddress != "" {
windowsStyleMAC := strings.Replace(
c.Network.Interface.MacAddress, ":", "-", -1)
dev.Settings = networkSettings{
MacAddress: windowsStyleMAC,
}
}
cu.Devices = append(cu.Devices, dev)
}
configurationb, err := json.Marshal(cu)
if err != nil {
return execdriver.ExitStatus{ExitCode: -1}, err
}
configuration := string(configurationb)
err = hcsshim.CreateComputeSystem(c.ID, configuration)
if err != nil {
logrus.Debugln("Failed to create temporary container ", err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
// Start the container
logrus.Debugln("Starting container ", c.ID)
err = hcsshim.StartComputeSystem(c.ID)
if err != nil {
logrus.Errorf("Failed to start compute system: %s", err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
defer func() {
// Stop the container
if terminateMode {
logrus.Debugf("Terminating container %s", c.ID)
if err := hcsshim.TerminateComputeSystem(c.ID); err != nil {
// IMPORTANT: Don't fail if fails to change state. It could already
// have been stopped through kill().
// Otherwise, the docker daemon will hang in job wait()
logrus.Warnf("Ignoring error from TerminateComputeSystem %s", err)
}
} else {
logrus.Debugf("Shutting down container %s", c.ID)
if err := hcsshim.ShutdownComputeSystem(c.ID); err != nil {
// IMPORTANT: Don't fail if fails to change state. It could already
// have been stopped through kill().
// Otherwise, the docker daemon will hang in job wait()
logrus.Warnf("Ignoring error from ShutdownComputeSystem %s", err)
}
}
}()
// We use a different pipe name between real and dummy mode in the HCS
var serverPipeFormat, clientPipeFormat string
if dummyMode {
clientPipeFormat = `\\.\pipe\docker-run-%[1]s-%[2]s`
serverPipeFormat = clientPipeFormat
} else {
clientPipeFormat = `\\.\pipe\docker-run-%[2]s`
serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-run-%[2]s`
}
createProcessParms := hcsshim.CreateProcessParams{
EmulateConsole: c.ProcessConfig.Tty,
WorkingDirectory: c.WorkingDir,
ConsoleSize: c.ProcessConfig.ConsoleSize,
}
// Configure the environment for the process
createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env)
// Connect stdin
if pipes.Stdin != nil {
stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdin")
createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdin")
// Listen on the named pipe
inListen, err = npipe.Listen(stdInPipe)
if err != nil {
logrus.Errorf("stdin failed to listen on %s err=%s", stdInPipe, err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
defer inListen.Close()
// Launch a goroutine to do the accept. We do this so that we can
// cause an otherwise blocking goroutine to gracefully close when
// the caller (us) closes the listener
go stdinAccept(inListen, stdInPipe, pipes.Stdin)
}
// Connect stdout
stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdout")
createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdout")
outListen, err = npipe.Listen(stdOutPipe)
if err != nil {
logrus.Errorf("stdout failed to listen on %s err=%s", stdOutPipe, err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
defer outListen.Close()
go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout)
// No stderr on TTY.
if !c.ProcessConfig.Tty {
// Connect stderr
stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stderr")
createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stderr")
errListen, err = npipe.Listen(stdErrPipe)
if err != nil {
logrus.Errorf("stderr failed to listen on %s err=%s", stdErrPipe, err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
defer errListen.Close()
go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr)
}
// This should get caught earlier, but just in case - validate that we
// have something to run
if c.ProcessConfig.Entrypoint == "" {
err = errors.New("No entrypoint specified")
logrus.Error(err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
// Build the command line of the process
createProcessParms.CommandLine = c.ProcessConfig.Entrypoint
for _, arg := range c.ProcessConfig.Arguments {
logrus.Debugln("appending ", arg)
createProcessParms.CommandLine += " " + arg
}
logrus.Debugf("CommandLine: %s", createProcessParms.CommandLine)
// Start the command running in the container.
var pid uint32
pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms)
if err != nil {
logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
//Save the PID as we'll need this in Kill()
logrus.Debugf("PID %d", pid)
c.ContainerPid = int(pid)
if c.ProcessConfig.Tty {
term = NewTtyConsole(c.ID, pid)
} else {
term = NewStdConsole()
}
c.ProcessConfig.Terminal = term
// Maintain our list of active containers. We'll need this later for exec
// and other commands.
d.Lock()
d.activeContainers[c.ID] = &activeContainer{
command: c,
}
d.Unlock()
// Invoke the start callback
if startCallback != nil {
startCallback(&c.ProcessConfig, int(pid))
}
var exitCode int32
exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid)
if err != nil {
logrus.Errorf("Failed to WaitForProcessInComputeSystem %s", err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
logrus.Debugf("Exiting Run() exitCode %d id=%s", exitCode, c.ID)
return execdriver.ExitStatus{ExitCode: int(exitCode)}, nil
}

View file

@ -0,0 +1,13 @@
// +build windows
package windows
import (
"fmt"
"github.com/docker/docker/daemon/execdriver"
)
func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) {
return nil, fmt.Errorf("Windows: Stats not implemented")
}

View file

@ -0,0 +1,21 @@
// +build windows
package windows
// StdConsole is for when using a container non-interactively
type StdConsole struct {
}
func NewStdConsole() *StdConsole {
return &StdConsole{}
}
func (s *StdConsole) Resize(h, w int) error {
// we do not need to resize a non tty
return nil
}
func (s *StdConsole) Close() error {
// nothing to close here
return nil
}

View file

@ -0,0 +1,45 @@
// +build windows
package windows
import (
"github.com/Sirupsen/logrus"
"github.com/docker/docker/daemon/execdriver"
"github.com/microsoft/hcsshim"
)
func (d *driver) Terminate(p *execdriver.Command) error {
logrus.Debugf("WindowsExec: Terminate() id=%s", p.ID)
return kill(p.ID, p.ContainerPid)
}
func (d *driver) Kill(p *execdriver.Command, sig int) error {
logrus.Debugf("WindowsExec: Kill() id=%s sig=%d", p.ID, sig)
return kill(p.ID, p.ContainerPid)
}
func kill(id string, pid int) error {
logrus.Debugln("kill() ", id, pid)
var err error
// Terminate Process
if err = hcsshim.TerminateProcessInComputeSystem(id, uint32(pid)); err != nil {
logrus.Warnf("Failed to terminate pid %d in %s", id, pid, err)
// Ignore errors
err = nil
}
if terminateMode {
// Terminate the compute system
if err = hcsshim.TerminateComputeSystem(id); err != nil {
logrus.Errorf("Failed to terminate %s - %s", id, err)
}
} else {
// Shutdown the compute system
if err = hcsshim.TerminateComputeSystem(id); err != nil {
logrus.Errorf("Failed to shutdown %s - %s", id, err)
}
}
return err
}

View file

@ -0,0 +1,31 @@
// +build windows
package windows
import (
"github.com/microsoft/hcsshim"
)
// TtyConsole is for when using a container interactively
type TtyConsole struct {
id string
processid uint32
}
func NewTtyConsole(id string, processid uint32) *TtyConsole {
tty := &TtyConsole{
id: id,
processid: processid,
}
return tty
}
func (t *TtyConsole) Resize(h, w int) error {
// TODO Windows: This is not implemented in HCS. Needs plumbing through
// along with mechanism for buffering
return hcsshim.ResizeConsoleInComputeSystem(t.id, t.processid, h, w)
}
func (t *TtyConsole) Close() error {
return nil
}

View file

@ -1,23 +1,28 @@
// +build windows
/*
This is the Windows driver for containers.
TODO Windows: It is currently a placeholder to allow compilation of the
daemon. Future PRs will have an implementation of this driver.
*/
package windows
import (
"fmt"
"strings"
"sync"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/autogen/dockerversion"
"github.com/docker/docker/daemon/execdriver"
"github.com/docker/docker/pkg/parsers"
)
const (
DriverName = "Windows"
Version = "Placeholder"
// This is a daemon development variable only and should not be
// used for running production containers on Windows.
var dummyMode bool
// This allows the daemon to terminate containers rather than shutdown
var terminateMode bool
var (
DriverName = "Windows 1854"
Version = dockerversion.VERSION + " " + dockerversion.GITCOMMIT
)
type activeContainer struct {
@ -25,73 +30,61 @@ type activeContainer struct {
}
type driver struct {
root string
initPath string
}
type info struct {
ID string
driver *driver
}
func NewDriver(root, initPath string) (*driver, error) {
return &driver{
root: root,
initPath: initPath,
}, nil
}
func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
return execdriver.ExitStatus{ExitCode: 0}, nil
}
func (d *driver) Terminate(p *execdriver.Command) error {
return nil
}
func (d *driver) Kill(p *execdriver.Command, sig int) error {
return nil
}
func kill(ID string, PID int) error {
return nil
}
func (d *driver) Pause(c *execdriver.Command) error {
return fmt.Errorf("Windows: Containers cannot be paused")
}
func (d *driver) Unpause(c *execdriver.Command) error {
return fmt.Errorf("Windows: Containers cannot be paused")
}
func (i *info) IsRunning() bool {
return false
}
func (d *driver) Info(id string) execdriver.Info {
return &info{
ID: id,
driver: d,
}
root string
initPath string
activeContainers map[string]*activeContainer
sync.Mutex
}
func (d *driver) Name() string {
return fmt.Sprintf("%s Date %s", DriverName, Version)
return fmt.Sprintf("%s %s", DriverName, Version)
}
func (d *driver) GetPidsForContainer(id string) ([]int, error) {
return nil, fmt.Errorf("GetPidsForContainer: GetPidsForContainer() not implemented")
func NewDriver(root, initPath string, options []string) (*driver, error) {
for _, option := range options {
key, val, err := parsers.ParseKeyValueOpt(option)
if err != nil {
return nil, err
}
key = strings.ToLower(key)
switch key {
case "dummy":
switch val {
case "1":
dummyMode = true
logrus.Warn("Using dummy mode in Windows exec driver. This is for development use only!")
}
case "terminate":
switch val {
case "1":
terminateMode = true
logrus.Warn("Using terminate mode in Windows exec driver. This is for testing purposes only.")
}
default:
return nil, fmt.Errorf("Unrecognised exec driver option %s\n", key)
}
}
return &driver{
root: root,
initPath: initPath,
activeContainers: make(map[string]*activeContainer),
}, nil
}
func (d *driver) Clean(id string) error {
return nil
}
func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) {
return nil, fmt.Errorf("Windows: Stats not implemented")
}
func (d *driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
return 0, nil
// setupEnvironmentVariables convert a string array of environment variables
// into a map as required by the HCS. Source array is in format [v1=k1] [v2=k2] etc.
func setupEnvironmentVariables(a []string) map[string]string {
r := make(map[string]string)
for _, s := range a {
arr := strings.Split(s, "=")
if len(arr) == 2 {
r[arr[0]] = arr[1]
}
}
return r
}

View file

@ -12,7 +12,9 @@ clone git github.com/go-check/check 64131543e7896d5bcc6bd5a76287eb75ea96c673
clone git github.com/gorilla/context 14f550f51a
clone git github.com/gorilla/mux e444e69cbd
clone git github.com/kr/pty 5cf931ef8f
clone git github.com/microsoft/hcsshim 2f540b26beafc3d4aded4fc9799af261a1a91352
clone git github.com/mistifyio/go-zfs v2.1.1
clone git github.com/natefinch/npipe 0938d701e50e580f5925c773055eb6d6b32a0cbc
clone git github.com/tchap/go-patricia v2.1.0
clone git golang.org/x/net 3cffabab72adf04f8e3b01c5baf775361837b5fe https://github.com/golang/net.git
clone hg code.google.com/p/gosqlite 74691fb6f837

View file

@ -254,6 +254,7 @@ type HostConfig struct {
Ulimits []*ulimit.Ulimit
LogConfig LogConfig
CgroupParent string // Parent cgroup.
ConsoleSize [2]int // Initial console size on Windows
}
func MergeConfigs(config *Config, hostConfig *HostConfig) *ContainerConfigWrapper {

View file

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,57 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func ActivateLayer(info DriverInfo, id string) error {
title := "hcsshim::ActivateLayer "
logrus.Debugf(title+"Flavour %s ID %s", info.Flavour, id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procActivateLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(idp)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s flavour=%d",
r1, syscall.Errno(r1), id, info.Flavour)
logrus.Error(err)
return err
}
logrus.Debugf(title+" - succeeded id=%s flavour=%d", id, info.Flavour)
return nil
}

View file

@ -0,0 +1,85 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func CopyLayer(info DriverInfo, srcId, dstId string, parentLayerPaths []string) error {
title := "hcsshim::CopyLayer "
logrus.Debugf(title+"srcId %s dstId", srcId, dstId)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procCopyLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert srcId to uint16 pointer for calling the procedure
srcIdp, err := syscall.UTF16PtrFromString(srcId)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of srcId %s to pointer %s", srcId, err)
logrus.Error(err)
return err
}
// Convert dstId to uint16 pointer for calling the procedure
dstIdp, err := syscall.UTF16PtrFromString(dstId)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of dstId %s to pointer %s", dstId, err)
logrus.Error(err)
return err
}
// Generate layer descriptors
layers, err := layerPathsToDescriptors(parentLayerPaths)
if err != nil {
err = fmt.Errorf(title+" - Failed to generate layer descriptors %s", err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
var layerDescriptorsp *WC_LAYER_DESCRIPTOR
if len(layers) > 0 {
layerDescriptorsp = &(layers[0])
} else {
layerDescriptorsp = nil
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(srcIdp)),
uintptr(unsafe.Pointer(dstIdp)),
uintptr(unsafe.Pointer(layerDescriptorsp)),
uintptr(len(layers)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(srcIdp))
use(unsafe.Pointer(dstIdp))
use(unsafe.Pointer(layerDescriptorsp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s srcId=%s dstId=%d",
r1, syscall.Errno(r1), srcId, dstId)
logrus.Error(err)
return err
}
logrus.Debugf(title+" - succeeded srcId=%s dstId=%s", srcId, dstId)
return nil
}

View file

@ -0,0 +1,70 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
// CreateComputeSystem creates a container
func CreateComputeSystem(id string, configuration string) error {
title := "HCSShim::CreateComputeSystem"
logrus.Debugln(title+" id=%s, configuration=%s", id, configuration)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procCreateComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
/*
Example configuration JSON below. RootDevicePath MUST use \\ not \ as path
separator. TODO Windows: Update this JSON sample with final API.
{
"SystemType" : "Container",
"Name" : "ContainerName",
"RootDevicePath" : "C:\\Containers\\test",
"IsDummy" : true
}
*/
// Convert id to uint16 pointers for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
// Convert configuration to uint16 pointers for calling the procedure
configurationp, err := syscall.UTF16PtrFromString(configuration)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of configuration %s to pointer %s", configuration, err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(idp)), uintptr(unsafe.Pointer(configurationp)))
use(unsafe.Pointer(idp))
use(unsafe.Pointer(configurationp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s configuration=%s", r1, syscall.Errno(r1), id, configuration)
logrus.Error(err)
return err
}
logrus.Debugf(title+"- succeeded %s", id)
return nil
}

View file

@ -0,0 +1,67 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func CreateLayer(info DriverInfo, id, parent string) error {
title := "hcsshim::CreateLayer "
logrus.Debugf(title+"Flavour %s ID %s parent %s", info.Flavour, id, parent)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procCreateLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
// Convert parent to uint16 pointer for calling the procedure
parentp, err := syscall.UTF16PtrFromString(parent)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of parent %s to pointer %s", parent, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion info struct %s", parent, err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(idp)),
uintptr(unsafe.Pointer(parentp)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(idp))
use(unsafe.Pointer(parentp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s parent=%s flavour=%d",
r1, syscall.Errno(r1), id, parent, info.Flavour)
logrus.Error(err)
return err
}
logrus.Debugf(title+" - succeeded id=%s parent=%s flavour=%d", id, parent, info.Flavour)
return nil
}

View file

@ -0,0 +1,89 @@
package hcsshim
import (
"encoding/json"
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
// processParameters is use to both the input of CreateProcessInComputeSystem
// and to convert the parameters to JSON for passing onto the HCS
type CreateProcessParams struct {
ApplicationName string
CommandLine string
WorkingDirectory string
StdInPipe, StdOutPipe, StdErrPipe string
Environment map[string]string
EmulateConsole bool
ConsoleSize [2]int
}
// CreateProcessInComputeSystem starts a process in a container. This is invoked, for example,
// as a result of docker run, docker exec, or RUN in Dockerfile. If successful,
// it returns the PID of the process.
func CreateProcessInComputeSystem(id string, params CreateProcessParams) (processid uint32, err error) {
title := "HCSShim::CreateProcessInComputeSystem"
logrus.Debugf(title+"id=%s params=%s", id, params)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procCreateProcessInComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return 0, err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return 0, err
}
// If we are not emulating a console, ignore any console size passed to us
if !params.EmulateConsole {
params.ConsoleSize[0] = 0
params.ConsoleSize[1] = 0
}
paramsJson, err := json.Marshal(params)
if err != nil {
err = fmt.Errorf(title+" - Failed to marshall params %s %s", params, err)
return 0, err
}
// Convert paramsJson to uint16 pointer for calling the procedure
paramsJsonp, err := syscall.UTF16PtrFromString(string(paramsJson))
if err != nil {
return 0, err
}
// Get a POINTER to variable to take the pid outparm
pid := new(uint32)
logrus.Debugf(title+" - Calling the procedure itself %s %s", id, paramsJson)
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(idp)),
uintptr(unsafe.Pointer(paramsJsonp)),
uintptr(unsafe.Pointer(pid)))
use(unsafe.Pointer(idp))
use(unsafe.Pointer(paramsJsonp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s params=%s", r1, syscall.Errno(r1), id, params)
logrus.Error(err)
return 0, err
}
logrus.Debugf(title+" - succeeded id=%s params=%s pid=%d", id, paramsJson, *pid)
return *pid, nil
}

View file

@ -0,0 +1,84 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func CreateSandboxLayer(info DriverInfo, layerId, parentId string, parentLayerPaths []string) error {
title := "hcsshim::CreateSandboxLayer "
logrus.Debugf(title+"layerId %s parentId %s", layerId, parentId)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procCreateSandboxLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Generate layer descriptors
layers, err := layerPathsToDescriptors(parentLayerPaths)
if err != nil {
err = fmt.Errorf(title+"- Failed to generate layer descriptors ", err)
return err
}
// Convert layerId to uint16 pointer for calling the procedure
layerIdp, err := syscall.UTF16PtrFromString(layerId)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of layerId %s to pointer %s", layerId, err)
logrus.Error(err)
return err
}
// Convert parentId to uint16 pointer for calling the procedure
parentIdp, err := syscall.UTF16PtrFromString(parentId)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of parentId %s to pointer %s", parentId, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
var layerDescriptorsp *WC_LAYER_DESCRIPTOR
if len(layers) > 0 {
layerDescriptorsp = &(layers[0])
} else {
layerDescriptorsp = nil
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(layerIdp)),
uintptr(unsafe.Pointer(parentIdp)),
uintptr(unsafe.Pointer(layerDescriptorsp)),
uintptr(len(layers)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(layerIdp))
use(unsafe.Pointer(parentIdp))
use(unsafe.Pointer(layerDescriptorsp))
if r1 != 0 {
err = fmt.Errorf(title+"- Win32 API call returned error r1=%d err=%s layerId=%s parentId=%s",
r1, syscall.Errno(r1), layerId, parentId)
logrus.Error(err)
return err
}
logrus.Debugf(title+"- succeeded layerId=%s parentId=%s", layerId, parentId)
return nil
}

View file

@ -0,0 +1,57 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func DeactivateLayer(info DriverInfo, id string) error {
title := "hcsshim::DeactivateLayer "
logrus.Debugf(title+"Flavour %s ID %s", info.Flavour, id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procDeactivateLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(idp)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s flavour=%d",
r1, syscall.Errno(r1), id, info.Flavour)
logrus.Error(err)
return err
}
logrus.Debugf(title+" - succeeded id=%s flavour=%d", id, info.Flavour)
return nil
}

View file

@ -0,0 +1,57 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func DestroyLayer(info DriverInfo, id string) error {
title := "hcsshim::DestroyLayer "
logrus.Debugf(title+"Flavour %s ID %s", info.Flavour, id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procDestroyLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(idp)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s flavour=%d",
r1, syscall.Errno(r1), id, info.Flavour)
logrus.Error(err)
return err
}
logrus.Debugf(title+" - succeeded id=%s flavour=%d", id, info.Flavour)
return nil
}

View file

@ -0,0 +1,83 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func ExportLayer(info DriverInfo, layerId string, exportFolderPath string, parentLayerPaths []string) error {
title := "hcsshim::ExportLayer "
logrus.Debugf(title+"flavour %d layerId %s folder %s", info.Flavour, layerId, exportFolderPath)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procExportLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Generate layer descriptors
layers, err := layerPathsToDescriptors(parentLayerPaths)
if err != nil {
err = fmt.Errorf(title+"- Failed to generate layer descriptors ", err)
return err
}
// Convert layerId to uint16 pointer for calling the procedure
layerIdp, err := syscall.UTF16PtrFromString(layerId)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of layerId %s to pointer %s", layerId, err)
logrus.Error(err)
return err
}
// Convert exportFolderPath to uint16 pointer for calling the procedure
exportFolderPathp, err := syscall.UTF16PtrFromString(exportFolderPath)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of exportFolderPath %s to pointer %s", exportFolderPath, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
var layerDescriptorsp *WC_LAYER_DESCRIPTOR
if len(layers) > 0 {
layerDescriptorsp = &(layers[0])
} else {
layerDescriptorsp = nil
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(layerIdp)),
uintptr(unsafe.Pointer(exportFolderPathp)),
uintptr(unsafe.Pointer(layerDescriptorsp)),
uintptr(len(layers)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(layerIdp))
use(unsafe.Pointer(exportFolderPathp))
use(unsafe.Pointer(layerDescriptorsp))
if r1 != 0 {
err = fmt.Errorf(title+"- Win32 API call returned error r1=%d err=%s layerId=%s flavour=%d folder=%s",
r1, syscall.Errno(r1), layerId, info.Flavour, exportFolderPath)
logrus.Error(err)
return err
}
logrus.Debugf(title+"- succeeded layerId=%s flavour=%d folder=%s", layerId, info.Flavour, exportFolderPath)
return nil
}

View file

@ -0,0 +1,87 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func GetLayerMountPath(info DriverInfo, id string) (string, error) {
title := "hcsshim::GetLayerMountPath "
logrus.Debugf(title+"Flavour %s ID %s", info.Flavour, id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procGetLayerMountPath)
if dll != nil {
defer dll.Release()
}
if err != nil {
return "", err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return "", err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion info struct %s", err)
logrus.Error(err)
return "", err
}
var mountPathLength uint64
mountPathLength = 0
// Call the procedure itself.
logrus.Debugf("Calling proc (1)")
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(idp)),
uintptr(unsafe.Pointer(&mountPathLength)),
uintptr(unsafe.Pointer(nil)))
if r1 != 0 {
err = fmt.Errorf(title+" - First Win32 API call returned error r1=%d err=%s id=%s flavour=%d",
r1, syscall.Errno(r1), id, info.Flavour)
logrus.Error(err)
return "", err
}
// Allocate a mount path of the returned length.
if mountPathLength == 0 {
return "", nil
}
mountPathp := make([]uint16, mountPathLength)
mountPathp[0] = 0
// Call the procedure again
logrus.Debugf("Calling proc (2)")
r1, _, _ = proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(idp)),
uintptr(unsafe.Pointer(&mountPathLength)),
uintptr(unsafe.Pointer(&mountPathp[0])))
use(unsafe.Pointer(&mountPathLength))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Second Win32 API call returned error r1=%d errno=%d id=%s flavour=%d",
r1, syscall.Errno(r1), id, info.Flavour)
logrus.Error(err)
return "", err
}
path := syscall.UTF16ToString(mountPathp[0:])
logrus.Debugf(title+" - succeeded id=%s flavour=%d path=%s", id, info.Flavour, path)
return path, nil
}

View file

@ -0,0 +1,19 @@
package hcsshim
import (
"crypto/sha1"
"fmt"
)
type GUID [16]byte
func NewGUID(source string) *GUID {
h := sha1.Sum([]byte(source))
var g GUID
copy(g[0:], h[0:16])
return &g
}
func (g *GUID) ToString() string {
return fmt.Sprintf("%x-%x-%x-%x-%x", g[0:4], g[4:6], g[6:8], g[8:10], g[10:])
}

View file

@ -0,0 +1,80 @@
// Shim for the Host Compute Service (HSC) to manage Windows Server
// containers and Hyper-V containers.
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
const (
// Name of the shim DLL for access to the HCS
shimDLLName = "vmcompute.dll"
// Container related functions in the shim DLL
procCreateComputeSystem = "CreateComputeSystem"
procStartComputeSystem = "StartComputeSystem"
procCreateProcessInComputeSystem = "CreateProcessInComputeSystem"
procWaitForProcessInComputeSystem = "WaitForProcessInComputeSystem"
procShutdownComputeSystem = "ShutdownComputeSystem"
procTerminateComputeSystem = "TerminateComputeSystem"
procTerminateProcessInComputeSystem = "TerminateProcessInComputeSystem"
procResizeConsoleInComputeSystem = "ResizeConsoleInComputeSystem"
// Storage related functions in the shim DLL
procLayerExists = "LayerExists"
procCreateLayer = "CreateLayer"
procDestroyLayer = "DestroyLayer"
procActivateLayer = "ActivateLayer"
procDeactivateLayer = "DeactivateLayer"
procGetLayerMountPath = "GetLayerMountPath"
procCopyLayer = "CopyLayer"
procCreateSandboxLayer = "CreateSandboxLayer"
procPrepareLayer = "PrepareLayer"
procUnprepareLayer = "UnprepareLayer"
procExportLayer = "ExportLayer"
procImportLayer = "ImportLayer"
)
// loadAndFind finds a procedure in the DLL. Note we do NOT do lazy loading as
// go is particularly unfriendly in the case of a mismatch. By that - it panics
// if a function can't be found. By explicitly loading, we can control error
// handling gracefully without the daemon terminating.
func loadAndFind(procedure string) (dll *syscall.DLL, proc *syscall.Proc, err error) {
logrus.Debugf("hcsshim::loadAndFind %s", procedure)
dll, err = syscall.LoadDLL(shimDLLName)
if err != nil {
err = fmt.Errorf("Failed to load %s - error %s", shimDLLName, err)
logrus.Error(err)
return nil, nil, err
}
proc, err = dll.FindProc(procedure)
if err != nil {
err = fmt.Errorf("Failed to find %s in %s", procedure, shimDLLName)
logrus.Error(err)
return nil, nil, err
}
return dll, proc, nil
}
// use is a no-op, but the compiler cannot see that it is.
// Calling use(p) ensures that p is kept live until that point.
/*
//go:noescape
func use(p unsafe.Pointer)
*/
// Alternate without using //go:noescape and asm.s
var temp unsafe.Pointer
func use(p unsafe.Pointer) {
temp = p
}

View file

@ -0,0 +1,83 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func ImportLayer(info DriverInfo, layerId string, importFolderPath string, parentLayerPaths []string) error {
title := "hcsshim::ImportLayer "
logrus.Debugf(title+"flavour %d layerId %s folder %s", info.Flavour, layerId, importFolderPath)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procImportLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Generate layer descriptors
layers, err := layerPathsToDescriptors(parentLayerPaths)
if err != nil {
err = fmt.Errorf(title+"- Failed to generate layer descriptors ", err)
return err
}
// Convert layerId to uint16 pointer for calling the procedure
layerIdp, err := syscall.UTF16PtrFromString(layerId)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of layerId %s to pointer %s", layerId, err)
logrus.Error(err)
return err
}
// Convert importFolderPath to uint16 pointer for calling the procedure
importFolderPathp, err := syscall.UTF16PtrFromString(importFolderPath)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of importFolderPath %s to pointer %s", importFolderPath, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
var layerDescriptorsp *WC_LAYER_DESCRIPTOR
if len(layers) > 0 {
layerDescriptorsp = &(layers[0])
} else {
layerDescriptorsp = nil
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(layerIdp)),
uintptr(unsafe.Pointer(importFolderPathp)),
uintptr(unsafe.Pointer(layerDescriptorsp)),
uintptr(len(layers)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(layerIdp))
use(unsafe.Pointer(importFolderPathp))
use(unsafe.Pointer(layerDescriptorsp))
if r1 != 0 {
err = fmt.Errorf(title+"- Win32 API call returned error r1=%d err=%s layerId=%s flavour=%d folder=%s",
r1, syscall.Errno(r1), layerId, info.Flavour, importFolderPath)
logrus.Error(err)
return err
}
logrus.Debugf(title+"- succeeded layerId=%s flavour=%d folder=%s", layerId, info.Flavour, importFolderPath)
return nil
}

View file

@ -0,0 +1,60 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func LayerExists(info DriverInfo, id string) (bool, error) {
title := "hcsshim::LayerExists "
logrus.Debugf(title+"Flavour %s ID %s", info.Flavour, id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procLayerExists)
if dll != nil {
defer dll.Release()
}
if err != nil {
return false, err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return false, err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion info struct %s", err)
logrus.Error(err)
return false, err
}
// Call the procedure itself.
var exists bool // Outparam from Win32
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(idp)),
uintptr(unsafe.Pointer(&exists)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s flavour=%d",
r1, syscall.Errno(r1), id, info.Flavour)
logrus.Error(err)
return false, err
}
logrus.Debugf(title+" - succeeded id=%s flavour=%d exists=%d", id, info.Flavour, exists)
return exists, nil
}

View file

@ -0,0 +1,105 @@
package hcsshim
// This file contains utility functions to support storage (graph) related
// functionality.
import (
"syscall"
"github.com/Sirupsen/logrus"
)
/* To pass into syscall, we need a struct matching the following:
enum GraphDriverType
{
DiffDriver,
FilterDriver
};
struct DriverInfo {
GraphDriverType Flavour;
LPCWSTR HomeDir;
};
*/
type DriverInfo struct {
Flavour int
HomeDir string
}
type driverInfo struct {
Flavour int
HomeDirp *uint16
}
func convertDriverInfo(info DriverInfo) (driverInfo, error) {
homedirp, err := syscall.UTF16PtrFromString(info.HomeDir)
if err != nil {
logrus.Debugf("Failed conversion of home to pointer for driver info: %s", err.Error())
return driverInfo{}, err
}
return driverInfo{
Flavour: info.Flavour,
HomeDirp: homedirp,
}, nil
}
/* To pass into syscall, we need a struct matching the following:
typedef struct _WC_LAYER_DESCRIPTOR {
//
// The ID of the layer
//
GUID LayerId;
//
// Additional flags
//
union {
struct {
ULONG Reserved : 31;
ULONG Dirty : 1; // Created from sandbox as a result of snapshot
};
ULONG Value;
} Flags;
//
// Path to the layer root directory, null-terminated
//
PCWSTR Path;
} WC_LAYER_DESCRIPTOR, *PWC_LAYER_DESCRIPTOR;
*/
type WC_LAYER_DESCRIPTOR struct {
LayerId GUID
Flags uint32
Pathp *uint16
}
func layerPathsToDescriptors(parentLayerPaths []string) ([]WC_LAYER_DESCRIPTOR, error) {
// Array of descriptors that gets constructed.
var layers []WC_LAYER_DESCRIPTOR
for i := 0; i < len(parentLayerPaths); i++ {
// Create a layer descriptor, using the folder path
// as the source for a GUID LayerId
g := NewGUID(parentLayerPaths[i])
p, err := syscall.UTF16PtrFromString(parentLayerPaths[i])
if err != nil {
logrus.Debugf("Failed conversion of parentLayerPath to pointer %s", err)
return nil, err
}
layers = append(layers, WC_LAYER_DESCRIPTOR{
LayerId: *g,
Flags: 0,
Pathp: p,
})
}
return layers, nil
}

View file

@ -0,0 +1,73 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func PrepareLayer(info DriverInfo, layerId string, parentLayerPaths []string) error {
title := "hcsshim::PrepareLayer "
logrus.Debugf(title+"flavour %d layerId %s", info.Flavour, layerId)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procPrepareLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Generate layer descriptors
layers, err := layerPathsToDescriptors(parentLayerPaths)
if err != nil {
err = fmt.Errorf(title+"- Failed to generate layer descriptors ", err)
return err
}
// Convert layerId to uint16 pointer for calling the procedure
layerIdp, err := syscall.UTF16PtrFromString(layerId)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of layerId %s to pointer %s", layerId, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
var layerDescriptorsp *WC_LAYER_DESCRIPTOR
if len(layers) > 0 {
layerDescriptorsp = &(layers[0])
} else {
layerDescriptorsp = nil
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(layerIdp)),
uintptr(unsafe.Pointer(layerDescriptorsp)),
uintptr(len(layers)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(layerIdp))
use(unsafe.Pointer(layerDescriptorsp))
if r1 != 0 {
err = fmt.Errorf(title+"- Win32 API call returned error r1=%d err=%s layerId=%s flavour=%d",
r1, syscall.Errno(r1), layerId, info.Flavour)
logrus.Error(err)
return err
}
logrus.Debugf(title+"- succeeded layerId=%s flavour=%d", layerId, info.Flavour)
return nil
}

View file

@ -0,0 +1,46 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func ResizeConsoleInComputeSystem(id string, processid uint32, h, w int) error {
title := "HCSShim::ResizeConsoleInComputeSystem"
logrus.Debugf(title+" id=%s processid=%d (%d,%d)", id, processid, h, w)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procResizeConsoleInComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
h16 := uint16(h)
w16 := uint16(w)
r1, _, _ := proc.Call(uintptr(unsafe.Pointer(idp)), uintptr(processid), uintptr(h16), uintptr(w16), uintptr(0))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s, id=%s pid=%d", r1, syscall.Errno(r1), id, processid)
logrus.Error(err)
return err
}
logrus.Debugf(title+" - succeeded id=%s processid=%d (%d,%d)", id, processid, h, w)
return nil
}

View file

@ -0,0 +1,49 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
// ShutdownComputeSystem shuts down a container
func ShutdownComputeSystem(id string) error {
var title = "HCSShim::ShutdownComputeSystem"
logrus.Debugf(title+" id=%s", id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procShutdownComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert id to uint16 pointers for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
timeout := uint32(0xffffffff)
// Call the procedure itself.
r1, _, err := proc.Call(
uintptr(unsafe.Pointer(idp)), uintptr(timeout))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s", r1, syscall.Errno(r1), id)
return syscall.Errno(r1)
}
logrus.Debugf(title+" - succeeded id=%s", id)
return nil
}

View file

@ -0,0 +1,47 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
// StartComputeSystem starts a container
func StartComputeSystem(id string) error {
title := "HCSShim::StartComputeSystem"
logrus.Debugf(title+" id=%s", id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procStartComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert ID to uint16 pointers for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, _ := proc.Call(uintptr(unsafe.Pointer(idp)))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s", r1, syscall.Errno(r1), id)
logrus.Error(err)
return err
}
logrus.Debugf("HCSShim::StartComputeSystem - succeeded id=%s", id)
return nil
}

View file

@ -0,0 +1,49 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
// TerminateComputeSystem force terminates a container
func TerminateComputeSystem(id string) error {
var title = "HCSShim::TerminateComputeSystem"
logrus.Debugf(title+" id=%s", id)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procTerminateComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert id to uint16 pointers for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
timeout := uint32(0xffffffff)
// Call the procedure itself.
r1, _, err := proc.Call(
uintptr(unsafe.Pointer(idp)), uintptr(timeout))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s", r1, syscall.Errno(r1), id)
return syscall.Errno(r1)
}
logrus.Debugf(title+" - succeeded id=%s", id)
return nil
}

View file

@ -0,0 +1,49 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
// TerminateProcessInComputeSystem kills a process in a running container
func TerminateProcessInComputeSystem(id string, processid uint32) (err error) {
title := "HCSShim::TerminateProcessInComputeSystem"
logrus.Debugf(title+" id=%s processid=%d", id, processid)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procTerminateProcessInComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert ID to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, err := proc.Call(
uintptr(unsafe.Pointer(idp)),
uintptr(processid))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s", r1, syscall.Errno(r1), id)
logrus.Error(err)
return err
}
logrus.Debugf(title+" - succeeded id=%s", id)
return nil
}

View file

@ -0,0 +1,57 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func UnprepareLayer(info DriverInfo, layerId string) error {
title := "hcsshim::UnprepareLayer "
logrus.Debugf(title+"flavour %d layerId %s", info.Flavour, layerId)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procUnprepareLayer)
if dll != nil {
defer dll.Release()
}
if err != nil {
return err
}
// Convert layerId to uint16 pointer for calling the procedure
layerIdp, err := syscall.UTF16PtrFromString(layerId)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion of layerId %s to pointer %s", layerId, err)
logrus.Error(err)
return err
}
// Convert info to API calling convention
infop, err := convertDriverInfo(info)
if err != nil {
err = fmt.Errorf(title+"- Failed conversion info struct %s", err)
logrus.Error(err)
return err
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(&infop)),
uintptr(unsafe.Pointer(layerIdp)))
use(unsafe.Pointer(&infop))
use(unsafe.Pointer(layerIdp))
if r1 != 0 {
err = fmt.Errorf(title+"- Win32 API call returned error r1=%d err=%s layerId=%s flavour=%d",
r1, syscall.Errno(r1), layerId, info.Flavour)
logrus.Error(err)
return err
}
logrus.Debugf(title+"- succeeded layerId=%s flavour=%d", layerId, info.Flavour)
return nil
}

View file

@ -0,0 +1,56 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
// WaitForProcessInComputeSystem waits for a process ID to terminate and returns
// the exit code.
func WaitForProcessInComputeSystem(id string, processid uint32) (exitcode int32, err error) {
title := "HCSShim::WaitForProcessInComputeSystem"
logrus.Debugf(title+" id=%s processid=%d", id, processid)
var timeout uint32 = 0xFFFFFFFF // (-1/INFINITE)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procWaitForProcessInComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return 0, err
}
// Convert id to uint16 pointer for calling the procedure
idp, err := syscall.UTF16PtrFromString(id)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return 0, err
}
// To get a POINTER to the ExitCode
ec := new(int32)
// Call the procedure itself.
r1, _, err := proc.Call(
uintptr(unsafe.Pointer(idp)),
uintptr(processid),
uintptr(timeout),
uintptr(unsafe.Pointer(ec)))
use(unsafe.Pointer(idp))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s", r1, syscall.Errno(r1), id)
return 0, err
}
logrus.Debugf(title+" - succeeded id=%s processid=%d exitcode=%d", id, processid, *ec)
return *ec, nil
}

View file

@ -0,0 +1,22 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe

View file

@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2013 npipe authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,308 @@
npipe [![Build status](https://ci.appveyor.com/api/projects/status/00vuepirsot29qwi)](https://ci.appveyor.com/project/natefinch/npipe) [![GoDoc](https://godoc.org/gopkg.in/natefinch/npipe.v2?status.svg)](https://godoc.org/gopkg.in/natefinch/npipe.v2)
=====
Package npipe provides a pure Go wrapper around Windows named pipes.
Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780
Note that the code lives at https://github.com/natefinch/npipe (v2 branch)
but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is
still npipe).
npipe provides an interface based on stdlib's net package, with Dial, Listen,
and Accept functions, as well as associated implementations of net.Conn and
net.Listener. It supports rpc over the connection.
### Notes
* Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API.
* The pipes support byte mode only (no support for message mode)
### Examples
The Dial function connects a client to a named pipe:
conn, err := npipe.Dial(`\\.\pipe\mypipename`)
if err != nil {
<handle error>
}
fmt.Fprintf(conn, "Hi server!\n")
msg, err := bufio.NewReader(conn).ReadString('\n')
...
The Listen function creates servers:
ln, err := npipe.Listen(`\\.\pipe\mypipename`)
if err != nil {
// handle error
}
for {
conn, err := ln.Accept()
if err != nil {
// handle error
continue
}
go handleConnection(conn)
}
## Variables
``` go
var ErrClosed = PipeError{"Pipe has been closed.", false}
```
ErrClosed is the error returned by PipeListener.Accept when Close is called
on the PipeListener.
## type PipeAddr
``` go
type PipeAddr string
```
PipeAddr represents the address of a named pipe.
### func (PipeAddr) Network
``` go
func (a PipeAddr) Network() string
```
Network returns the address's network name, "pipe".
### func (PipeAddr) String
``` go
func (a PipeAddr) String() string
```
String returns the address of the pipe
## type PipeConn
``` go
type PipeConn struct {
// contains filtered or unexported fields
}
```
PipeConn is the implementation of the net.Conn interface for named pipe connections.
### func Dial
``` go
func Dial(address string) (*PipeConn, error)
```
Dial connects to a named pipe with the given address. If the specified pipe is not available,
it will wait indefinitely for the pipe to become available.
The address must be of the form \\.\\pipe\<name> for local pipes and \\<computer>\pipe\<name>
for remote pipes.
Dial will return a PipeError if you pass in a badly formatted pipe name.
Examples:
// local pipe
conn, err := Dial(`\\.\pipe\mypipename`)
// remote pipe
conn, err := Dial(`\\othercomp\pipe\mypipename`)
### func DialTimeout
``` go
func DialTimeout(address string, timeout time.Duration) (*PipeConn, error)
```
DialTimeout acts like Dial, but will time out after the duration of timeout
### func (\*PipeConn) Close
``` go
func (c *PipeConn) Close() error
```
Close closes the connection.
### func (\*PipeConn) LocalAddr
``` go
func (c *PipeConn) LocalAddr() net.Addr
```
LocalAddr returns the local network address.
### func (\*PipeConn) Read
``` go
func (c *PipeConn) Read(b []byte) (int, error)
```
Read implements the net.Conn Read method.
### func (\*PipeConn) RemoteAddr
``` go
func (c *PipeConn) RemoteAddr() net.Addr
```
RemoteAddr returns the remote network address.
### func (\*PipeConn) SetDeadline
``` go
func (c *PipeConn) SetDeadline(t time.Time) error
```
SetDeadline implements the net.Conn SetDeadline method.
Note that timeouts are only supported on Windows Vista/Server 2008 and above
### func (\*PipeConn) SetReadDeadline
``` go
func (c *PipeConn) SetReadDeadline(t time.Time) error
```
SetReadDeadline implements the net.Conn SetReadDeadline method.
Note that timeouts are only supported on Windows Vista/Server 2008 and above
### func (\*PipeConn) SetWriteDeadline
``` go
func (c *PipeConn) SetWriteDeadline(t time.Time) error
```
SetWriteDeadline implements the net.Conn SetWriteDeadline method.
Note that timeouts are only supported on Windows Vista/Server 2008 and above
### func (\*PipeConn) Write
``` go
func (c *PipeConn) Write(b []byte) (int, error)
```
Write implements the net.Conn Write method.
## type PipeError
``` go
type PipeError struct {
// contains filtered or unexported fields
}
```
PipeError is an error related to a call to a pipe
### func (PipeError) Error
``` go
func (e PipeError) Error() string
```
Error implements the error interface
### func (PipeError) Temporary
``` go
func (e PipeError) Temporary() bool
```
Temporary implements net.AddrError.Temporary()
### func (PipeError) Timeout
``` go
func (e PipeError) Timeout() bool
```
Timeout implements net.AddrError.Timeout()
## type PipeListener
``` go
type PipeListener struct {
// contains filtered or unexported fields
}
```
PipeListener is a named pipe listener. Clients should typically
use variables of type net.Listener instead of assuming named pipe.
### func Listen
``` go
func Listen(address string) (*PipeListener, error)
```
Listen returns a new PipeListener that will listen on a pipe with the given
address. The address must be of the form \\.\pipe\<name>
Listen will return a PipeError for an incorrectly formatted pipe name.
### func (\*PipeListener) Accept
``` go
func (l *PipeListener) Accept() (net.Conn, error)
```
Accept implements the Accept method in the net.Listener interface; it
waits for the next call and returns a generic net.Conn.
### func (\*PipeListener) AcceptPipe
``` go
func (l *PipeListener) AcceptPipe() (*PipeConn, error)
```
AcceptPipe accepts the next incoming call and returns the new connection.
### func (\*PipeListener) Addr
``` go
func (l *PipeListener) Addr() net.Addr
```
Addr returns the listener's network address, a PipeAddr.
### func (\*PipeListener) Close
``` go
func (l *PipeListener) Close() error
```
Close stops listening on the address.
Already Accepted connections are not closed.

View file

@ -0,0 +1,50 @@
// Copyright 2013 Nate Finch. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Package npipe provides a pure Go wrapper around Windows named pipes.
//
// !! Note, this package is Windows-only. There is no code to compile on linux.
//
// Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780
//
// Note that the code lives at https://github.com/natefinch/npipe (v2 branch)
// but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is
// still npipe).
//
// npipe provides an interface based on stdlib's net package, with Dial, Listen,
// and Accept functions, as well as associated implementations of net.Conn and
// net.Listener. It supports rpc over the connection.
//
// Notes
//
// * Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API.
//
// * The pipes support byte mode only (no support for message mode)
//
// Examples
//
// The Dial function connects a client to a named pipe:
// conn, err := npipe.Dial(`\\.\pipe\mypipename`)
// if err != nil {
// <handle error>
// }
// fmt.Fprintf(conn, "Hi server!\n")
// msg, err := bufio.NewReader(conn).ReadString('\n')
// ...
//
// The Listen function creates servers:
//
// ln, err := npipe.Listen(`\\.\pipe\mypipename`)
// if err != nil {
// // handle error
// }
// for {
// conn, err := ln.Accept()
// if err != nil {
// // handle error
// continue
// }
// go handleConnection(conn)
// }
package npipe

View file

@ -0,0 +1,518 @@
package npipe
//sys createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW
//sys connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = ConnectNamedPipe
//sys disconnectNamedPipe(handle syscall.Handle) (err error) = DisconnectNamedPipe
//sys waitNamedPipe(name *uint16, timeout uint32) (err error) = WaitNamedPipeW
//sys createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateEventW
//sys getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) = GetOverlappedResult
//sys cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = CancelIoEx
import (
"fmt"
"io"
"net"
"sync"
"syscall"
"time"
)
const (
// openMode
pipe_access_duplex = 0x3
pipe_access_inbound = 0x1
pipe_access_outbound = 0x2
// openMode write flags
file_flag_first_pipe_instance = 0x00080000
file_flag_write_through = 0x80000000
file_flag_overlapped = 0x40000000
// openMode ACL flags
write_dac = 0x00040000
write_owner = 0x00080000
access_system_security = 0x01000000
// pipeMode
pipe_type_byte = 0x0
pipe_type_message = 0x4
// pipeMode read mode flags
pipe_readmode_byte = 0x0
pipe_readmode_message = 0x2
// pipeMode wait mode flags
pipe_wait = 0x0
pipe_nowait = 0x1
// pipeMode remote-client mode flags
pipe_accept_remote_clients = 0x0
pipe_reject_remote_clients = 0x8
pipe_unlimited_instances = 255
nmpwait_wait_forever = 0xFFFFFFFF
// the two not-an-errors below occur if a client connects to the pipe between
// the server's CreateNamedPipe and ConnectNamedPipe calls.
error_no_data syscall.Errno = 0xE8
error_pipe_connected syscall.Errno = 0x217
error_pipe_busy syscall.Errno = 0xE7
error_sem_timeout syscall.Errno = 0x79
error_bad_pathname syscall.Errno = 0xA1
error_invalid_name syscall.Errno = 0x7B
error_io_incomplete syscall.Errno = 0x3e4
)
var _ net.Conn = (*PipeConn)(nil)
var _ net.Listener = (*PipeListener)(nil)
// ErrClosed is the error returned by PipeListener.Accept when Close is called
// on the PipeListener.
var ErrClosed = PipeError{"Pipe has been closed.", false}
// PipeError is an error related to a call to a pipe
type PipeError struct {
msg string
timeout bool
}
// Error implements the error interface
func (e PipeError) Error() string {
return e.msg
}
// Timeout implements net.AddrError.Timeout()
func (e PipeError) Timeout() bool {
return e.timeout
}
// Temporary implements net.AddrError.Temporary()
func (e PipeError) Temporary() bool {
return false
}
// Dial connects to a named pipe with the given address. If the specified pipe is not available,
// it will wait indefinitely for the pipe to become available.
//
// The address must be of the form \\.\\pipe\<name> for local pipes and \\<computer>\pipe\<name>
// for remote pipes.
//
// Dial will return a PipeError if you pass in a badly formatted pipe name.
//
// Examples:
// // local pipe
// conn, err := Dial(`\\.\pipe\mypipename`)
//
// // remote pipe
// conn, err := Dial(`\\othercomp\pipe\mypipename`)
func Dial(address string) (*PipeConn, error) {
for {
conn, err := dial(address, nmpwait_wait_forever)
if err == nil {
return conn, nil
}
if isPipeNotReady(err) {
<-time.After(100 * time.Millisecond)
continue
}
return nil, err
}
}
// DialTimeout acts like Dial, but will time out after the duration of timeout
func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) {
deadline := time.Now().Add(timeout)
now := time.Now()
for now.Before(deadline) {
millis := uint32(deadline.Sub(now) / time.Millisecond)
conn, err := dial(address, millis)
if err == nil {
return conn, nil
}
if err == error_sem_timeout {
// This is WaitNamedPipe's timeout error, so we know we're done
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
}
if isPipeNotReady(err) {
left := deadline.Sub(time.Now())
retry := 100 * time.Millisecond
if left > retry {
<-time.After(retry)
} else {
<-time.After(left - time.Millisecond)
}
now = time.Now()
continue
}
return nil, err
}
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
}
// isPipeNotReady checks the error to see if it indicates the pipe is not ready
func isPipeNotReady(err error) bool {
// Pipe Busy means another client just grabbed the open pipe end,
// and the server hasn't made a new one yet.
// File Not Found means the server hasn't created the pipe yet.
// Neither is a fatal error.
return err == syscall.ERROR_FILE_NOT_FOUND || err == error_pipe_busy
}
// newOverlapped creates a structure used to track asynchronous
// I/O requests that have been issued.
func newOverlapped() (*syscall.Overlapped, error) {
event, err := createEvent(nil, true, true, nil)
if err != nil {
return nil, err
}
return &syscall.Overlapped{HEvent: event}, nil
}
// waitForCompletion waits for an asynchronous I/O request referred to by overlapped to complete.
// This function returns the number of bytes transferred by the operation and an error code if
// applicable (nil otherwise).
func waitForCompletion(handle syscall.Handle, overlapped *syscall.Overlapped) (uint32, error) {
_, err := syscall.WaitForSingleObject(overlapped.HEvent, syscall.INFINITE)
if err != nil {
return 0, err
}
var transferred uint32
err = getOverlappedResult(handle, overlapped, &transferred, true)
return transferred, err
}
// dial is a helper to initiate a connection to a named pipe that has been started by a server.
// The timeout is only enforced if the pipe server has already created the pipe, otherwise
// this function will return immediately.
func dial(address string, timeout uint32) (*PipeConn, error) {
name, err := syscall.UTF16PtrFromString(string(address))
if err != nil {
return nil, err
}
// If at least one instance of the pipe has been created, this function
// will wait timeout milliseconds for it to become available.
// It will return immediately regardless of timeout, if no instances
// of the named pipe have been created yet.
// If this returns with no error, there is a pipe available.
if err := waitNamedPipe(name, timeout); err != nil {
if err == error_bad_pathname {
// badly formatted pipe name
return nil, badAddr(address)
}
return nil, err
}
pathp, err := syscall.UTF16PtrFromString(address)
if err != nil {
return nil, err
}
handle, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE,
uint32(syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE), nil, syscall.OPEN_EXISTING,
syscall.FILE_FLAG_OVERLAPPED, 0)
if err != nil {
return nil, err
}
return &PipeConn{handle: handle, addr: PipeAddr(address)}, nil
}
// Listen returns a new PipeListener that will listen on a pipe with the given
// address. The address must be of the form \\.\pipe\<name>
//
// Listen will return a PipeError for an incorrectly formatted pipe name.
func Listen(address string) (*PipeListener, error) {
handle, err := createPipe(address, true)
if err == error_invalid_name {
return nil, badAddr(address)
}
if err != nil {
return nil, err
}
return &PipeListener{
addr: PipeAddr(address),
handle: handle,
}, nil
}
// PipeListener is a named pipe listener. Clients should typically
// use variables of type net.Listener instead of assuming named pipe.
type PipeListener struct {
addr PipeAddr
handle syscall.Handle
closed bool
// acceptHandle contains the current handle waiting for
// an incoming connection or nil.
acceptHandle syscall.Handle
// acceptOverlapped is set before waiting on a connection.
// If not waiting, it is nil.
acceptOverlapped *syscall.Overlapped
// acceptMutex protects the handle and overlapped structure.
acceptMutex sync.Mutex
}
// Accept implements the Accept method in the net.Listener interface; it
// waits for the next call and returns a generic net.Conn.
func (l *PipeListener) Accept() (net.Conn, error) {
c, err := l.AcceptPipe()
for err == error_no_data {
// Ignore clients that connect and immediately disconnect.
c, err = l.AcceptPipe()
}
if err != nil {
return nil, err
}
return c, nil
}
// AcceptPipe accepts the next incoming call and returns the new connection.
// It might return an error if a client connected and immediately cancelled
// the connection.
func (l *PipeListener) AcceptPipe() (*PipeConn, error) {
if l == nil || l.addr == "" || l.closed {
return nil, syscall.EINVAL
}
// the first time we call accept, the handle will have been created by the Listen
// call. This is to prevent race conditions where the client thinks the server
// isn't listening because it hasn't actually called create yet. After the first time, we'll
// have to create a new handle each time
handle := l.handle
if handle == 0 {
var err error
handle, err = createPipe(string(l.addr), false)
if err != nil {
return nil, err
}
} else {
l.handle = 0
}
overlapped, err := newOverlapped()
if err != nil {
return nil, err
}
defer syscall.CloseHandle(overlapped.HEvent)
if err := connectNamedPipe(handle, overlapped); err != nil && err != error_pipe_connected {
if err == error_io_incomplete || err == syscall.ERROR_IO_PENDING {
l.acceptMutex.Lock()
l.acceptOverlapped = overlapped
l.acceptHandle = handle
l.acceptMutex.Unlock()
defer func() {
l.acceptMutex.Lock()
l.acceptOverlapped = nil
l.acceptHandle = 0
l.acceptMutex.Unlock()
}()
_, err = waitForCompletion(handle, overlapped)
}
if err == syscall.ERROR_OPERATION_ABORTED {
// Return error compatible to net.Listener.Accept() in case the
// listener was closed.
return nil, ErrClosed
}
if err != nil {
return nil, err
}
}
return &PipeConn{handle: handle, addr: l.addr}, nil
}
// Close stops listening on the address.
// Already Accepted connections are not closed.
func (l *PipeListener) Close() error {
if l.closed {
return nil
}
l.closed = true
if l.handle != 0 {
err := disconnectNamedPipe(l.handle)
if err != nil {
return err
}
err = syscall.CloseHandle(l.handle)
if err != nil {
return err
}
l.handle = 0
}
l.acceptMutex.Lock()
defer l.acceptMutex.Unlock()
if l.acceptOverlapped != nil && l.acceptHandle != 0 {
// Cancel the pending IO. This call does not block, so it is safe
// to hold onto the mutex above.
if err := cancelIoEx(l.acceptHandle, l.acceptOverlapped); err != nil {
return err
}
err := syscall.CloseHandle(l.acceptOverlapped.HEvent)
if err != nil {
return err
}
l.acceptOverlapped.HEvent = 0
err = syscall.CloseHandle(l.acceptHandle)
if err != nil {
return err
}
l.acceptHandle = 0
}
return nil
}
// Addr returns the listener's network address, a PipeAddr.
func (l *PipeListener) Addr() net.Addr { return l.addr }
// PipeConn is the implementation of the net.Conn interface for named pipe connections.
type PipeConn struct {
handle syscall.Handle
addr PipeAddr
// these aren't actually used yet
readDeadline *time.Time
writeDeadline *time.Time
}
type iodata struct {
n uint32
err error
}
// completeRequest looks at iodata to see if a request is pending. If so, it waits for it to either complete or to
// abort due to hitting the specified deadline. Deadline may be set to nil to wait forever. If no request is pending,
// the content of iodata is returned.
func (c *PipeConn) completeRequest(data iodata, deadline *time.Time, overlapped *syscall.Overlapped) (int, error) {
if data.err == error_io_incomplete || data.err == syscall.ERROR_IO_PENDING {
var timer <-chan time.Time
if deadline != nil {
if timeDiff := deadline.Sub(time.Now()); timeDiff > 0 {
timer = time.After(timeDiff)
}
}
done := make(chan iodata)
go func() {
n, err := waitForCompletion(c.handle, overlapped)
done <- iodata{n, err}
}()
select {
case data = <-done:
case <-timer:
syscall.CancelIoEx(c.handle, overlapped)
data = iodata{0, timeout(c.addr.String())}
}
}
// Windows will produce ERROR_BROKEN_PIPE upon closing
// a handle on the other end of a connection. Go RPC
// expects an io.EOF error in this case.
if data.err == syscall.ERROR_BROKEN_PIPE {
data.err = io.EOF
}
return int(data.n), data.err
}
// Read implements the net.Conn Read method.
func (c *PipeConn) Read(b []byte) (int, error) {
// Use ReadFile() rather than Read() because the latter
// contains a workaround that eats ERROR_BROKEN_PIPE.
overlapped, err := newOverlapped()
if err != nil {
return 0, err
}
defer syscall.CloseHandle(overlapped.HEvent)
var n uint32
err = syscall.ReadFile(c.handle, b, &n, overlapped)
return c.completeRequest(iodata{n, err}, c.readDeadline, overlapped)
}
// Write implements the net.Conn Write method.
func (c *PipeConn) Write(b []byte) (int, error) {
overlapped, err := newOverlapped()
if err != nil {
return 0, err
}
defer syscall.CloseHandle(overlapped.HEvent)
var n uint32
err = syscall.WriteFile(c.handle, b, &n, overlapped)
return c.completeRequest(iodata{n, err}, c.writeDeadline, overlapped)
}
// Close closes the connection.
func (c *PipeConn) Close() error {
return syscall.CloseHandle(c.handle)
}
// LocalAddr returns the local network address.
func (c *PipeConn) LocalAddr() net.Addr {
return c.addr
}
// RemoteAddr returns the remote network address.
func (c *PipeConn) RemoteAddr() net.Addr {
// not sure what to do here, we don't have remote addr....
return c.addr
}
// SetDeadline implements the net.Conn SetDeadline method.
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
func (c *PipeConn) SetDeadline(t time.Time) error {
c.SetReadDeadline(t)
c.SetWriteDeadline(t)
return nil
}
// SetReadDeadline implements the net.Conn SetReadDeadline method.
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
func (c *PipeConn) SetReadDeadline(t time.Time) error {
c.readDeadline = &t
return nil
}
// SetWriteDeadline implements the net.Conn SetWriteDeadline method.
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
func (c *PipeConn) SetWriteDeadline(t time.Time) error {
c.writeDeadline = &t
return nil
}
// PipeAddr represents the address of a named pipe.
type PipeAddr string
// Network returns the address's network name, "pipe".
func (a PipeAddr) Network() string { return "pipe" }
// String returns the address of the pipe
func (a PipeAddr) String() string {
return string(a)
}
// createPipe is a helper function to make sure we always create pipes
// with the same arguments, since subsequent calls to create pipe need
// to use the same arguments as the first one. If first is set, fail
// if the pipe already exists.
func createPipe(address string, first bool) (syscall.Handle, error) {
n, err := syscall.UTF16PtrFromString(address)
if err != nil {
return 0, err
}
mode := uint32(pipe_access_duplex | syscall.FILE_FLAG_OVERLAPPED)
if first {
mode |= file_flag_first_pipe_instance
}
return createNamedPipe(n,
mode,
pipe_type_byte,
pipe_unlimited_instances,
512, 512, 0, nil)
}
func badAddr(addr string) PipeError {
return PipeError{fmt.Sprintf("Invalid pipe address '%s'.", addr), false}
}
func timeout(addr string) PipeError {
return PipeError{fmt.Sprintf("Pipe IO timed out waiting for '%s'", addr), true}
}

View file

@ -0,0 +1,124 @@
// +build windows
// go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
package npipe
import "unsafe"
import "syscall"
var (
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe")
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
procCreateEventW = modkernel32.NewProc("CreateEventW")
procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult")
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
)
func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(openMode), uintptr(pipeMode), uintptr(maxInstances), uintptr(outBufSize), uintptr(inBufSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func disconnectNamedPipe(handle syscall.Handle) (err error) {
r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func waitNamedPipe(name *uint16, timeout uint32) (err error) {
r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) {
var _p0 uint32
if manualReset {
_p0 = 1
} else {
_p0 = 0
}
var _p1 uint32
if initialState {
_p1 = 1
} else {
_p1 = 0
}
r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) {
var _p0 uint32
if wait {
_p0 = 1
} else {
_p0 = 0
}
r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}

View file

@ -0,0 +1,124 @@
// +build windows
// go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
package npipe
import "unsafe"
import "syscall"
var (
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe")
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
procCreateEventW = modkernel32.NewProc("CreateEventW")
procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult")
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
)
func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(openMode), uintptr(pipeMode), uintptr(maxInstances), uintptr(outBufSize), uintptr(inBufSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func disconnectNamedPipe(handle syscall.Handle) (err error) {
r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func waitNamedPipe(name *uint16, timeout uint32) (err error) {
r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) {
var _p0 uint32
if manualReset {
_p0 = 1
} else {
_p0 = 0
}
var _p1 uint32
if initialState {
_p1 = 1
} else {
_p1 = 0
}
r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) {
var _p0 uint32
if wait {
_p0 = 1
} else {
_p0 = 0
}
r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}