github.com/chenchun/docker@v1.3.2-0.20150629222414-20467faf132b/daemon/execdriver/lxc/lxc_template.go (about)

     1  // +build linux
     2  
     3  package lxc
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"strings"
     9  	"text/template"
    10  
    11  	"github.com/Sirupsen/logrus"
    12  	"github.com/docker/docker/daemon/execdriver"
    13  	nativeTemplate "github.com/docker/docker/daemon/execdriver/native/template"
    14  	"github.com/docker/docker/pkg/stringutils"
    15  	"github.com/docker/libcontainer/label"
    16  )
    17  
    18  const LxcTemplate = `
    19  lxc.network.type = none
    20  # root filesystem
    21  {{$ROOTFS := .Rootfs}}
    22  lxc.rootfs = {{$ROOTFS}}
    23  
    24  # use a dedicated pts for the container (and limit the number of pseudo terminal
    25  # available)
    26  lxc.pts = 1024
    27  
    28  # disable the main console
    29  lxc.console = none
    30  
    31  # no controlling tty at all
    32  lxc.tty = 1
    33  
    34  {{if .ProcessConfig.Privileged}}
    35  lxc.cgroup.devices.allow = a
    36  {{else}}
    37  # no implicit access to devices
    38  lxc.cgroup.devices.deny = a
    39  #Allow the devices passed to us in the AllowedDevices list.
    40  {{range $allowedDevice := .AllowedDevices}}
    41  lxc.cgroup.devices.allow = {{$allowedDevice.CgroupString}}
    42  {{end}}
    43  {{end}}
    44  
    45  # standard mount point
    46  # Use mnt.putold as per https://bugs.launchpad.net/ubuntu/+source/lxc/+bug/986385
    47  lxc.pivotdir = lxc_putold
    48  
    49  # lxc.autodev is not compatible with lxc --device switch
    50  lxc.autodev = 0
    51  
    52  # NOTICE: These mounts must be applied within the namespace
    53  {{if .ProcessConfig.Privileged}}
    54  # WARNING: mounting procfs and/or sysfs read-write is a known attack vector.
    55  # See e.g. http://blog.zx2c4.com/749 and https://bit.ly/T9CkqJ
    56  # We mount them read-write here, but later, dockerinit will call the Restrict() function to remount them read-only.
    57  # We cannot mount them directly read-only, because that would prevent loading AppArmor profiles.
    58  lxc.mount.entry = proc {{escapeFstabSpaces $ROOTFS}}/proc proc nosuid,nodev,noexec 0 0
    59  lxc.mount.entry = sysfs {{escapeFstabSpaces $ROOTFS}}/sys sysfs nosuid,nodev,noexec 0 0
    60  	{{if .AppArmor}}
    61  lxc.aa_profile = unconfined
    62  	{{end}}
    63  {{else}}
    64  # In non-privileged mode, lxc will automatically mount /proc and /sys in readonly mode
    65  # for security. See: http://man7.org/linux/man-pages/man5/lxc.container.conf.5.html
    66  lxc.mount.auto = proc sys
    67  	{{if .AppArmorProfile}}
    68  lxc.aa_profile = {{.AppArmorProfile}}
    69  	{{end}}
    70  {{end}}
    71  
    72  {{if .ProcessConfig.Tty}}
    73  lxc.mount.entry = {{.ProcessConfig.Console}} {{escapeFstabSpaces $ROOTFS}}/dev/console none bind,rw,create=file 0 0
    74  {{end}}
    75  
    76  lxc.mount.entry = devpts {{escapeFstabSpaces $ROOTFS}}/dev/pts devpts {{formatMountLabel "newinstance,ptmxmode=0666,nosuid,noexec,create=dir" ""}} 0 0
    77  lxc.mount.entry = shm {{escapeFstabSpaces $ROOTFS}}/dev/shm tmpfs {{formatMountLabel "size=65536k,nosuid,nodev,noexec,create=dir" ""}} 0 0
    78  
    79  {{range $value := .Mounts}}
    80  {{$createVal := isDirectory $value.Source}}
    81  {{if $value.Writable}}
    82  lxc.mount.entry = {{$value.Source}} {{escapeFstabSpaces $ROOTFS}}/{{escapeFstabSpaces $value.Destination}} none rbind,rw,create={{$createVal}} 0 0
    83  {{else}}
    84  lxc.mount.entry = {{$value.Source}} {{escapeFstabSpaces $ROOTFS}}/{{escapeFstabSpaces $value.Destination}} none rbind,ro,create={{$createVal}} 0 0
    85  {{end}}
    86  {{end}}
    87  
    88  # limits
    89  {{if .Resources}}
    90  {{if .Resources.Memory}}
    91  lxc.cgroup.memory.limit_in_bytes = {{.Resources.Memory}}
    92  lxc.cgroup.memory.soft_limit_in_bytes = {{.Resources.Memory}}
    93  {{with $memSwap := getMemorySwap .Resources}}
    94  lxc.cgroup.memory.memsw.limit_in_bytes = {{$memSwap}}
    95  {{end}}
    96  {{end}}
    97  {{if .Resources.CpuShares}}
    98  lxc.cgroup.cpu.shares = {{.Resources.CpuShares}}
    99  {{end}}
   100  {{if .Resources.CpuPeriod}}
   101  lxc.cgroup.cpu.cfs_period_us = {{.Resources.CpuPeriod}}
   102  {{end}}
   103  {{if .Resources.CpusetCpus}}
   104  lxc.cgroup.cpuset.cpus = {{.Resources.CpusetCpus}}
   105  {{end}}
   106  {{if .Resources.CpusetMems}}
   107  lxc.cgroup.cpuset.mems = {{.Resources.CpusetMems}}
   108  {{end}}
   109  {{if .Resources.CpuQuota}}
   110  lxc.cgroup.cpu.cfs_quota_us = {{.Resources.CpuQuota}}
   111  {{end}}
   112  {{if .Resources.BlkioWeight}}
   113  lxc.cgroup.blkio.weight = {{.Resources.BlkioWeight}}
   114  {{end}}
   115  {{if .Resources.OomKillDisable}}
   116  lxc.cgroup.memory.oom_control = {{.Resources.OomKillDisable}}
   117  {{end}}
   118  {{end}}
   119  
   120  {{if .LxcConfig}}
   121  {{range $value := .LxcConfig}}
   122  lxc.{{$value}}
   123  {{end}}
   124  {{end}}
   125  
   126  {{if .Network.Interface}}
   127  {{if .Network.Interface.IPAddress}}
   128  lxc.network.ipv4 = {{.Network.Interface.IPAddress}}/{{.Network.Interface.IPPrefixLen}}
   129  {{end}}
   130  {{if .Network.Interface.Gateway}}
   131  lxc.network.ipv4.gateway = {{.Network.Interface.Gateway}}
   132  {{end}}
   133  {{if .Network.Interface.MacAddress}}
   134  lxc.network.hwaddr = {{.Network.Interface.MacAddress}}
   135  {{end}}
   136  {{end}}
   137  {{if .ProcessConfig.Env}}
   138  lxc.utsname = {{getHostname .ProcessConfig.Env}}
   139  {{end}}
   140  
   141  {{if .ProcessConfig.Privileged}}
   142  # No cap values are needed, as lxc is starting in privileged mode
   143  {{else}}
   144  	{{ with keepCapabilities .CapAdd .CapDrop }}
   145  		{{range .}}
   146  lxc.cap.keep = {{.}}
   147  		{{end}}
   148  	{{else}}
   149  		{{ with dropList .CapDrop }}
   150  		{{range .}}
   151  lxc.cap.drop = {{.}}
   152  		{{end}}
   153  		{{end}}
   154  	{{end}}
   155  {{end}}
   156  `
   157  
   158  var LxcTemplateCompiled *template.Template
   159  
   160  // Escape spaces in strings according to the fstab documentation, which is the
   161  // format for "lxc.mount.entry" lines in lxc.conf. See also "man 5 fstab".
   162  func escapeFstabSpaces(field string) string {
   163  	return strings.Replace(field, " ", "\\040", -1)
   164  }
   165  
   166  func keepCapabilities(adds []string, drops []string) ([]string, error) {
   167  	container := nativeTemplate.New()
   168  	logrus.Debugf("adds %s drops %s\n", adds, drops)
   169  	caps, err := execdriver.TweakCapabilities(container.Capabilities, adds, drops)
   170  	if err != nil {
   171  		return nil, err
   172  	}
   173  	var newCaps []string
   174  	for _, cap := range caps {
   175  		logrus.Debugf("cap %s\n", cap)
   176  		realCap := execdriver.GetCapability(cap)
   177  		numCap := fmt.Sprintf("%d", realCap.Value)
   178  		newCaps = append(newCaps, numCap)
   179  	}
   180  
   181  	return newCaps, nil
   182  }
   183  
   184  func dropList(drops []string) ([]string, error) {
   185  	if stringutils.InSlice(drops, "all") {
   186  		var newCaps []string
   187  		for _, capName := range execdriver.GetAllCapabilities() {
   188  			cap := execdriver.GetCapability(capName)
   189  			logrus.Debugf("drop cap %s\n", cap.Key)
   190  			numCap := fmt.Sprintf("%d", cap.Value)
   191  			newCaps = append(newCaps, numCap)
   192  		}
   193  		return newCaps, nil
   194  	}
   195  	return []string{}, nil
   196  }
   197  
   198  func isDirectory(source string) string {
   199  	f, err := os.Stat(source)
   200  	logrus.Debugf("dir: %s\n", source)
   201  	if err != nil {
   202  		if os.IsNotExist(err) {
   203  			return "dir"
   204  		}
   205  		return ""
   206  	}
   207  	if f.IsDir() {
   208  		return "dir"
   209  	}
   210  	return "file"
   211  }
   212  
   213  func getMemorySwap(v *execdriver.Resources) int64 {
   214  	// By default, MemorySwap is set to twice the size of RAM.
   215  	// If you want to omit MemorySwap, set it to `-1'.
   216  	if v.MemorySwap < 0 {
   217  		return 0
   218  	}
   219  	return v.Memory * 2
   220  }
   221  
   222  func getLabel(c map[string][]string, name string) string {
   223  	label := c["label"]
   224  	for _, l := range label {
   225  		parts := strings.SplitN(l, "=", 2)
   226  		if strings.TrimSpace(parts[0]) == name {
   227  			return strings.TrimSpace(parts[1])
   228  		}
   229  	}
   230  	return ""
   231  }
   232  
   233  func getHostname(env []string) string {
   234  	for _, kv := range env {
   235  		parts := strings.SplitN(kv, "=", 2)
   236  		if parts[0] == "HOSTNAME" && len(parts) == 2 {
   237  			return parts[1]
   238  		}
   239  	}
   240  	return ""
   241  }
   242  
   243  func init() {
   244  	var err error
   245  	funcMap := template.FuncMap{
   246  		"getMemorySwap":     getMemorySwap,
   247  		"escapeFstabSpaces": escapeFstabSpaces,
   248  		"formatMountLabel":  label.FormatMountLabel,
   249  		"isDirectory":       isDirectory,
   250  		"keepCapabilities":  keepCapabilities,
   251  		"dropList":          dropList,
   252  		"getHostname":       getHostname,
   253  	}
   254  	LxcTemplateCompiled, err = template.New("lxc").Funcs(funcMap).Parse(LxcTemplate)
   255  	if err != nil {
   256  		panic(err)
   257  	}
   258  }