k8s.io/kubernetes@v1.29.3/pkg/volume/metrics_du.go (about) 1 /* 2 Copyright 2014 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package volume 18 19 import ( 20 "k8s.io/apimachinery/pkg/api/resource" 21 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 22 "k8s.io/kubernetes/pkg/volume/util/fs" 23 ) 24 25 var _ MetricsProvider = &metricsDu{} 26 27 // metricsDu represents a MetricsProvider that calculates the used and 28 // available Volume space by calling fs.DiskUsage() and gathering 29 // filesystem info for the Volume path. 30 type metricsDu struct { 31 // the directory path the volume is mounted to. 32 path string 33 } 34 35 // NewMetricsDu creates a new metricsDu with the Volume path. 36 func NewMetricsDu(path string) MetricsProvider { 37 return &metricsDu{path} 38 } 39 40 // GetMetrics calculates the volume usage and device free space by executing "du" 41 // and gathering filesystem info for the Volume path. 42 // See MetricsProvider.GetMetrics 43 func (md *metricsDu) GetMetrics() (*Metrics, error) { 44 metrics := &Metrics{Time: metav1.Now()} 45 if md.path == "" { 46 return metrics, NewNoPathDefinedError() 47 } 48 49 err := md.getDiskUsage(metrics) 50 if err != nil { 51 return metrics, err 52 } 53 54 err = md.getFsInfo(metrics) 55 if err != nil { 56 return metrics, err 57 } 58 59 return metrics, nil 60 } 61 62 // getDiskUsage writes metrics.Used and metric.InodesUsed from fs.DiskUsage 63 func (md *metricsDu) getDiskUsage(metrics *Metrics) error { 64 usage, err := fs.DiskUsage(md.path) 65 if err != nil { 66 return err 67 } 68 metrics.Used = resource.NewQuantity(usage.Bytes, resource.BinarySI) 69 metrics.InodesUsed = resource.NewQuantity(usage.Inodes, resource.BinarySI) 70 return nil 71 } 72 73 // getFsInfo writes metrics.Capacity and metrics.Available from the filesystem 74 // info 75 func (md *metricsDu) getFsInfo(metrics *Metrics) error { 76 available, capacity, _, inodes, inodesFree, _, err := fs.Info(md.path) 77 if err != nil { 78 return NewFsInfoFailedError(err) 79 } 80 metrics.Available = resource.NewQuantity(available, resource.BinarySI) 81 metrics.Capacity = resource.NewQuantity(capacity, resource.BinarySI) 82 metrics.Inodes = resource.NewQuantity(inodes, resource.BinarySI) 83 metrics.InodesFree = resource.NewQuantity(inodesFree, resource.BinarySI) 84 return nil 85 }