hostconfig.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package runconfig
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "github.com/docker/docker/api/types/container"
  8. )
  9. // DecodeHostConfig creates a HostConfig based on the specified Reader.
  10. // It assumes the content of the reader will be JSON, and decodes it.
  11. func DecodeHostConfig(src io.Reader) (*container.HostConfig, error) {
  12. decoder := json.NewDecoder(src)
  13. var w ContainerConfigWrapper
  14. if err := decoder.Decode(&w); err != nil {
  15. return nil, err
  16. }
  17. hc := w.getHostConfig()
  18. return hc, nil
  19. }
  20. // SetDefaultNetModeIfBlank changes the NetworkMode in a HostConfig structure
  21. // to default if it is not populated. This ensures backwards compatibility after
  22. // the validation of the network mode was moved from the docker CLI to the
  23. // docker daemon.
  24. func SetDefaultNetModeIfBlank(hc *container.HostConfig) {
  25. if hc != nil {
  26. if hc.NetworkMode == container.NetworkMode("") {
  27. hc.NetworkMode = container.NetworkMode("default")
  28. }
  29. }
  30. }
  31. // validateNetContainerMode ensures that the various combinations of requested
  32. // network settings wrt container mode are valid.
  33. func validateNetContainerMode(c *container.Config, hc *container.HostConfig) error {
  34. // We may not be passed a host config, such as in the case of docker commit
  35. if hc == nil {
  36. return nil
  37. }
  38. parts := strings.Split(string(hc.NetworkMode), ":")
  39. if parts[0] == "container" {
  40. if len(parts) < 2 || parts[1] == "" {
  41. return fmt.Errorf("Invalid network mode: invalid container format container:<name|id>")
  42. }
  43. }
  44. if hc.NetworkMode.IsContainer() && c.Hostname != "" {
  45. return ErrConflictNetworkHostname
  46. }
  47. if hc.NetworkMode.IsContainer() && len(hc.Links) > 0 {
  48. return ErrConflictContainerNetworkAndLinks
  49. }
  50. if hc.NetworkMode.IsContainer() && len(hc.DNS) > 0 {
  51. return ErrConflictNetworkAndDNS
  52. }
  53. if hc.NetworkMode.IsContainer() && len(hc.ExtraHosts) > 0 {
  54. return ErrConflictNetworkHosts
  55. }
  56. if (hc.NetworkMode.IsContainer() || hc.NetworkMode.IsHost()) && c.MacAddress != "" {
  57. return ErrConflictContainerNetworkAndMac
  58. }
  59. if hc.NetworkMode.IsContainer() && (len(hc.PortBindings) > 0 || hc.PublishAllPorts == true) {
  60. return ErrConflictNetworkPublishPorts
  61. }
  62. if hc.NetworkMode.IsContainer() && len(c.ExposedPorts) > 0 {
  63. return ErrConflictNetworkExposePorts
  64. }
  65. return nil
  66. }