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