github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/pkg/prune/image_pruner.go (about)

     1  // Copyright © 2022 Alibaba Group Holding Ltd.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package prune
    16  
    17  import (
    18  	"path/filepath"
    19  
    20  	"github.com/alibaba/sealer/common"
    21  	"github.com/alibaba/sealer/pkg/image/store"
    22  	"github.com/alibaba/sealer/utils"
    23  )
    24  
    25  type imagePrune struct {
    26  	imageRootDir string
    27  	imageStore   store.ImageStore
    28  }
    29  
    30  func NewImagePrune() (Pruner, error) {
    31  	imageStore, err := store.NewDefaultImageStore()
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	return imagePrune{imageStore: imageStore,
    37  		imageRootDir: common.DefaultImageDBRootDir,
    38  	}, nil
    39  }
    40  
    41  func (i imagePrune) Select() ([]string, error) {
    42  	var pruneList []string
    43  
    44  	imageIDFiles, err := i.getAllImageID()
    45  	if err != nil {
    46  		return pruneList, err
    47  	}
    48  
    49  	subsets, err := utils.GetDirNameListInDir(i.imageRootDir, utils.FilterOptions{
    50  		All:          true,
    51  		WithFullPath: true,
    52  	})
    53  
    54  	if err != nil {
    55  		return pruneList, err
    56  	}
    57  
    58  	for _, subset := range subsets {
    59  		if utils.NotIn(filepath.Base(subset), imageIDFiles) {
    60  			pruneList = append(pruneList, subset)
    61  		}
    62  	}
    63  
    64  	return pruneList, nil
    65  }
    66  
    67  // getAllImageID return current image id with ext "yaml".
    68  func (i imagePrune) getAllImageID() ([]string, error) {
    69  	imageMetadataMap, err := i.imageStore.GetImageMetadataMap()
    70  
    71  	var imageIDList []string
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	for _, imageMetadata := range imageMetadataMap {
    77  		for _, m := range imageMetadata.Manifests {
    78  			imageIDList = append(imageIDList, m.ID+".yaml")
    79  		}
    80  	}
    81  	return imageIDList, err
    82  }
    83  func (i imagePrune) GetSelectorMessage() string {
    84  	return ImagePruner
    85  }