metrics_du.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package volume
  14. import (
  15. "errors"
  16. "fmt"
  17. "k8s.io/kubernetes/pkg/api/resource"
  18. "k8s.io/kubernetes/pkg/volume/util"
  19. )
  20. var _ MetricsProvider = &metricsDu{}
  21. // metricsDu represents a MetricsProvider that calculates the used and
  22. // available Volume space by executing the "du" command and gathering
  23. // filesystem info for the Volume path.
  24. type metricsDu struct {
  25. // the directory path the volume is mounted to.
  26. path string
  27. }
  28. // NewMetricsDu creates a new metricsDu with the Volume path.
  29. func NewMetricsDu(path string) MetricsProvider {
  30. return &metricsDu{path}
  31. }
  32. // GetMetrics calculates the volume usage and device free space by executing "du"
  33. // and gathering filesystem info for the Volume path.
  34. // See MetricsProvider.GetMetrics
  35. func (md *metricsDu) GetMetrics() (*Metrics, error) {
  36. metrics := &Metrics{}
  37. if md.path == "" {
  38. return metrics, errors.New("no path defined for disk usage metrics.")
  39. }
  40. err := md.runDu(metrics)
  41. if err != nil {
  42. return metrics, err
  43. }
  44. err = md.getFsInfo(metrics)
  45. if err != nil {
  46. return metrics, err
  47. }
  48. return metrics, nil
  49. }
  50. // runDu executes the "du" command and writes the results to metrics.Used
  51. func (md *metricsDu) runDu(metrics *Metrics) error {
  52. used, err := util.Du(md.path)
  53. if err != nil {
  54. return err
  55. }
  56. metrics.Used = used
  57. return nil
  58. }
  59. // getFsInfo writes metrics.Capacity and metrics.Available from the filesystem
  60. // info
  61. func (md *metricsDu) getFsInfo(metrics *Metrics) error {
  62. available, capacity, _, err := util.FsInfo(md.path)
  63. if err != nil {
  64. return fmt.Errorf("Failed to get FsInfo due to error %v", err)
  65. }
  66. metrics.Available = resource.NewQuantity(available, resource.BinarySI)
  67. metrics.Capacity = resource.NewQuantity(capacity, resource.BinarySI)
  68. return nil
  69. }