github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/daemon/daemon_linux.go (about)

     1  package daemon
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"regexp"
     9  	"strings"
    10  
    11  	"github.com/Sirupsen/logrus"
    12  	"github.com/docker/docker/pkg/mount"
    13  )
    14  
    15  func (daemon *Daemon) cleanupMountsByID(id string) error {
    16  	logrus.Debugf("Cleaning up old mountid %s: start.", id)
    17  	f, err := os.Open("/proc/self/mountinfo")
    18  	if err != nil {
    19  		return err
    20  	}
    21  	defer f.Close()
    22  
    23  	return daemon.cleanupMountsFromReaderByID(f, id, mount.Unmount)
    24  }
    25  
    26  func (daemon *Daemon) cleanupMountsFromReaderByID(reader io.Reader, id string, unmount func(target string) error) error {
    27  	if daemon.root == "" {
    28  		return nil
    29  	}
    30  	var errors []string
    31  
    32  	regexps := getCleanPatterns(id)
    33  	sc := bufio.NewScanner(reader)
    34  	for sc.Scan() {
    35  		if fields := strings.Fields(sc.Text()); len(fields) >= 4 {
    36  			if mnt := fields[4]; strings.HasPrefix(mnt, daemon.root) {
    37  				for _, p := range regexps {
    38  					if p.MatchString(mnt) {
    39  						if err := unmount(mnt); err != nil {
    40  							logrus.Error(err)
    41  							errors = append(errors, err.Error())
    42  						}
    43  					}
    44  				}
    45  			}
    46  		}
    47  	}
    48  
    49  	if err := sc.Err(); err != nil {
    50  		return err
    51  	}
    52  
    53  	if len(errors) > 0 {
    54  		return fmt.Errorf("Error cleaning up mounts:\n%v", strings.Join(errors, "\n"))
    55  	}
    56  
    57  	logrus.Debugf("Cleaning up old mountid %v: done.", id)
    58  	return nil
    59  }
    60  
    61  // cleanupMounts umounts shm/mqueue mounts for old containers
    62  func (daemon *Daemon) cleanupMounts() error {
    63  	return daemon.cleanupMountsByID("")
    64  }
    65  
    66  func getCleanPatterns(id string) (regexps []*regexp.Regexp) {
    67  	var patterns []string
    68  	if id == "" {
    69  		id = "[0-9a-f]{64}"
    70  		patterns = append(patterns, "containers/"+id+"/shm")
    71  	}
    72  	patterns = append(patterns, "aufs/mnt/"+id+"$", "overlay/"+id+"/merged$", "zfs/graph/"+id+"$")
    73  	for _, p := range patterns {
    74  		r, err := regexp.Compile(p)
    75  		if err == nil {
    76  			regexps = append(regexps, r)
    77  		}
    78  	}
    79  	return
    80  }