1package types // import "github.com/docker/docker/api/types"
2
3import (
4	"errors"
5	"fmt"
6	"io"
7	"os"
8	"strings"
9	"time"
10
11	"github.com/docker/docker/api/types/container"
12	"github.com/docker/docker/api/types/filters"
13	"github.com/docker/docker/api/types/mount"
14	"github.com/docker/docker/api/types/network"
15	"github.com/docker/docker/api/types/registry"
16	"github.com/docker/docker/api/types/swarm"
17	"github.com/docker/go-connections/nat"
18)
19
20// RootFS returns Image's RootFS description including the layer IDs.
21type RootFS struct {
22	Type      string
23	Layers    []string `json:",omitempty"`
24	BaseLayer string   `json:",omitempty"`
25}
26
27// ImageInspect contains response of Engine API:
28// GET "/images/{name:.*}/json"
29type ImageInspect struct {
30	ID              string `json:"Id"`
31	RepoTags        []string
32	RepoDigests     []string
33	Parent          string
34	Comment         string
35	Created         string
36	Container       string
37	ContainerConfig *container.Config
38	DockerVersion   string
39	Author          string
40	Config          *container.Config
41	Architecture    string
42	Os              string
43	OsVersion       string `json:",omitempty"`
44	Size            int64
45	VirtualSize     int64
46	GraphDriver     GraphDriverData
47	RootFS          RootFS
48	Metadata        ImageMetadata
49}
50
51// ImageMetadata contains engine-local data about the image
52type ImageMetadata struct {
53	LastTagTime time.Time `json:",omitempty"`
54}
55
56// Container contains response of Engine API:
57// GET "/containers/json"
58type Container struct {
59	ID         string `json:"Id"`
60	Names      []string
61	Image      string
62	ImageID    string
63	Command    string
64	Created    int64
65	Ports      []Port
66	SizeRw     int64 `json:",omitempty"`
67	SizeRootFs int64 `json:",omitempty"`
68	Labels     map[string]string
69	State      string
70	Status     string
71	HostConfig struct {
72		NetworkMode string `json:",omitempty"`
73	}
74	NetworkSettings *SummaryNetworkSettings
75	Mounts          []MountPoint
76}
77
78// CopyConfig contains request body of Engine API:
79// POST "/containers/"+containerID+"/copy"
80type CopyConfig struct {
81	Resource string
82}
83
84// ContainerPathStat is used to encode the header from
85// GET "/containers/{name:.*}/archive"
86// "Name" is the file or directory name.
87type ContainerPathStat struct {
88	Name       string      `json:"name"`
89	Size       int64       `json:"size"`
90	Mode       os.FileMode `json:"mode"`
91	Mtime      time.Time   `json:"mtime"`
92	LinkTarget string      `json:"linkTarget"`
93}
94
95// ContainerStats contains response of Engine API:
96// GET "/stats"
97type ContainerStats struct {
98	Body   io.ReadCloser `json:"body"`
99	OSType string        `json:"ostype"`
100}
101
102// Ping contains response of Engine API:
103// GET "/_ping"
104type Ping struct {
105	APIVersion     string
106	OSType         string
107	Experimental   bool
108	BuilderVersion BuilderVersion
109}
110
111// ComponentVersion describes the version information for a specific component.
112type ComponentVersion struct {
113	Name    string
114	Version string
115	Details map[string]string `json:",omitempty"`
116}
117
118// Version contains response of Engine API:
119// GET "/version"
120type Version struct {
121	Platform   struct{ Name string } `json:",omitempty"`
122	Components []ComponentVersion    `json:",omitempty"`
123
124	// The following fields are deprecated, they relate to the Engine component and are kept for backwards compatibility
125
126	Version       string
127	APIVersion    string `json:"ApiVersion"`
128	MinAPIVersion string `json:"MinAPIVersion,omitempty"`
129	GitCommit     string
130	GoVersion     string
131	Os            string
132	Arch          string
133	KernelVersion string `json:",omitempty"`
134	Experimental  bool   `json:",omitempty"`
135	BuildTime     string `json:",omitempty"`
136}
137
138// Commit holds the Git-commit (SHA1) that a binary was built from, as reported
139// in the version-string of external tools, such as containerd, or runC.
140type Commit struct {
141	ID       string // ID is the actual commit ID of external tool.
142	Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time.
143}
144
145// Info contains response of Engine API:
146// GET "/info"
147type Info struct {
148	ID                 string
149	Containers         int
150	ContainersRunning  int
151	ContainersPaused   int
152	ContainersStopped  int
153	Images             int
154	Driver             string
155	DriverStatus       [][2]string
156	SystemStatus       [][2]string
157	Plugins            PluginsInfo
158	MemoryLimit        bool
159	SwapLimit          bool
160	KernelMemory       bool
161	CPUCfsPeriod       bool `json:"CpuCfsPeriod"`
162	CPUCfsQuota        bool `json:"CpuCfsQuota"`
163	CPUShares          bool
164	CPUSet             bool
165	IPv4Forwarding     bool
166	BridgeNfIptables   bool
167	BridgeNfIP6tables  bool `json:"BridgeNfIp6tables"`
168	Debug              bool
169	NFd                int
170	OomKillDisable     bool
171	NGoroutines        int
172	SystemTime         string
173	LoggingDriver      string
174	CgroupDriver       string
175	NEventsListener    int
176	KernelVersion      string
177	OperatingSystem    string
178	OSType             string
179	Architecture       string
180	IndexServerAddress string
181	RegistryConfig     *registry.ServiceConfig
182	NCPU               int
183	MemTotal           int64
184	GenericResources   []swarm.GenericResource
185	DockerRootDir      string
186	HTTPProxy          string `json:"HttpProxy"`
187	HTTPSProxy         string `json:"HttpsProxy"`
188	NoProxy            string
189	Name               string
190	Labels             []string
191	ExperimentalBuild  bool
192	ServerVersion      string
193	ClusterStore       string
194	ClusterAdvertise   string
195	Runtimes           map[string]Runtime
196	DefaultRuntime     string
197	Swarm              swarm.Info
198	// LiveRestoreEnabled determines whether containers should be kept
199	// running when the daemon is shutdown or upon daemon start if
200	// running containers are detected
201	LiveRestoreEnabled bool
202	Isolation          container.Isolation
203	InitBinary         string
204	ContainerdCommit   Commit
205	RuncCommit         Commit
206	InitCommit         Commit
207	SecurityOptions    []string
208	ProductLicense     string `json:",omitempty"`
209	Warnings           []string
210}
211
212// KeyValue holds a key/value pair
213type KeyValue struct {
214	Key, Value string
215}
216
217// SecurityOpt contains the name and options of a security option
218type SecurityOpt struct {
219	Name    string
220	Options []KeyValue
221}
222
223// DecodeSecurityOptions decodes a security options string slice to a type safe
224// SecurityOpt
225func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) {
226	so := []SecurityOpt{}
227	for _, opt := range opts {
228		// support output from a < 1.13 docker daemon
229		if !strings.Contains(opt, "=") {
230			so = append(so, SecurityOpt{Name: opt})
231			continue
232		}
233		secopt := SecurityOpt{}
234		split := strings.Split(opt, ",")
235		for _, s := range split {
236			kv := strings.SplitN(s, "=", 2)
237			if len(kv) != 2 {
238				return nil, fmt.Errorf("invalid security option %q", s)
239			}
240			if kv[0] == "" || kv[1] == "" {
241				return nil, errors.New("invalid empty security option")
242			}
243			if kv[0] == "name" {
244				secopt.Name = kv[1]
245				continue
246			}
247			secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]})
248		}
249		so = append(so, secopt)
250	}
251	return so, nil
252}
253
254// PluginsInfo is a temp struct holding Plugins name
255// registered with docker daemon. It is used by Info struct
256type PluginsInfo struct {
257	// List of Volume plugins registered
258	Volume []string
259	// List of Network plugins registered
260	Network []string
261	// List of Authorization plugins registered
262	Authorization []string
263	// List of Log plugins registered
264	Log []string
265}
266
267// ExecStartCheck is a temp struct used by execStart
268// Config fields is part of ExecConfig in runconfig package
269type ExecStartCheck struct {
270	// ExecStart will first check if it's detached
271	Detach bool
272	// Check if there's a tty
273	Tty bool
274}
275
276// HealthcheckResult stores information about a single run of a healthcheck probe
277type HealthcheckResult struct {
278	Start    time.Time // Start is the time this check started
279	End      time.Time // End is the time this check ended
280	ExitCode int       // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe
281	Output   string    // Output from last check
282}
283
284// Health states
285const (
286	NoHealthcheck = "none"      // Indicates there is no healthcheck
287	Starting      = "starting"  // Starting indicates that the container is not yet ready
288	Healthy       = "healthy"   // Healthy indicates that the container is running correctly
289	Unhealthy     = "unhealthy" // Unhealthy indicates that the container has a problem
290)
291
292// Health stores information about the container's healthcheck results
293type Health struct {
294	Status        string               // Status is one of Starting, Healthy or Unhealthy
295	FailingStreak int                  // FailingStreak is the number of consecutive failures
296	Log           []*HealthcheckResult // Log contains the last few results (oldest first)
297}
298
299// ContainerState stores container's running state
300// it's part of ContainerJSONBase and will return by "inspect" command
301type ContainerState struct {
302	Status     string // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead"
303	Running    bool
304	Paused     bool
305	Restarting bool
306	OOMKilled  bool
307	Dead       bool
308	Pid        int
309	ExitCode   int
310	Error      string
311	StartedAt  string
312	FinishedAt string
313	Health     *Health `json:",omitempty"`
314}
315
316// ContainerNode stores information about the node that a container
317// is running on.  It's only available in Docker Swarm
318type ContainerNode struct {
319	ID        string
320	IPAddress string `json:"IP"`
321	Addr      string
322	Name      string
323	Cpus      int
324	Memory    int64
325	Labels    map[string]string
326}
327
328// ContainerJSONBase contains response of Engine API:
329// GET "/containers/{name:.*}/json"
330type ContainerJSONBase struct {
331	ID              string `json:"Id"`
332	Created         string
333	Path            string
334	Args            []string
335	State           *ContainerState
336	Image           string
337	ResolvConfPath  string
338	HostnamePath    string
339	HostsPath       string
340	LogPath         string
341	Node            *ContainerNode `json:",omitempty"`
342	Name            string
343	RestartCount    int
344	Driver          string
345	Platform        string
346	MountLabel      string
347	ProcessLabel    string
348	AppArmorProfile string
349	ExecIDs         []string
350	HostConfig      *container.HostConfig
351	GraphDriver     GraphDriverData
352	SizeRw          *int64 `json:",omitempty"`
353	SizeRootFs      *int64 `json:",omitempty"`
354}
355
356// ContainerJSON is newly used struct along with MountPoint
357type ContainerJSON struct {
358	*ContainerJSONBase
359	Mounts          []MountPoint
360	Config          *container.Config
361	NetworkSettings *NetworkSettings
362}
363
364// NetworkSettings exposes the network settings in the api
365type NetworkSettings struct {
366	NetworkSettingsBase
367	DefaultNetworkSettings
368	Networks map[string]*network.EndpointSettings
369}
370
371// SummaryNetworkSettings provides a summary of container's networks
372// in /containers/json
373type SummaryNetworkSettings struct {
374	Networks map[string]*network.EndpointSettings
375}
376
377// NetworkSettingsBase holds basic information about networks
378type NetworkSettingsBase struct {
379	Bridge                 string      // Bridge is the Bridge name the network uses(e.g. `docker0`)
380	SandboxID              string      // SandboxID uniquely represents a container's network stack
381	HairpinMode            bool        // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface
382	LinkLocalIPv6Address   string      // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix
383	LinkLocalIPv6PrefixLen int         // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address
384	Ports                  nat.PortMap // Ports is a collection of PortBinding indexed by Port
385	SandboxKey             string      // SandboxKey identifies the sandbox
386	SecondaryIPAddresses   []network.Address
387	SecondaryIPv6Addresses []network.Address
388}
389
390// DefaultNetworkSettings holds network information
391// during the 2 release deprecation period.
392// It will be removed in Docker 1.11.
393type DefaultNetworkSettings struct {
394	EndpointID          string // EndpointID uniquely represents a service endpoint in a Sandbox
395	Gateway             string // Gateway holds the gateway address for the network
396	GlobalIPv6Address   string // GlobalIPv6Address holds network's global IPv6 address
397	GlobalIPv6PrefixLen int    // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address
398	IPAddress           string // IPAddress holds the IPv4 address for the network
399	IPPrefixLen         int    // IPPrefixLen represents mask length of network's IPv4 address
400	IPv6Gateway         string // IPv6Gateway holds gateway address specific for IPv6
401	MacAddress          string // MacAddress holds the MAC address for the network
402}
403
404// MountPoint represents a mount point configuration inside the container.
405// This is used for reporting the mountpoints in use by a container.
406type MountPoint struct {
407	Type        mount.Type `json:",omitempty"`
408	Name        string     `json:",omitempty"`
409	Source      string
410	Destination string
411	Driver      string `json:",omitempty"`
412	Mode        string
413	RW          bool
414	Propagation mount.Propagation
415}
416
417// NetworkResource is the body of the "get network" http response message
418type NetworkResource struct {
419	Name       string                         // Name is the requested name of the network
420	ID         string                         `json:"Id"` // ID uniquely identifies a network on a single machine
421	Created    time.Time                      // Created is the time the network created
422	Scope      string                         // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level)
423	Driver     string                         // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`)
424	EnableIPv6 bool                           // EnableIPv6 represents whether to enable IPv6
425	IPAM       network.IPAM                   // IPAM is the network's IP Address Management
426	Internal   bool                           // Internal represents if the network is used internal only
427	Attachable bool                           // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode.
428	Ingress    bool                           // Ingress indicates the network is providing the routing-mesh for the swarm cluster.
429	ConfigFrom network.ConfigReference        // ConfigFrom specifies the source which will provide the configuration for this network.
430	ConfigOnly bool                           // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services.
431	Containers map[string]EndpointResource    // Containers contains endpoints belonging to the network
432	Options    map[string]string              // Options holds the network specific options to use for when creating the network
433	Labels     map[string]string              // Labels holds metadata specific to the network being created
434	Peers      []network.PeerInfo             `json:",omitempty"` // List of peer nodes for an overlay network
435	Services   map[string]network.ServiceInfo `json:",omitempty"`
436}
437
438// EndpointResource contains network resources allocated and used for a container in a network
439type EndpointResource struct {
440	Name        string
441	EndpointID  string
442	MacAddress  string
443	IPv4Address string
444	IPv6Address string
445}
446
447// NetworkCreate is the expected body of the "create network" http request message
448type NetworkCreate struct {
449	// Check for networks with duplicate names.
450	// Network is primarily keyed based on a random ID and not on the name.
451	// Network name is strictly a user-friendly alias to the network
452	// which is uniquely identified using ID.
453	// And there is no guaranteed way to check for duplicates.
454	// Option CheckDuplicate is there to provide a best effort checking of any networks
455	// which has the same name but it is not guaranteed to catch all name collisions.
456	CheckDuplicate bool
457	Driver         string
458	Scope          string
459	EnableIPv6     bool
460	IPAM           *network.IPAM
461	Internal       bool
462	Attachable     bool
463	Ingress        bool
464	ConfigOnly     bool
465	ConfigFrom     *network.ConfigReference
466	Options        map[string]string
467	Labels         map[string]string
468}
469
470// NetworkCreateRequest is the request message sent to the server for network create call.
471type NetworkCreateRequest struct {
472	NetworkCreate
473	Name string
474}
475
476// NetworkCreateResponse is the response message sent by the server for network create call
477type NetworkCreateResponse struct {
478	ID      string `json:"Id"`
479	Warning string
480}
481
482// NetworkConnect represents the data to be used to connect a container to the network
483type NetworkConnect struct {
484	Container      string
485	EndpointConfig *network.EndpointSettings `json:",omitempty"`
486}
487
488// NetworkDisconnect represents the data to be used to disconnect a container from the network
489type NetworkDisconnect struct {
490	Container string
491	Force     bool
492}
493
494// NetworkInspectOptions holds parameters to inspect network
495type NetworkInspectOptions struct {
496	Scope   string
497	Verbose bool
498}
499
500// Checkpoint represents the details of a checkpoint
501type Checkpoint struct {
502	Name string // Name is the name of the checkpoint
503}
504
505// Runtime describes an OCI runtime
506type Runtime struct {
507	Path string   `json:"path"`
508	Args []string `json:"runtimeArgs,omitempty"`
509}
510
511// DiskUsage contains response of Engine API:
512// GET "/system/df"
513type DiskUsage struct {
514	LayersSize  int64
515	Images      []*ImageSummary
516	Containers  []*Container
517	Volumes     []*Volume
518	BuildCache  []*BuildCache
519	BuilderSize int64 // deprecated
520}
521
522// ContainersPruneReport contains the response for Engine API:
523// POST "/containers/prune"
524type ContainersPruneReport struct {
525	ContainersDeleted []string
526	SpaceReclaimed    uint64
527}
528
529// VolumesPruneReport contains the response for Engine API:
530// POST "/volumes/prune"
531type VolumesPruneReport struct {
532	VolumesDeleted []string
533	SpaceReclaimed uint64
534}
535
536// ImagesPruneReport contains the response for Engine API:
537// POST "/images/prune"
538type ImagesPruneReport struct {
539	ImagesDeleted  []ImageDeleteResponseItem
540	SpaceReclaimed uint64
541}
542
543// BuildCachePruneReport contains the response for Engine API:
544// POST "/build/prune"
545type BuildCachePruneReport struct {
546	SpaceReclaimed uint64
547}
548
549// NetworksPruneReport contains the response for Engine API:
550// POST "/networks/prune"
551type NetworksPruneReport struct {
552	NetworksDeleted []string
553}
554
555// SecretCreateResponse contains the information returned to a client
556// on the creation of a new secret.
557type SecretCreateResponse struct {
558	// ID is the id of the created secret.
559	ID string
560}
561
562// SecretListOptions holds parameters to list secrets
563type SecretListOptions struct {
564	Filters filters.Args
565}
566
567// ConfigCreateResponse contains the information returned to a client
568// on the creation of a new config.
569type ConfigCreateResponse struct {
570	// ID is the id of the created config.
571	ID string
572}
573
574// ConfigListOptions holds parameters to list configs
575type ConfigListOptions struct {
576	Filters filters.Args
577}
578
579// PushResult contains the tag, manifest digest, and manifest size from the
580// push. It's used to signal this information to the trust code in the client
581// so it can sign the manifest if necessary.
582type PushResult struct {
583	Tag    string
584	Digest string
585	Size   int
586}
587
588// BuildResult contains the image id of a successful build
589type BuildResult struct {
590	ID string
591}
592
593// BuildCache contains information about a build cache record
594type BuildCache struct {
595	ID      string
596	Mutable bool
597	InUse   bool
598	Size    int64
599
600	CreatedAt   time.Time
601	LastUsedAt  *time.Time
602	UsageCount  int
603	Parent      string
604	Description string
605}
606