config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package configs
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "os/exec"
  7. "time"
  8. "github.com/opencontainers/runtime-spec/specs-go"
  9. "github.com/sirupsen/logrus"
  10. )
  11. type Rlimit struct {
  12. Type int `json:"type"`
  13. Hard uint64 `json:"hard"`
  14. Soft uint64 `json:"soft"`
  15. }
  16. // IDMap represents UID/GID Mappings for User Namespaces.
  17. type IDMap struct {
  18. ContainerID int `json:"container_id"`
  19. HostID int `json:"host_id"`
  20. Size int `json:"size"`
  21. }
  22. // Seccomp represents syscall restrictions
  23. // By default, only the native architecture of the kernel is allowed to be used
  24. // for syscalls. Additional architectures can be added by specifying them in
  25. // Architectures.
  26. type Seccomp struct {
  27. DefaultAction Action `json:"default_action"`
  28. Architectures []string `json:"architectures"`
  29. Syscalls []*Syscall `json:"syscalls"`
  30. }
  31. // Action is taken upon rule match in Seccomp
  32. type Action int
  33. const (
  34. Kill Action = iota + 1
  35. Errno
  36. Trap
  37. Allow
  38. Trace
  39. Log
  40. )
  41. // Operator is a comparison operator to be used when matching syscall arguments in Seccomp
  42. type Operator int
  43. const (
  44. EqualTo Operator = iota + 1
  45. NotEqualTo
  46. GreaterThan
  47. GreaterThanOrEqualTo
  48. LessThan
  49. LessThanOrEqualTo
  50. MaskEqualTo
  51. )
  52. // Arg is a rule to match a specific syscall argument in Seccomp
  53. type Arg struct {
  54. Index uint `json:"index"`
  55. Value uint64 `json:"value"`
  56. ValueTwo uint64 `json:"value_two"`
  57. Op Operator `json:"op"`
  58. }
  59. // Syscall is a rule to match a syscall in Seccomp
  60. type Syscall struct {
  61. Name string `json:"name"`
  62. Action Action `json:"action"`
  63. Args []*Arg `json:"args"`
  64. }
  65. // TODO Windows. Many of these fields should be factored out into those parts
  66. // which are common across platforms, and those which are platform specific.
  67. // Config defines configuration options for executing a process inside a contained environment.
  68. type Config struct {
  69. // NoPivotRoot will use MS_MOVE and a chroot to jail the process into the container's rootfs
  70. // This is a common option when the container is running in ramdisk
  71. NoPivotRoot bool `json:"no_pivot_root"`
  72. // ParentDeathSignal specifies the signal that is sent to the container's process in the case
  73. // that the parent process dies.
  74. ParentDeathSignal int `json:"parent_death_signal"`
  75. // Path to a directory containing the container's root filesystem.
  76. Rootfs string `json:"rootfs"`
  77. // Readonlyfs will remount the container's rootfs as readonly where only externally mounted
  78. // bind mounts are writtable.
  79. Readonlyfs bool `json:"readonlyfs"`
  80. // Specifies the mount propagation flags to be applied to /.
  81. RootPropagation int `json:"rootPropagation"`
  82. // Mounts specify additional source and destination paths that will be mounted inside the container's
  83. // rootfs and mount namespace if specified
  84. Mounts []*Mount `json:"mounts"`
  85. // The device nodes that should be automatically created within the container upon container start. Note, make sure that the node is marked as allowed in the cgroup as well!
  86. Devices []*Device `json:"devices"`
  87. MountLabel string `json:"mount_label"`
  88. // Hostname optionally sets the container's hostname if provided
  89. Hostname string `json:"hostname"`
  90. // Namespaces specifies the container's namespaces that it should setup when cloning the init process
  91. // If a namespace is not provided that namespace is shared from the container's parent process
  92. Namespaces Namespaces `json:"namespaces"`
  93. // Capabilities specify the capabilities to keep when executing the process inside the container
  94. // All capabilities not specified will be dropped from the processes capability mask
  95. Capabilities *Capabilities `json:"capabilities"`
  96. // Networks specifies the container's network setup to be created
  97. Networks []*Network `json:"networks"`
  98. // Routes can be specified to create entries in the route table as the container is started
  99. Routes []*Route `json:"routes"`
  100. // Cgroups specifies specific cgroup settings for the various subsystems that the container is
  101. // placed into to limit the resources the container has available
  102. Cgroups *Cgroup `json:"cgroups"`
  103. // AppArmorProfile specifies the profile to apply to the process running in the container and is
  104. // change at the time the process is execed
  105. AppArmorProfile string `json:"apparmor_profile,omitempty"`
  106. // ProcessLabel specifies the label to apply to the process running in the container. It is
  107. // commonly used by selinux
  108. ProcessLabel string `json:"process_label,omitempty"`
  109. // Rlimits specifies the resource limits, such as max open files, to set in the container
  110. // If Rlimits are not set, the container will inherit rlimits from the parent process
  111. Rlimits []Rlimit `json:"rlimits,omitempty"`
  112. // OomScoreAdj specifies the adjustment to be made by the kernel when calculating oom scores
  113. // for a process. Valid values are between the range [-1000, '1000'], where processes with
  114. // higher scores are preferred for being killed. If it is unset then we don't touch the current
  115. // value.
  116. // More information about kernel oom score calculation here: https://lwn.net/Articles/317814/
  117. OomScoreAdj *int `json:"oom_score_adj,omitempty"`
  118. // UidMappings is an array of User ID mappings for User Namespaces
  119. UidMappings []IDMap `json:"uid_mappings"`
  120. // GidMappings is an array of Group ID mappings for User Namespaces
  121. GidMappings []IDMap `json:"gid_mappings"`
  122. // MaskPaths specifies paths within the container's rootfs to mask over with a bind
  123. // mount pointing to /dev/null as to prevent reads of the file.
  124. MaskPaths []string `json:"mask_paths"`
  125. // ReadonlyPaths specifies paths within the container's rootfs to remount as read-only
  126. // so that these files prevent any writes.
  127. ReadonlyPaths []string `json:"readonly_paths"`
  128. // Sysctl is a map of properties and their values. It is the equivalent of using
  129. // sysctl -w my.property.name value in Linux.
  130. Sysctl map[string]string `json:"sysctl"`
  131. // Seccomp allows actions to be taken whenever a syscall is made within the container.
  132. // A number of rules are given, each having an action to be taken if a syscall matches it.
  133. // A default action to be taken if no rules match is also given.
  134. Seccomp *Seccomp `json:"seccomp"`
  135. // NoNewPrivileges controls whether processes in the container can gain additional privileges.
  136. NoNewPrivileges bool `json:"no_new_privileges,omitempty"`
  137. // Hooks are a collection of actions to perform at various container lifecycle events.
  138. // CommandHooks are serialized to JSON, but other hooks are not.
  139. Hooks *Hooks
  140. // Version is the version of opencontainer specification that is supported.
  141. Version string `json:"version"`
  142. // Labels are user defined metadata that is stored in the config and populated on the state
  143. Labels []string `json:"labels"`
  144. // NoNewKeyring will not allocated a new session keyring for the container. It will use the
  145. // callers keyring in this case.
  146. NoNewKeyring bool `json:"no_new_keyring"`
  147. // IntelRdt specifies settings for Intel RDT group that the container is placed into
  148. // to limit the resources (e.g., L3 cache, memory bandwidth) the container has available
  149. IntelRdt *IntelRdt `json:"intel_rdt,omitempty"`
  150. // RootlessEUID is set when the runc was launched with non-zero EUID.
  151. // Note that RootlessEUID is set to false when launched with EUID=0 in userns.
  152. // When RootlessEUID is set, runc creates a new userns for the container.
  153. // (config.json needs to contain userns settings)
  154. RootlessEUID bool `json:"rootless_euid,omitempty"`
  155. // RootlessCgroups is set when unlikely to have the full access to cgroups.
  156. // When RootlessCgroups is set, cgroups errors are ignored.
  157. RootlessCgroups bool `json:"rootless_cgroups,omitempty"`
  158. }
  159. type Hooks struct {
  160. // Prestart commands are executed after the container namespaces are created,
  161. // but before the user supplied command is executed from init.
  162. Prestart []Hook
  163. // Poststart commands are executed after the container init process starts.
  164. Poststart []Hook
  165. // Poststop commands are executed after the container init process exits.
  166. Poststop []Hook
  167. }
  168. type Capabilities struct {
  169. // Bounding is the set of capabilities checked by the kernel.
  170. Bounding []string
  171. // Effective is the set of capabilities checked by the kernel.
  172. Effective []string
  173. // Inheritable is the capabilities preserved across execve.
  174. Inheritable []string
  175. // Permitted is the limiting superset for effective capabilities.
  176. Permitted []string
  177. // Ambient is the ambient set of capabilities that are kept.
  178. Ambient []string
  179. }
  180. func (hooks *Hooks) UnmarshalJSON(b []byte) error {
  181. var state struct {
  182. Prestart []CommandHook
  183. Poststart []CommandHook
  184. Poststop []CommandHook
  185. }
  186. if err := json.Unmarshal(b, &state); err != nil {
  187. return err
  188. }
  189. deserialize := func(shooks []CommandHook) (hooks []Hook) {
  190. for _, shook := range shooks {
  191. hooks = append(hooks, shook)
  192. }
  193. return hooks
  194. }
  195. hooks.Prestart = deserialize(state.Prestart)
  196. hooks.Poststart = deserialize(state.Poststart)
  197. hooks.Poststop = deserialize(state.Poststop)
  198. return nil
  199. }
  200. func (hooks Hooks) MarshalJSON() ([]byte, error) {
  201. serialize := func(hooks []Hook) (serializableHooks []CommandHook) {
  202. for _, hook := range hooks {
  203. switch chook := hook.(type) {
  204. case CommandHook:
  205. serializableHooks = append(serializableHooks, chook)
  206. default:
  207. logrus.Warnf("cannot serialize hook of type %T, skipping", hook)
  208. }
  209. }
  210. return serializableHooks
  211. }
  212. return json.Marshal(map[string]interface{}{
  213. "prestart": serialize(hooks.Prestart),
  214. "poststart": serialize(hooks.Poststart),
  215. "poststop": serialize(hooks.Poststop),
  216. })
  217. }
  218. type Hook interface {
  219. // Run executes the hook with the provided state.
  220. Run(*specs.State) error
  221. }
  222. // NewFunctionHook will call the provided function when the hook is run.
  223. func NewFunctionHook(f func(*specs.State) error) FuncHook {
  224. return FuncHook{
  225. run: f,
  226. }
  227. }
  228. type FuncHook struct {
  229. run func(*specs.State) error
  230. }
  231. func (f FuncHook) Run(s *specs.State) error {
  232. return f.run(s)
  233. }
  234. type Command struct {
  235. Path string `json:"path"`
  236. Args []string `json:"args"`
  237. Env []string `json:"env"`
  238. Dir string `json:"dir"`
  239. Timeout *time.Duration `json:"timeout"`
  240. }
  241. // NewCommandHook will execute the provided command when the hook is run.
  242. func NewCommandHook(cmd Command) CommandHook {
  243. return CommandHook{
  244. Command: cmd,
  245. }
  246. }
  247. type CommandHook struct {
  248. Command
  249. }
  250. func (c Command) Run(s *specs.State) error {
  251. b, err := json.Marshal(s)
  252. if err != nil {
  253. return err
  254. }
  255. var stdout, stderr bytes.Buffer
  256. cmd := exec.Cmd{
  257. Path: c.Path,
  258. Args: c.Args,
  259. Env: c.Env,
  260. Stdin: bytes.NewReader(b),
  261. Stdout: &stdout,
  262. Stderr: &stderr,
  263. }
  264. if err := cmd.Start(); err != nil {
  265. return err
  266. }
  267. errC := make(chan error, 1)
  268. go func() {
  269. err := cmd.Wait()
  270. if err != nil {
  271. err = fmt.Errorf("error running hook: %v, stdout: %s, stderr: %s", err, stdout.String(), stderr.String())
  272. }
  273. errC <- err
  274. }()
  275. var timerCh <-chan time.Time
  276. if c.Timeout != nil {
  277. timer := time.NewTimer(*c.Timeout)
  278. defer timer.Stop()
  279. timerCh = timer.C
  280. }
  281. select {
  282. case err := <-errC:
  283. return err
  284. case <-timerCh:
  285. cmd.Process.Kill()
  286. cmd.Wait()
  287. return fmt.Errorf("hook ran past specified timeout of %.1fs", c.Timeout.Seconds())
  288. }
  289. }