Kubernetes ImageGC分析

上一篇文章分析了ContainerGC,k8s為了回收機(jī)器上的存儲(chǔ)資源同時(shí)有ImageGC對(duì)image資源進(jìn)行回收蜡塌。

ImageGC同樣定義了image gc manager和gc policy央勒。

//pkg/kubelet/image/image_gc_manager.go
type ImageGCPolicy struct {
    // Any usage above this threshold will always trigger garbage collection.
    // This is the highest usage we will allow.
    HighThresholdPercent int

    // Any usage below this threshold will never trigger garbage collection.
    // This is the lowest threshold we will try to garbage collect to.
    LowThresholdPercent int

    // Minimum age at which an image can be garbage collected.
    MinAge time.Duration
}

type realImageGCManager struct {
    // Container runtime
    runtime container.Runtime

    // Records of images and their use.
    imageRecords     map[string]*imageRecord
    imageRecordsLock sync.Mutex

    // The image garbage collection policy in use.
    policy ImageGCPolicy

    // cAdvisor instance.
    cadvisor cadvisor.Interface

    // Recorder for Kubernetes events.
    recorder record.EventRecorder

    // Reference to this node.
    nodeRef *v1.ObjectReference

    // Track initialization
    initialized bool

    // imageCache is the cache of latest image list.
    imageCache imageCache
}

策略也主要有三個(gè)參數(shù):

  • HighThresholdPercent 高于此閾值將進(jìn)行回收
  • LowThresholdPercent 低于此閾值將不會(huì)觸發(fā)回收
  • MinAge 回收image的最小年齡

在這個(gè)文件里同樣有一個(gè)GarbageCollect方法

func (im *realImageGCManager) detectImages(detectTime time.Time) error {
    images, err := im.runtime.ListImages()
    if err != nil {
        return err
    }
    pods, err := im.runtime.GetPods(true)
    if err != nil {
        return err
    }

    // Make a set of images in use by containers.
    imagesInUse := sets.NewString()
    for _, pod := range pods {
        for _, container := range pod.Containers {
            glog.V(5).Infof("Pod %s/%s, container %s uses image %s(%s)", pod.Namespace, pod.Name, container.Name, container.Image, container.ImageID)
            imagesInUse.Insert(container.ImageID)
        }
    }

    // Add new images and record those being used.
    now := time.Now()
    currentImages := sets.NewString()
    im.imageRecordsLock.Lock()
    defer im.imageRecordsLock.Unlock()
    for _, image := range images {
        glog.V(5).Infof("Adding image ID %s to currentImages", image.ID)
        currentImages.Insert(image.ID)

        // New image, set it as detected now.
        if _, ok := im.imageRecords[image.ID]; !ok {
            glog.V(5).Infof("Image ID %s is new", image.ID)
            im.imageRecords[image.ID] = &imageRecord{
                firstDetected: detectTime,
            }
        }

        // Set last used time to now if the image is being used.
        if isImageUsed(image, imagesInUse) {
            glog.V(5).Infof("Setting Image ID %s lastUsed to %v", image.ID, now)
            im.imageRecords[image.ID].lastUsed = now
        }

        glog.V(5).Infof("Image ID %s has size %d", image.ID, image.Size)
        im.imageRecords[image.ID].size = image.Size
    }

    // Remove old images from our records.
    for image := range im.imageRecords {
        if !currentImages.Has(image) {
            glog.V(5).Infof("Image ID %s is no longer present; removing from imageRecords", image)
            delete(im.imageRecords, image)
        }
    }

    return nil
}

func (im *realImageGCManager) GarbageCollect() error {
    // Get disk usage on disk holding images.
    fsInfo, err := im.cadvisor.ImagesFsInfo()
    if err != nil {
        return err
    }
    capacity := int64(fsInfo.Capacity)
    available := int64(fsInfo.Available)
    if available > capacity {
        glog.Warningf("available %d is larger than capacity %d", available, capacity)
        available = capacity
    }

    // Check valid capacity.
    if capacity == 0 {
        err := fmt.Errorf("invalid capacity %d on device %q at mount point %q", capacity, fsInfo.Device, fsInfo.Mountpoint)
        im.recorder.Eventf(im.nodeRef, v1.EventTypeWarning, events.InvalidDiskCapacity, err.Error())
        return err
    }

    // If over the max threshold, free enough to place us at the lower threshold.
    usagePercent := 100 - int(available*100/capacity)
    if usagePercent >= im.policy.HighThresholdPercent {
        amountToFree := capacity*int64(100-im.policy.LowThresholdPercent)/100 - available
        glog.Infof("[imageGCManager]: Disk usage on %q (%s) is at %d%% which is over the high threshold (%d%%). Trying to free %d bytes", fsInfo.Device, fsInfo.Mountpoint, usagePercent, im.policy.HighThresholdPercent, amountToFree)
        freed, err := im.freeSpace(amountToFree, time.Now())
        if err != nil {
            return err
        }

        if freed < amountToFree {
            err := fmt.Errorf("failed to garbage collect required amount of images. Wanted to free %d bytes, but freed %d bytes", amountToFree, freed)
            im.recorder.Eventf(im.nodeRef, v1.EventTypeWarning, events.FreeDiskSpaceFailed, err.Error())
            return err
        }
    }

    return nil
}

func (im *realImageGCManager) DeleteUnusedImages() (int64, error) {
    return im.freeSpace(math.MaxInt64, time.Now())
}

// Tries to free bytesToFree worth of images on the disk.
//
// Returns the number of bytes free and an error if any occurred. The number of
// bytes freed is always returned.
// Note that error may be nil and the number of bytes free may be less
// than bytesToFree.
func (im *realImageGCManager) freeSpace(bytesToFree int64, freeTime time.Time) (int64, error) {
    err := im.detectImages(freeTime)
    if err != nil {
        return 0, err
    }

    im.imageRecordsLock.Lock()
    defer im.imageRecordsLock.Unlock()

    // Get all images in eviction order.
    images := make([]evictionInfo, 0, len(im.imageRecords))
    for image, record := range im.imageRecords {
        images = append(images, evictionInfo{
            id:          image,
            imageRecord: *record,
        })
    }
    sort.Sort(byLastUsedAndDetected(images))

    // Delete unused images until we've freed up enough space.
    var deletionErrors []error
    spaceFreed := int64(0)
    for _, image := range images {
        glog.V(5).Infof("Evaluating image ID %s for possible garbage collection", image.id)
        // Images that are currently in used were given a newer lastUsed.
        if image.lastUsed.Equal(freeTime) || image.lastUsed.After(freeTime) {
            glog.V(5).Infof("Image ID %s has lastUsed=%v which is >= freeTime=%v, not eligible for garbage collection", image.id, image.lastUsed, freeTime)
            break
        }

        // Avoid garbage collect the image if the image is not old enough.
        // In such a case, the image may have just been pulled down, and will be used by a container right away.

        if freeTime.Sub(image.firstDetected) < im.policy.MinAge {
            glog.V(5).Infof("Image ID %s has age %v which is less than the policy's minAge of %v, not eligible for garbage collection", image.id, freeTime.Sub(image.firstDetected), im.policy.MinAge)
            continue
        }

        // Remove image. Continue despite errors.
        glog.Infof("[imageGCManager]: Removing image %q to free %d bytes", image.id, image.size)
        err := im.runtime.RemoveImage(container.ImageSpec{Image: image.id})
        if err != nil {
            deletionErrors = append(deletionErrors, err)
            continue
        }
        delete(im.imageRecords, image.id)
        spaceFreed += image.size

        if spaceFreed >= bytesToFree {
            break
        }
    }

    if len(deletionErrors) > 0 {
        return spaceFreed, fmt.Errorf("wanted to free %d bytes, but freed %d bytes space with errors in image deletion: %v", bytesToFree, spaceFreed, errors.NewAggregate(deletionErrors))
    }
    return spaceFreed, nil
}

GarbageCollect方法也是在pkg/kubelet/kubelet.go里面進(jìn)行調(diào)用勺美,每調(diào)用一次執(zhí)行一次回收流程比庄,每次調(diào)用間隔是5分鐘叙谨。
GarbageCollect首先會(huì)調(diào)用cadvisor獲取監(jiān)控機(jī)器上的資源總量可用量审轮,當(dāng)發(fā)現(xiàn)使用的資源已經(jīng)大于設(shè)置的最高閾值將會(huì)觸發(fā)回收行為损敷,并且計(jì)算出需要回收的空間大小烂斋。

freeSpace方法則是真正的回收過(guò)程屹逛,過(guò)程分兩步。

  • 探測(cè)機(jī)器上的image
  • 刪除老的image

探測(cè)鏡像:

探測(cè)機(jī)器上的image是獲取機(jī)器上的image列表并如果是正在使用的image標(biāo)記最后使用時(shí)間和image大小和第一次探測(cè)到的時(shí)間汛骂,并把這個(gè)列表的image放到imageRecords里面進(jìn)行緩存罕模,imageRecords是個(gè)map結(jié)結(jié)構(gòu)的數(shù)據(jù)類型。

回收鏡像:

回收鏡像首先遍歷imageRecords里面的鏡像帘瞭,放到一個(gè)數(shù)組里面排序淑掌,按照最后使用時(shí)間或者第一次探測(cè)到的時(shí)間進(jìn)行排序。
下一步則對(duì)數(shù)組里面的鏡像進(jìn)行回收蝶念,如果鏡像還在使用中或者最后探測(cè)到的時(shí)間小于設(shè)置的MinAge則不進(jìn)行回收抛腕,否則刪除鏡像∶窖常回收過(guò)程中如果發(fā)現(xiàn)現(xiàn)在機(jī)器上的資源已經(jīng)小于設(shè)置的LowThresholdPercent那么跳出回收流程担敌。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市适袜,隨后出現(xiàn)的幾起案子柄错,更是在濱河造成了極大的恐慌,老刑警劉巖苦酱,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件售貌,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡疫萤,警方通過(guò)查閱死者的電腦和手機(jī)颂跨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)扯饶,“玉大人恒削,你說(shuō)我怎么就攤上這事池颈。” “怎么了钓丰?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵躯砰,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我携丁,道長(zhǎng)琢歇,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任梦鉴,我火速辦了婚禮李茫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘肥橙。我一直安慰自己魄宏,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布存筏。 她就那樣靜靜地躺著宠互,像睡著了一般。 火紅的嫁衣襯著肌膚如雪方篮。 梳的紋絲不亂的頭發(fā)上名秀,一...
    開(kāi)封第一講書(shū)人閱讀 51,125評(píng)論 1 297
  • 那天励负,我揣著相機(jī)與錄音藕溅,去河邊找鬼。 笑死继榆,一個(gè)胖子當(dāng)著我的面吹牛巾表,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播略吨,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼集币,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了翠忠?” 一聲冷哼從身側(cè)響起鞠苟,我...
    開(kāi)封第一講書(shū)人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎秽之,沒(méi)想到半個(gè)月后当娱,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡考榨,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年跨细,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片河质。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡冀惭,死狀恐怖震叙,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情散休,我是刑警寧澤媒楼,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站戚丸,受9級(jí)特大地震影響匣砖,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜昏滴,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一猴鲫、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧谣殊,春花似錦拂共、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至蛇捌,卻和暖如春抚恒,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背络拌。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工俭驮, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人春贸。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓混萝,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親萍恕。 傳聞我的和親對(duì)象是個(gè)殘疾皇子逸嘀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容

  • 本文由作者自行翻譯,未經(jīng)作者授權(quán)允粤,不得隨意轉(zhuǎn)發(fā)崭倘。后續(xù)作者會(huì)陸續(xù)發(fā)布一系列關(guān)于JVM內(nèi)存管理的文章,敬請(qǐng)期待类垫。 1司光、...
    猿學(xué)堂閱讀 1,349評(píng)論 0 50
  • docker實(shí)現(xiàn)了更便捷的單機(jī)容器虛擬化的管理, docker的位置處于操作系統(tǒng)層與應(yīng)用層之間; 相對(duì)傳統(tǒng)虛擬化(...
    Harvey_L閱讀 19,899評(píng)論 3 44
  • 多線程、特別是NSOperation 和 GCD 的內(nèi)部原理阔挠。運(yùn)行時(shí)機(jī)制的原理和運(yùn)用場(chǎng)景飘庄。SDWebImage的原...
    LZM輪回閱讀 2,007評(píng)論 0 12
  • 文/沒(méi)有春 回憶是一條絲線 隨著年齡的增長(zhǎng) 越拉越長(zhǎng) 曾經(jīng)以為日子太慢 現(xiàn)在卻恨不得把那些日子再過(guò)一遍 慢慢地舔完...
    沒(méi)有春閱讀 386評(píng)論 10 22
  • 文 / 顧空城 1跪削、 看過(guò)很多干貨分享者的文章谴仙,里面很多都有說(shuō)到讀書(shū),在閑余的時(shí)間里讀書(shū)碾盐、在繁忙的日子里擠出時(shí)間來(lái)...
    顧空城閱讀 1,060評(píng)論 15 19