list.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. package daemon
  2. import (
  3. "errors"
  4. "fmt"
  5. "sort"
  6. "strconv"
  7. "strings"
  8. "github.com/Sirupsen/logrus"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/filters"
  11. networktypes "github.com/docker/docker/api/types/network"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/image"
  14. "github.com/docker/docker/volume"
  15. "github.com/docker/go-connections/nat"
  16. )
  17. var acceptedVolumeFilterTags = map[string]bool{
  18. "dangling": true,
  19. "name": true,
  20. "driver": true,
  21. "label": true,
  22. }
  23. var acceptedPsFilterTags = map[string]bool{
  24. "ancestor": true,
  25. "before": true,
  26. "exited": true,
  27. "id": true,
  28. "isolation": true,
  29. "label": true,
  30. "name": true,
  31. "status": true,
  32. "health": true,
  33. "since": true,
  34. "volume": true,
  35. "network": true,
  36. "is-task": true,
  37. }
  38. // iterationAction represents possible outcomes happening during the container iteration.
  39. type iterationAction int
  40. // containerReducer represents a reducer for a container.
  41. // Returns the object to serialize by the api.
  42. type containerReducer func(*container.Container, *listContext) (*types.Container, error)
  43. const (
  44. // includeContainer is the action to include a container in the reducer.
  45. includeContainer iterationAction = iota
  46. // excludeContainer is the action to exclude a container in the reducer.
  47. excludeContainer
  48. // stopIteration is the action to stop iterating over the list of containers.
  49. stopIteration
  50. )
  51. // errStopIteration makes the iterator to stop without returning an error.
  52. var errStopIteration = errors.New("container list iteration stopped")
  53. // List returns an array of all containers registered in the daemon.
  54. func (daemon *Daemon) List() []*container.Container {
  55. return daemon.containers.List()
  56. }
  57. // listContext is the daemon generated filtering to iterate over containers.
  58. // This is created based on the user specification from types.ContainerListOptions.
  59. type listContext struct {
  60. // idx is the container iteration index for this context
  61. idx int
  62. // ancestorFilter tells whether it should check ancestors or not
  63. ancestorFilter bool
  64. // names is a list of container names to filter with
  65. names map[string][]string
  66. // images is a list of images to filter with
  67. images map[image.ID]bool
  68. // filters is a collection of arguments to filter with, specified by the user
  69. filters filters.Args
  70. // exitAllowed is a list of exit codes allowed to filter with
  71. exitAllowed []int
  72. // beforeFilter is a filter to ignore containers that appear before the one given
  73. beforeFilter *container.Container
  74. // sinceFilter is a filter to stop the filtering when the iterator arrive to the given container
  75. sinceFilter *container.Container
  76. // taskFilter tells if we should filter based on wether a container is part of a task
  77. taskFilter bool
  78. // isTask tells us if the we should filter container that are a task (true) or not (false)
  79. isTask bool
  80. // ContainerListOptions is the filters set by the user
  81. *types.ContainerListOptions
  82. }
  83. // byContainerCreated is a temporary type used to sort a list of containers by creation time.
  84. type byContainerCreated []*container.Container
  85. func (r byContainerCreated) Len() int { return len(r) }
  86. func (r byContainerCreated) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
  87. func (r byContainerCreated) Less(i, j int) bool {
  88. return r[i].Created.UnixNano() < r[j].Created.UnixNano()
  89. }
  90. // Containers returns the list of containers to show given the user's filtering.
  91. func (daemon *Daemon) Containers(config *types.ContainerListOptions) ([]*types.Container, error) {
  92. return daemon.reduceContainers(config, daemon.transformContainer)
  93. }
  94. func (daemon *Daemon) filterByNameIDMatches(ctx *listContext) []*container.Container {
  95. idSearch := false
  96. names := ctx.filters.Get("name")
  97. ids := ctx.filters.Get("id")
  98. if len(names)+len(ids) == 0 {
  99. // if name or ID filters are not in use, return to
  100. // standard behavior of walking the entire container
  101. // list from the daemon's in-memory store
  102. return daemon.List()
  103. }
  104. // idSearch will determine if we limit name matching to the IDs
  105. // matched from any IDs which were specified as filters
  106. if len(ids) > 0 {
  107. idSearch = true
  108. }
  109. matches := make(map[string]bool)
  110. // find ID matches; errors represent "not found" and can be ignored
  111. for _, id := range ids {
  112. if fullID, err := daemon.idIndex.Get(id); err == nil {
  113. matches[fullID] = true
  114. }
  115. }
  116. // look for name matches; if ID filtering was used, then limit the
  117. // search space to the matches map only; errors represent "not found"
  118. // and can be ignored
  119. if len(names) > 0 {
  120. for id, idNames := range ctx.names {
  121. // if ID filters were used and no matches on that ID were
  122. // found, continue to next ID in the list
  123. if idSearch && !matches[id] {
  124. continue
  125. }
  126. for _, eachName := range idNames {
  127. if ctx.filters.Match("name", eachName) {
  128. matches[id] = true
  129. }
  130. }
  131. }
  132. }
  133. cntrs := make([]*container.Container, 0, len(matches))
  134. for id := range matches {
  135. if c := daemon.containers.Get(id); c != nil {
  136. cntrs = append(cntrs, c)
  137. }
  138. }
  139. // Restore sort-order after filtering
  140. // Created gives us nanosec resolution for sorting
  141. sort.Sort(sort.Reverse(byContainerCreated(cntrs)))
  142. return cntrs
  143. }
  144. // reduceContainers parses the user's filtering options and generates the list of containers to return based on a reducer.
  145. func (daemon *Daemon) reduceContainers(config *types.ContainerListOptions, reducer containerReducer) ([]*types.Container, error) {
  146. var (
  147. containers = []*types.Container{}
  148. )
  149. ctx, err := daemon.foldFilter(config)
  150. if err != nil {
  151. return nil, err
  152. }
  153. // fastpath to only look at a subset of containers if specific name
  154. // or ID matches were provided by the user--otherwise we potentially
  155. // end up locking and querying many more containers than intended
  156. containerList := daemon.filterByNameIDMatches(ctx)
  157. for _, container := range containerList {
  158. t, err := daemon.reducePsContainer(container, ctx, reducer)
  159. if err != nil {
  160. if err != errStopIteration {
  161. return nil, err
  162. }
  163. break
  164. }
  165. if t != nil {
  166. containers = append(containers, t)
  167. ctx.idx++
  168. }
  169. }
  170. return containers, nil
  171. }
  172. // reducePsContainer is the basic representation for a container as expected by the ps command.
  173. func (daemon *Daemon) reducePsContainer(container *container.Container, ctx *listContext, reducer containerReducer) (*types.Container, error) {
  174. container.Lock()
  175. defer container.Unlock()
  176. // filter containers to return
  177. action := includeContainerInList(container, ctx)
  178. switch action {
  179. case excludeContainer:
  180. return nil, nil
  181. case stopIteration:
  182. return nil, errStopIteration
  183. }
  184. // transform internal container struct into api structs
  185. return reducer(container, ctx)
  186. }
  187. // foldFilter generates the container filter based on the user's filtering options.
  188. func (daemon *Daemon) foldFilter(config *types.ContainerListOptions) (*listContext, error) {
  189. psFilters := config.Filters
  190. if err := psFilters.Validate(acceptedPsFilterTags); err != nil {
  191. return nil, err
  192. }
  193. var filtExited []int
  194. err := psFilters.WalkValues("exited", func(value string) error {
  195. code, err := strconv.Atoi(value)
  196. if err != nil {
  197. return err
  198. }
  199. filtExited = append(filtExited, code)
  200. return nil
  201. })
  202. if err != nil {
  203. return nil, err
  204. }
  205. err = psFilters.WalkValues("status", func(value string) error {
  206. if !container.IsValidStateString(value) {
  207. return fmt.Errorf("Unrecognised filter value for status: %s", value)
  208. }
  209. config.All = true
  210. return nil
  211. })
  212. if err != nil {
  213. return nil, err
  214. }
  215. var taskFilter, isTask bool
  216. if psFilters.Include("is-task") {
  217. if psFilters.ExactMatch("is-task", "true") {
  218. taskFilter = true
  219. isTask = true
  220. } else if psFilters.ExactMatch("is-task", "false") {
  221. taskFilter = true
  222. isTask = false
  223. } else {
  224. return nil, fmt.Errorf("Invalid filter 'is-task=%s'", psFilters.Get("is-task"))
  225. }
  226. }
  227. err = psFilters.WalkValues("health", func(value string) error {
  228. if !container.IsValidHealthString(value) {
  229. return fmt.Errorf("Unrecognised filter value for health: %s", value)
  230. }
  231. return nil
  232. })
  233. if err != nil {
  234. return nil, err
  235. }
  236. var beforeContFilter, sinceContFilter *container.Container
  237. err = psFilters.WalkValues("before", func(value string) error {
  238. beforeContFilter, err = daemon.GetContainer(value)
  239. return err
  240. })
  241. if err != nil {
  242. return nil, err
  243. }
  244. err = psFilters.WalkValues("since", func(value string) error {
  245. sinceContFilter, err = daemon.GetContainer(value)
  246. return err
  247. })
  248. if err != nil {
  249. return nil, err
  250. }
  251. imagesFilter := map[image.ID]bool{}
  252. var ancestorFilter bool
  253. if psFilters.Include("ancestor") {
  254. ancestorFilter = true
  255. psFilters.WalkValues("ancestor", func(ancestor string) error {
  256. id, err := daemon.GetImageID(ancestor)
  257. if err != nil {
  258. logrus.Warnf("Error while looking up for image %v", ancestor)
  259. return nil
  260. }
  261. if imagesFilter[id] {
  262. // Already seen this ancestor, skip it
  263. return nil
  264. }
  265. // Then walk down the graph and put the imageIds in imagesFilter
  266. populateImageFilterByParents(imagesFilter, id, daemon.imageStore.Children)
  267. return nil
  268. })
  269. }
  270. return &listContext{
  271. filters: psFilters,
  272. ancestorFilter: ancestorFilter,
  273. images: imagesFilter,
  274. exitAllowed: filtExited,
  275. beforeFilter: beforeContFilter,
  276. sinceFilter: sinceContFilter,
  277. taskFilter: taskFilter,
  278. isTask: isTask,
  279. ContainerListOptions: config,
  280. names: daemon.nameIndex.GetAll(),
  281. }, nil
  282. }
  283. // includeContainerInList decides whether a container should be included in the output or not based in the filter.
  284. // It also decides if the iteration should be stopped or not.
  285. func includeContainerInList(container *container.Container, ctx *listContext) iterationAction {
  286. // Do not include container if it's in the list before the filter container.
  287. // Set the filter container to nil to include the rest of containers after this one.
  288. if ctx.beforeFilter != nil {
  289. if container.ID == ctx.beforeFilter.ID {
  290. ctx.beforeFilter = nil
  291. }
  292. return excludeContainer
  293. }
  294. // Stop iteration when the container arrives to the filter container
  295. if ctx.sinceFilter != nil {
  296. if container.ID == ctx.sinceFilter.ID {
  297. return stopIteration
  298. }
  299. }
  300. // Do not include container if it's stopped and we're not filters
  301. if !container.Running && !ctx.All && ctx.Limit <= 0 {
  302. return excludeContainer
  303. }
  304. // Do not include container if the name doesn't match
  305. if !ctx.filters.Match("name", container.Name) {
  306. return excludeContainer
  307. }
  308. // Do not include container if the id doesn't match
  309. if !ctx.filters.Match("id", container.ID) {
  310. return excludeContainer
  311. }
  312. if ctx.taskFilter {
  313. if ctx.isTask != container.Managed {
  314. return excludeContainer
  315. }
  316. }
  317. // Do not include container if any of the labels don't match
  318. if !ctx.filters.MatchKVList("label", container.Config.Labels) {
  319. return excludeContainer
  320. }
  321. // Do not include container if isolation doesn't match
  322. if excludeContainer == excludeByIsolation(container, ctx) {
  323. return excludeContainer
  324. }
  325. // Stop iteration when the index is over the limit
  326. if ctx.Limit > 0 && ctx.idx == ctx.Limit {
  327. return stopIteration
  328. }
  329. // Do not include container if its exit code is not in the filter
  330. if len(ctx.exitAllowed) > 0 {
  331. shouldSkip := true
  332. for _, code := range ctx.exitAllowed {
  333. if code == container.ExitCode() && !container.Running && !container.StartedAt.IsZero() {
  334. shouldSkip = false
  335. break
  336. }
  337. }
  338. if shouldSkip {
  339. return excludeContainer
  340. }
  341. }
  342. // Do not include container if its status doesn't match the filter
  343. if !ctx.filters.Match("status", container.State.StateString()) {
  344. return excludeContainer
  345. }
  346. // Do not include container if its health doesn't match the filter
  347. if !ctx.filters.ExactMatch("health", container.State.HealthString()) {
  348. return excludeContainer
  349. }
  350. if ctx.filters.Include("volume") {
  351. volumesByName := make(map[string]*volume.MountPoint)
  352. for _, m := range container.MountPoints {
  353. if m.Name != "" {
  354. volumesByName[m.Name] = m
  355. } else {
  356. volumesByName[m.Source] = m
  357. }
  358. }
  359. volumeExist := fmt.Errorf("volume mounted in container")
  360. err := ctx.filters.WalkValues("volume", func(value string) error {
  361. if _, exist := container.MountPoints[value]; exist {
  362. return volumeExist
  363. }
  364. if _, exist := volumesByName[value]; exist {
  365. return volumeExist
  366. }
  367. return nil
  368. })
  369. if err != volumeExist {
  370. return excludeContainer
  371. }
  372. }
  373. if ctx.ancestorFilter {
  374. if len(ctx.images) == 0 {
  375. return excludeContainer
  376. }
  377. if !ctx.images[container.ImageID] {
  378. return excludeContainer
  379. }
  380. }
  381. networkExist := fmt.Errorf("container part of network")
  382. if ctx.filters.Include("network") {
  383. err := ctx.filters.WalkValues("network", func(value string) error {
  384. if _, ok := container.NetworkSettings.Networks[value]; ok {
  385. return networkExist
  386. }
  387. for _, nw := range container.NetworkSettings.Networks {
  388. if nw.EndpointSettings == nil {
  389. continue
  390. }
  391. if nw.NetworkID == value {
  392. return networkExist
  393. }
  394. }
  395. return nil
  396. })
  397. if err != networkExist {
  398. return excludeContainer
  399. }
  400. }
  401. return includeContainer
  402. }
  403. // transformContainer generates the container type expected by the docker ps command.
  404. func (daemon *Daemon) transformContainer(container *container.Container, ctx *listContext) (*types.Container, error) {
  405. newC := &types.Container{
  406. ID: container.ID,
  407. Names: ctx.names[container.ID],
  408. ImageID: container.ImageID.String(),
  409. }
  410. if newC.Names == nil {
  411. // Dead containers will often have no name, so make sure the response isn't null
  412. newC.Names = []string{}
  413. }
  414. image := container.Config.Image // if possible keep the original ref
  415. if image != container.ImageID.String() {
  416. id, err := daemon.GetImageID(image)
  417. if _, isDNE := err.(ErrImageDoesNotExist); err != nil && !isDNE {
  418. return nil, err
  419. }
  420. if err != nil || id != container.ImageID {
  421. image = container.ImageID.String()
  422. }
  423. }
  424. newC.Image = image
  425. if len(container.Args) > 0 {
  426. args := []string{}
  427. for _, arg := range container.Args {
  428. if strings.Contains(arg, " ") {
  429. args = append(args, fmt.Sprintf("'%s'", arg))
  430. } else {
  431. args = append(args, arg)
  432. }
  433. }
  434. argsAsString := strings.Join(args, " ")
  435. newC.Command = fmt.Sprintf("%s %s", container.Path, argsAsString)
  436. } else {
  437. newC.Command = container.Path
  438. }
  439. newC.Created = container.Created.Unix()
  440. newC.State = container.State.StateString()
  441. newC.Status = container.State.String()
  442. newC.HostConfig.NetworkMode = string(container.HostConfig.NetworkMode)
  443. // copy networks to avoid races
  444. networks := make(map[string]*networktypes.EndpointSettings)
  445. for name, network := range container.NetworkSettings.Networks {
  446. if network == nil || network.EndpointSettings == nil {
  447. continue
  448. }
  449. networks[name] = &networktypes.EndpointSettings{
  450. EndpointID: network.EndpointID,
  451. Gateway: network.Gateway,
  452. IPAddress: network.IPAddress,
  453. IPPrefixLen: network.IPPrefixLen,
  454. IPv6Gateway: network.IPv6Gateway,
  455. GlobalIPv6Address: network.GlobalIPv6Address,
  456. GlobalIPv6PrefixLen: network.GlobalIPv6PrefixLen,
  457. MacAddress: network.MacAddress,
  458. NetworkID: network.NetworkID,
  459. }
  460. if network.IPAMConfig != nil {
  461. networks[name].IPAMConfig = &networktypes.EndpointIPAMConfig{
  462. IPv4Address: network.IPAMConfig.IPv4Address,
  463. IPv6Address: network.IPAMConfig.IPv6Address,
  464. }
  465. }
  466. }
  467. newC.NetworkSettings = &types.SummaryNetworkSettings{Networks: networks}
  468. newC.Ports = []types.Port{}
  469. for port, bindings := range container.NetworkSettings.Ports {
  470. p, err := nat.ParsePort(port.Port())
  471. if err != nil {
  472. return nil, err
  473. }
  474. if len(bindings) == 0 {
  475. newC.Ports = append(newC.Ports, types.Port{
  476. PrivatePort: uint16(p),
  477. Type: port.Proto(),
  478. })
  479. continue
  480. }
  481. for _, binding := range bindings {
  482. h, err := nat.ParsePort(binding.HostPort)
  483. if err != nil {
  484. return nil, err
  485. }
  486. newC.Ports = append(newC.Ports, types.Port{
  487. PrivatePort: uint16(p),
  488. PublicPort: uint16(h),
  489. Type: port.Proto(),
  490. IP: binding.HostIP,
  491. })
  492. }
  493. }
  494. if ctx.Size {
  495. sizeRw, sizeRootFs := daemon.getSize(container)
  496. newC.SizeRw = sizeRw
  497. newC.SizeRootFs = sizeRootFs
  498. }
  499. newC.Labels = container.Config.Labels
  500. newC.Mounts = addMountPoints(container)
  501. return newC, nil
  502. }
  503. // Volumes lists known volumes, using the filter to restrict the range
  504. // of volumes returned.
  505. func (daemon *Daemon) Volumes(filter string) ([]*types.Volume, []string, error) {
  506. var (
  507. volumesOut []*types.Volume
  508. )
  509. volFilters, err := filters.FromParam(filter)
  510. if err != nil {
  511. return nil, nil, err
  512. }
  513. if err := volFilters.Validate(acceptedVolumeFilterTags); err != nil {
  514. return nil, nil, err
  515. }
  516. volumes, warnings, err := daemon.volumes.List()
  517. if err != nil {
  518. return nil, nil, err
  519. }
  520. filterVolumes, err := daemon.filterVolumes(volumes, volFilters)
  521. if err != nil {
  522. return nil, nil, err
  523. }
  524. for _, v := range filterVolumes {
  525. apiV := volumeToAPIType(v)
  526. if vv, ok := v.(interface {
  527. CachedPath() string
  528. }); ok {
  529. apiV.Mountpoint = vv.CachedPath()
  530. } else {
  531. apiV.Mountpoint = v.Path()
  532. }
  533. volumesOut = append(volumesOut, apiV)
  534. }
  535. return volumesOut, warnings, nil
  536. }
  537. // filterVolumes filters volume list according to user specified filter
  538. // and returns user chosen volumes
  539. func (daemon *Daemon) filterVolumes(vols []volume.Volume, filter filters.Args) ([]volume.Volume, error) {
  540. // if filter is empty, return original volume list
  541. if filter.Len() == 0 {
  542. return vols, nil
  543. }
  544. var retVols []volume.Volume
  545. for _, vol := range vols {
  546. if filter.Include("name") {
  547. if !filter.Match("name", vol.Name()) {
  548. continue
  549. }
  550. }
  551. if filter.Include("driver") {
  552. if !filter.Match("driver", vol.DriverName()) {
  553. continue
  554. }
  555. }
  556. if filter.Include("label") {
  557. v, ok := vol.(volume.DetailedVolume)
  558. if !ok {
  559. continue
  560. }
  561. if !filter.MatchKVList("label", v.Labels()) {
  562. continue
  563. }
  564. }
  565. retVols = append(retVols, vol)
  566. }
  567. danglingOnly := false
  568. if filter.Include("dangling") {
  569. if filter.ExactMatch("dangling", "true") || filter.ExactMatch("dangling", "1") {
  570. danglingOnly = true
  571. } else if !filter.ExactMatch("dangling", "false") && !filter.ExactMatch("dangling", "0") {
  572. return nil, fmt.Errorf("Invalid filter 'dangling=%s'", filter.Get("dangling"))
  573. }
  574. retVols = daemon.volumes.FilterByUsed(retVols, !danglingOnly)
  575. }
  576. return retVols, nil
  577. }
  578. func populateImageFilterByParents(ancestorMap map[image.ID]bool, imageID image.ID, getChildren func(image.ID) []image.ID) {
  579. if !ancestorMap[imageID] {
  580. for _, id := range getChildren(imageID) {
  581. populateImageFilterByParents(ancestorMap, id, getChildren)
  582. }
  583. ancestorMap[imageID] = true
  584. }
  585. }