csi_metrics.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2019 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 csi
  14. import (
  15. "context"
  16. "fmt"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/kubernetes/pkg/volume"
  19. )
  20. var _ volume.MetricsProvider = &metricsCsi{}
  21. // metricsCsi represents a MetricsProvider that calculates the used,free and
  22. // capacity information for volume using volume path.
  23. type metricsCsi struct {
  24. // the directory path the volume is mounted to.
  25. targetPath string
  26. // Volume handle or id
  27. volumeID string
  28. //csiClient with cache
  29. csiClientGetter
  30. }
  31. // NewMetricsCsi creates a new metricsCsi with the Volume ID and path.
  32. func NewMetricsCsi(volumeID string, targetPath string, driverName csiDriverName) volume.MetricsProvider {
  33. mc := &metricsCsi{volumeID: volumeID, targetPath: targetPath}
  34. mc.csiClientGetter.driverName = driverName
  35. return mc
  36. }
  37. func (mc *metricsCsi) GetMetrics() (*volume.Metrics, error) {
  38. currentTime := metav1.Now()
  39. ctx, cancel := context.WithTimeout(context.Background(), csiTimeout)
  40. defer cancel()
  41. // Get CSI client
  42. csiClient, err := mc.csiClientGetter.Get()
  43. if err != nil {
  44. return nil, err
  45. }
  46. // Check whether "GET_VOLUME_STATS" is set
  47. volumeStatsSet, err := csiClient.NodeSupportsVolumeStats(ctx)
  48. if err != nil {
  49. return nil, err
  50. }
  51. // if plugin doesnot support volume status, return.
  52. if !volumeStatsSet {
  53. return nil, volume.NewNotSupportedErrorWithDriverName(
  54. string(mc.csiClientGetter.driverName))
  55. }
  56. // Get Volumestatus
  57. metrics, err := csiClient.NodeGetVolumeStats(ctx, mc.volumeID, mc.targetPath)
  58. if err != nil {
  59. return nil, err
  60. }
  61. if metrics == nil {
  62. return nil, fmt.Errorf("csi.NodeGetVolumeStats returned nil metrics for volume %s", mc.volumeID)
  63. }
  64. //set recorded time
  65. metrics.Time = currentTime
  66. return metrics, nil
  67. }