2015-11-12 14:55:17 -05:00
|
|
|
package container
|
2014-08-04 20:05:56 -04:00
|
|
|
|
|
|
|
import (
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 10:53:35 -05:00
|
|
|
"fmt"
|
2014-08-04 20:05:56 -04:00
|
|
|
"io"
|
|
|
|
"os/exec"
|
2015-07-29 08:21:16 -04:00
|
|
|
"strings"
|
2014-08-04 20:05:56 -04:00
|
|
|
"sync"
|
2015-07-29 08:21:16 -04:00
|
|
|
"syscall"
|
2014-08-04 20:05:56 -04:00
|
|
|
"time"
|
|
|
|
|
2015-03-26 18:22:04 -04:00
|
|
|
"github.com/Sirupsen/logrus"
|
2014-10-24 18:11:48 -04:00
|
|
|
"github.com/docker/docker/daemon/execdriver"
|
2015-11-12 14:55:17 -05:00
|
|
|
"github.com/docker/docker/pkg/promise"
|
2015-03-24 07:25:26 -04:00
|
|
|
"github.com/docker/docker/pkg/stringid"
|
2016-01-04 19:05:26 -05:00
|
|
|
"github.com/docker/engine-api/types/container"
|
2014-08-04 20:05:56 -04:00
|
|
|
)
|
|
|
|
|
2015-07-03 09:50:06 -04:00
|
|
|
const (
|
|
|
|
defaultTimeIncrement = 100
|
|
|
|
loggerCloseTimeout = 10 * time.Second
|
|
|
|
)
|
2014-08-04 21:20:53 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// supervisor defines the interface that a supervisor must implement
|
|
|
|
type supervisor interface {
|
2015-11-03 12:33:13 -05:00
|
|
|
// LogContainerEvent generates events related to a given container
|
|
|
|
LogContainerEvent(*Container, string)
|
2015-11-03 12:43:36 -05:00
|
|
|
// Cleanup ensures that the container is properly unmounted
|
|
|
|
Cleanup(*Container)
|
2015-11-03 13:45:12 -05:00
|
|
|
// StartLogging starts the logging driver for the container
|
|
|
|
StartLogging(*Container) error
|
2015-11-03 14:25:22 -05:00
|
|
|
// Run starts a container
|
|
|
|
Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.DriverCallback) (execdriver.ExitStatus, error)
|
|
|
|
// IsShuttingDown tells whether the supervisor is shutting down or not
|
|
|
|
IsShuttingDown() bool
|
2015-11-03 12:33:13 -05:00
|
|
|
}
|
|
|
|
|
2014-08-04 20:05:56 -04:00
|
|
|
// containerMonitor monitors the execution of a container's main process.
|
2015-01-05 22:33:53 -05:00
|
|
|
// If a restart policy is specified for the container the monitor will ensure that the
|
2014-08-04 20:05:56 -04:00
|
|
|
// process is restarted based on the rules of the policy. When the container is finally stopped
|
|
|
|
// the monitor will reset and cleanup any of the container resources such as networking allocations
|
|
|
|
// and the rootfs
|
|
|
|
type containerMonitor struct {
|
|
|
|
mux sync.Mutex
|
|
|
|
|
2015-11-03 12:33:13 -05:00
|
|
|
// supervisor keeps track of the container and the events it generates
|
2015-11-12 14:55:17 -05:00
|
|
|
supervisor supervisor
|
2015-11-03 12:33:13 -05:00
|
|
|
|
2014-08-04 21:20:53 -04:00
|
|
|
// container is the container being monitored
|
|
|
|
container *Container
|
|
|
|
|
2014-08-13 17:56:35 -04:00
|
|
|
// restartPolicy is the current policy being applied to the container monitor
|
2015-12-18 13:36:17 -05:00
|
|
|
restartPolicy container.RestartPolicy
|
2014-08-04 21:20:53 -04:00
|
|
|
|
|
|
|
// failureCount is the number of times the container has failed to
|
|
|
|
// start in a row
|
|
|
|
failureCount int
|
|
|
|
|
|
|
|
// shouldStop signals the monitor that the next time the container exits it is
|
|
|
|
// either because docker or the user asked for the container to be stopped
|
|
|
|
shouldStop bool
|
|
|
|
|
2014-08-13 17:56:35 -04:00
|
|
|
// startSignal is a channel that is closes after the container initially starts
|
2014-08-12 21:03:11 -04:00
|
|
|
startSignal chan struct{}
|
|
|
|
|
2014-08-11 18:00:55 -04:00
|
|
|
// stopChan is used to signal to the monitor whenever there is a wait for the
|
|
|
|
// next restart so that the timeIncrement is not honored and the user is not
|
|
|
|
// left waiting for nothing to happen during this time
|
|
|
|
stopChan chan struct{}
|
|
|
|
|
2014-08-04 21:20:53 -04:00
|
|
|
// timeIncrement is the amount of time to wait between restarts
|
|
|
|
// this is in milliseconds
|
|
|
|
timeIncrement int
|
2014-08-12 16:08:26 -04:00
|
|
|
|
|
|
|
// lastStartTime is the time which the monitor last exec'd the container's process
|
|
|
|
lastStartTime time.Time
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// StartMonitor initializes a containerMonitor for this container with the provided supervisor and restart policy
|
|
|
|
// and starts the container's process.
|
2016-01-04 10:58:20 -05:00
|
|
|
func (container *Container) StartMonitor(s supervisor) error {
|
2015-11-12 14:55:17 -05:00
|
|
|
container.monitor = &containerMonitor{
|
|
|
|
supervisor: s,
|
2014-08-04 20:05:56 -04:00
|
|
|
container: container,
|
2016-01-04 10:58:20 -05:00
|
|
|
restartPolicy: container.HostConfig.RestartPolicy,
|
2014-08-04 21:20:53 -04:00
|
|
|
timeIncrement: defaultTimeIncrement,
|
2014-08-14 13:50:22 -04:00
|
|
|
stopChan: make(chan struct{}),
|
|
|
|
startSignal: make(chan struct{}),
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
2015-11-12 14:55:17 -05:00
|
|
|
|
|
|
|
return container.monitor.wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
// wait starts the container and wait until
|
|
|
|
// we either receive an error from the initial start of the container's
|
|
|
|
// process or until the process is running in the container
|
|
|
|
func (m *containerMonitor) wait() error {
|
|
|
|
select {
|
|
|
|
case <-m.startSignal:
|
|
|
|
case err := <-promise.Go(m.start):
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Stop signals to the container monitor that it should stop monitoring the container
|
|
|
|
// for exits the next time the process dies
|
|
|
|
func (m *containerMonitor) ExitOnNext() {
|
|
|
|
m.mux.Lock()
|
2014-08-11 18:00:55 -04:00
|
|
|
|
|
|
|
// we need to protect having a double close of the channel when stop is called
|
|
|
|
// twice or else we will get a panic
|
|
|
|
if !m.shouldStop {
|
|
|
|
m.shouldStop = true
|
|
|
|
close(m.stopChan)
|
|
|
|
}
|
|
|
|
|
2014-08-04 20:05:56 -04:00
|
|
|
m.mux.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the container's resources such as networking allocations and
|
2015-12-13 11:00:39 -05:00
|
|
|
// unmounts the container's root filesystem
|
2015-09-29 13:51:40 -04:00
|
|
|
func (m *containerMonitor) Close() error {
|
2014-08-04 20:05:56 -04:00
|
|
|
// Cleanup networking and mounts
|
2015-11-03 12:43:36 -05:00
|
|
|
m.supervisor.Cleanup(m.container)
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
if err := m.container.ToDisk(); err != nil {
|
2015-03-26 18:22:04 -04:00
|
|
|
logrus.Errorf("Error dumping container %s state to disk: %s", m.container.ID, err)
|
2014-08-06 13:40:43 -04:00
|
|
|
|
|
|
|
return err
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start starts the containers process and monitors it according to the restart policy
|
2015-11-12 14:55:17 -05:00
|
|
|
func (m *containerMonitor) start() error {
|
2014-08-04 20:05:56 -04:00
|
|
|
var (
|
2014-08-04 21:20:53 -04:00
|
|
|
err error
|
2014-10-30 19:06:54 -04:00
|
|
|
exitStatus execdriver.ExitStatus
|
2014-08-26 11:53:43 -04:00
|
|
|
// this variable indicates where we in execution flow:
|
|
|
|
// before Run or after
|
|
|
|
afterRun bool
|
2014-08-04 20:05:56 -04:00
|
|
|
)
|
2014-08-04 21:20:53 -04:00
|
|
|
|
|
|
|
// ensure that when the monitor finally exits we release the networking and unmount the rootfs
|
2014-08-14 07:51:31 -04:00
|
|
|
defer func() {
|
2014-08-26 11:53:43 -04:00
|
|
|
if afterRun {
|
2014-08-14 07:51:31 -04:00
|
|
|
m.container.Lock()
|
|
|
|
defer m.container.Unlock()
|
2015-11-12 14:55:17 -05:00
|
|
|
m.container.SetStopped(&exitStatus)
|
2014-08-14 07:51:31 -04:00
|
|
|
}
|
2015-09-29 13:51:40 -04:00
|
|
|
m.Close()
|
2014-08-14 07:51:31 -04:00
|
|
|
}()
|
2015-08-05 17:09:08 -04:00
|
|
|
// reset stopped flag
|
|
|
|
if m.container.HasBeenManuallyStopped {
|
|
|
|
m.container.HasBeenManuallyStopped = false
|
|
|
|
}
|
2014-08-04 20:05:56 -04:00
|
|
|
|
|
|
|
// reset the restart count
|
|
|
|
m.container.RestartCount = -1
|
|
|
|
|
2014-08-11 18:00:55 -04:00
|
|
|
for {
|
2014-08-04 20:05:56 -04:00
|
|
|
m.container.RestartCount++
|
2014-08-04 21:20:53 -04:00
|
|
|
|
2015-11-03 13:45:12 -05:00
|
|
|
if err := m.supervisor.StartLogging(m.container); err != nil {
|
2014-08-28 07:39:27 -04:00
|
|
|
m.resetContainer(false)
|
2014-08-04 20:05:56 -04:00
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-11-17 19:21:44 -05:00
|
|
|
pipes := execdriver.NewPipes(m.container.Stdin(), m.container.Stdout(), m.container.Stderr(), m.container.Config.OpenStdin)
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2015-11-03 12:33:13 -05:00
|
|
|
m.logEvent("start")
|
2014-08-07 13:50:25 -04:00
|
|
|
|
2014-08-12 16:08:26 -04:00
|
|
|
m.lastStartTime = time.Now()
|
|
|
|
|
2015-11-03 14:25:22 -05:00
|
|
|
if exitStatus, err = m.supervisor.Run(m.container, pipes, m.callback); err != nil {
|
2014-08-12 21:03:11 -04:00
|
|
|
// if we receive an internal error from the initial start of a container then lets
|
|
|
|
// return it instead of entering the restart loop
|
2015-11-08 21:29:34 -05:00
|
|
|
// set to 127 for container cmd not found/does not exist)
|
2015-07-29 08:21:16 -04:00
|
|
|
if strings.Contains(err.Error(), "executable file not found") ||
|
|
|
|
strings.Contains(err.Error(), "no such file or directory") ||
|
|
|
|
strings.Contains(err.Error(), "system cannot find the file specified") {
|
|
|
|
if m.container.RestartCount == 0 {
|
|
|
|
m.container.ExitCode = 127
|
|
|
|
m.resetContainer(false)
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 10:53:35 -05:00
|
|
|
return fmt.Errorf("Container command not found or does not exist.")
|
2015-07-29 08:21:16 -04:00
|
|
|
}
|
|
|
|
}
|
2015-11-08 21:29:34 -05:00
|
|
|
// set to 126 for container cmd can't be invoked errors
|
2015-07-29 08:21:16 -04:00
|
|
|
if strings.Contains(err.Error(), syscall.EACCES.Error()) {
|
|
|
|
if m.container.RestartCount == 0 {
|
|
|
|
m.container.ExitCode = 126
|
|
|
|
m.resetContainer(false)
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 10:53:35 -05:00
|
|
|
return fmt.Errorf("Container command could not be invoked.")
|
2015-07-29 08:21:16 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-13 17:58:57 -04:00
|
|
|
if m.container.RestartCount == 0 {
|
2014-10-30 19:06:54 -04:00
|
|
|
m.container.ExitCode = -1
|
2014-08-28 07:39:27 -04:00
|
|
|
m.resetContainer(false)
|
2014-08-12 21:03:11 -04:00
|
|
|
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 10:53:35 -05:00
|
|
|
return fmt.Errorf("Cannot start container %s: %v", m.container.ID, err)
|
2014-08-12 21:03:11 -04:00
|
|
|
}
|
|
|
|
|
2015-03-26 18:22:04 -04:00
|
|
|
logrus.Errorf("Error running container: %s", err)
|
2016-01-14 13:38:09 -05:00
|
|
|
}
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2014-08-14 07:51:31 -04:00
|
|
|
// here container.Lock is already lost
|
2014-08-26 11:53:43 -04:00
|
|
|
afterRun = true
|
2014-08-14 07:51:31 -04:00
|
|
|
|
2014-10-08 13:03:57 -04:00
|
|
|
m.resetMonitor(err == nil && exitStatus.ExitCode == 0)
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2014-10-08 13:03:57 -04:00
|
|
|
if m.shouldRestart(exitStatus.ExitCode) {
|
2016-02-02 06:50:06 -05:00
|
|
|
m.container.SetRestartingLocking(&exitStatus)
|
2015-11-03 12:33:13 -05:00
|
|
|
m.logEvent("die")
|
2014-08-28 07:39:27 -04:00
|
|
|
m.resetContainer(true)
|
2014-08-11 14:07:37 -04:00
|
|
|
|
2014-08-11 13:50:02 -04:00
|
|
|
// sleep with a small time increment between each restart to help avoid issues cased by quickly
|
|
|
|
// restarting the container because of some types of errors ( networking cut out, etc... )
|
2014-08-11 18:00:55 -04:00
|
|
|
m.waitForNextRestart()
|
|
|
|
|
|
|
|
// we need to check this before reentering the loop because the waitForNextRestart could have
|
|
|
|
// been terminated by a request from a user
|
|
|
|
if m.shouldStop {
|
|
|
|
return err
|
|
|
|
}
|
2014-08-04 20:05:56 -04:00
|
|
|
continue
|
|
|
|
}
|
2015-09-11 06:01:47 -04:00
|
|
|
|
2015-11-03 12:33:13 -05:00
|
|
|
m.logEvent("die")
|
2014-08-28 07:39:27 -04:00
|
|
|
m.resetContainer(true)
|
2014-08-26 11:53:43 -04:00
|
|
|
return err
|
2016-01-14 13:38:09 -05:00
|
|
|
}
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
|
|
|
|
2014-08-11 14:07:37 -04:00
|
|
|
// resetMonitor resets the stateful fields on the containerMonitor based on the
|
2015-03-13 05:12:02 -04:00
|
|
|
// previous runs success or failure. Regardless of success, if the container had
|
2014-08-12 16:08:26 -04:00
|
|
|
// an execution time of more than 10s then reset the timer back to the default
|
2014-08-11 14:07:37 -04:00
|
|
|
func (m *containerMonitor) resetMonitor(successful bool) {
|
2014-08-12 16:08:26 -04:00
|
|
|
executionTime := time.Now().Sub(m.lastStartTime).Seconds()
|
|
|
|
|
|
|
|
if executionTime > 10 {
|
2014-08-11 14:07:37 -04:00
|
|
|
m.timeIncrement = defaultTimeIncrement
|
|
|
|
} else {
|
|
|
|
// otherwise we need to increment the amount of time we wait before restarting
|
|
|
|
// the process. We will build up by multiplying the increment by 2
|
2014-08-12 16:08:26 -04:00
|
|
|
m.timeIncrement *= 2
|
|
|
|
}
|
2014-08-11 14:07:37 -04:00
|
|
|
|
2014-08-12 16:08:26 -04:00
|
|
|
// the container exited successfully so we need to reset the failure counter
|
|
|
|
if successful {
|
|
|
|
m.failureCount = 0
|
|
|
|
} else {
|
2014-08-11 14:07:37 -04:00
|
|
|
m.failureCount++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-11 18:00:55 -04:00
|
|
|
// waitForNextRestart waits with the default time increment to restart the container unless
|
2014-08-13 17:56:35 -04:00
|
|
|
// a user or docker asks for the container to be stopped
|
2014-08-11 18:00:55 -04:00
|
|
|
func (m *containerMonitor) waitForNextRestart() {
|
|
|
|
select {
|
|
|
|
case <-time.After(time.Duration(m.timeIncrement) * time.Millisecond):
|
|
|
|
case <-m.stopChan:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-04 21:20:53 -04:00
|
|
|
// shouldRestart checks the restart policy and applies the rules to determine if
|
|
|
|
// the container's process should be restarted
|
2014-10-08 13:03:57 -04:00
|
|
|
func (m *containerMonitor) shouldRestart(exitCode int) bool {
|
2014-08-04 20:05:56 -04:00
|
|
|
m.mux.Lock()
|
2014-08-04 21:20:53 -04:00
|
|
|
defer m.mux.Unlock()
|
|
|
|
|
|
|
|
// do not restart if the user or docker has requested that this container be stopped
|
|
|
|
if m.shouldStop {
|
2015-11-03 14:25:22 -05:00
|
|
|
m.container.HasBeenManuallyStopped = !m.supervisor.IsShuttingDown()
|
2014-08-04 21:20:53 -04:00
|
|
|
return false
|
|
|
|
}
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2015-05-16 07:34:09 -04:00
|
|
|
switch {
|
2015-08-05 17:09:08 -04:00
|
|
|
case m.restartPolicy.IsAlways(), m.restartPolicy.IsUnlessStopped():
|
2014-08-04 21:20:53 -04:00
|
|
|
return true
|
2015-05-16 07:34:09 -04:00
|
|
|
case m.restartPolicy.IsOnFailure():
|
2014-08-04 21:20:53 -04:00
|
|
|
// the default value of 0 for MaximumRetryCount means that we will not enforce a maximum count
|
2015-01-07 02:16:04 -05:00
|
|
|
if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount > max {
|
2015-03-26 18:22:04 -04:00
|
|
|
logrus.Debugf("stopping restart of container %s because maximum failure could of %d has been reached",
|
2015-03-24 07:25:26 -04:00
|
|
|
stringid.TruncateID(m.container.ID), max)
|
2014-08-04 21:20:53 -04:00
|
|
|
return false
|
|
|
|
}
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2014-10-08 13:03:57 -04:00
|
|
|
return exitCode != 0
|
2014-08-04 21:20:53 -04:00
|
|
|
}
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2014-08-04 21:20:53 -04:00
|
|
|
return false
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// callback ensures that the container's state is properly updated after we
|
|
|
|
// received ack from the execution drivers
|
2015-09-29 13:51:40 -04:00
|
|
|
func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error {
|
2015-09-11 06:01:47 -04:00
|
|
|
go func() {
|
2015-12-05 00:01:31 -05:00
|
|
|
for range chOOM {
|
2015-11-03 12:33:13 -05:00
|
|
|
m.logEvent("oom")
|
2015-09-11 06:01:47 -04:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2014-08-26 18:05:37 -04:00
|
|
|
if processConfig.Tty {
|
2015-11-12 14:55:17 -05:00
|
|
|
// The callback is called after the process start()
|
2014-09-28 11:01:35 -04:00
|
|
|
// so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave
|
2014-08-04 20:05:56 -04:00
|
|
|
// which we close here.
|
2014-08-26 18:05:37 -04:00
|
|
|
if c, ok := processConfig.Stdout.(io.Closer); ok {
|
2014-08-04 20:05:56 -04:00
|
|
|
c.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-14 13:38:09 -05:00
|
|
|
m.container.SetRunning(pid)
|
2014-08-04 20:05:56 -04:00
|
|
|
|
2014-08-14 03:01:39 -04:00
|
|
|
// signal that the process has started
|
|
|
|
// close channel only if not closed
|
|
|
|
select {
|
|
|
|
case <-m.startSignal:
|
|
|
|
default:
|
2014-08-13 17:56:35 -04:00
|
|
|
close(m.startSignal)
|
|
|
|
}
|
2014-08-12 21:03:11 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
if err := m.container.ToDiskLocking(); err != nil {
|
2015-07-02 06:24:35 -04:00
|
|
|
logrus.Errorf("Error saving container to disk: %v", err)
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
2015-09-11 15:05:57 -04:00
|
|
|
return nil
|
2014-08-04 20:05:56 -04:00
|
|
|
}
|
2014-08-11 14:07:37 -04:00
|
|
|
|
|
|
|
// resetContainer resets the container's IO and ensures that the command is able to be executed again
|
|
|
|
// by copying the data into a new struct
|
2014-08-28 07:39:27 -04:00
|
|
|
// if lock is true, then container locked during reset
|
|
|
|
func (m *containerMonitor) resetContainer(lock bool) {
|
2014-08-11 14:07:37 -04:00
|
|
|
container := m.container
|
2014-08-28 07:39:27 -04:00
|
|
|
if lock {
|
|
|
|
container.Lock()
|
|
|
|
defer container.Unlock()
|
|
|
|
}
|
2014-08-11 14:07:37 -04:00
|
|
|
|
2015-11-17 19:21:44 -05:00
|
|
|
if err := container.CloseStreams(); err != nil {
|
|
|
|
logrus.Errorf("%s: %s", container.ID, err)
|
2014-08-11 14:07:37 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
if container.Command != nil && container.Command.ProcessConfig.Terminal != nil {
|
|
|
|
if err := container.Command.ProcessConfig.Terminal.Close(); err != nil {
|
2015-03-26 18:22:04 -04:00
|
|
|
logrus.Errorf("%s: Error closing terminal: %s", container.ID, err)
|
2014-08-11 14:07:37 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Re-create a brand new stdin pipe once the container exited
|
|
|
|
if container.Config.OpenStdin {
|
2015-11-17 19:21:44 -05:00
|
|
|
container.NewInputPipes()
|
2014-08-11 14:07:37 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
if container.LogDriver != nil {
|
|
|
|
if container.LogCopier != nil {
|
2015-03-18 14:44:14 -04:00
|
|
|
exit := make(chan struct{})
|
|
|
|
go func() {
|
2015-11-12 14:55:17 -05:00
|
|
|
container.LogCopier.Wait()
|
2015-03-18 14:44:14 -04:00
|
|
|
close(exit)
|
|
|
|
}()
|
|
|
|
select {
|
2015-07-03 09:50:06 -04:00
|
|
|
case <-time.After(loggerCloseTimeout):
|
2015-03-26 18:22:04 -04:00
|
|
|
logrus.Warnf("Logger didn't exit in time: logs may be truncated")
|
2016-01-15 08:42:23 -05:00
|
|
|
container.LogCopier.Close()
|
|
|
|
// always waits for the LogCopier to finished before closing
|
|
|
|
<-exit
|
2015-03-18 14:44:14 -04:00
|
|
|
case <-exit:
|
|
|
|
}
|
|
|
|
}
|
2015-11-12 14:55:17 -05:00
|
|
|
container.LogDriver.Close()
|
|
|
|
container.LogCopier = nil
|
|
|
|
container.LogDriver = nil
|
2015-02-04 14:04:58 -05:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
c := container.Command.ProcessConfig.Cmd
|
2014-08-11 14:07:37 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
container.Command.ProcessConfig.Cmd = exec.Cmd{
|
2014-08-11 14:07:37 -04:00
|
|
|
Stdin: c.Stdin,
|
|
|
|
Stdout: c.Stdout,
|
|
|
|
Stderr: c.Stderr,
|
|
|
|
Path: c.Path,
|
|
|
|
Env: c.Env,
|
|
|
|
ExtraFiles: c.ExtraFiles,
|
|
|
|
Args: c.Args,
|
|
|
|
Dir: c.Dir,
|
|
|
|
SysProcAttr: c.SysProcAttr,
|
|
|
|
}
|
|
|
|
}
|
2015-11-03 12:33:13 -05:00
|
|
|
|
|
|
|
func (m *containerMonitor) logEvent(action string) {
|
|
|
|
m.supervisor.LogContainerEvent(m.container, action)
|
|
|
|
}
|