resize_util.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. Copyright 2018 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 util
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/api/meta"
  19. "k8s.io/apimachinery/pkg/api/resource"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  22. "k8s.io/apimachinery/pkg/types"
  23. "k8s.io/apimachinery/pkg/util/strategicpatch"
  24. clientset "k8s.io/client-go/kubernetes"
  25. "k8s.io/kubernetes/pkg/util/mount"
  26. "k8s.io/kubernetes/pkg/util/resizefs"
  27. "k8s.io/kubernetes/pkg/volume"
  28. volumetypes "k8s.io/kubernetes/pkg/volume/util/types"
  29. )
  30. var (
  31. knownResizeConditions = map[v1.PersistentVolumeClaimConditionType]bool{
  32. v1.PersistentVolumeClaimFileSystemResizePending: true,
  33. v1.PersistentVolumeClaimResizing: true,
  34. }
  35. )
  36. type resizeProcessStatus struct {
  37. condition v1.PersistentVolumeClaimCondition
  38. processed bool
  39. }
  40. // ClaimToClaimKey return namespace/name string for pvc
  41. func ClaimToClaimKey(claim *v1.PersistentVolumeClaim) string {
  42. return fmt.Sprintf("%s/%s", claim.Namespace, claim.Name)
  43. }
  44. // UpdatePVSize updates just pv size after cloudprovider resizing is successful
  45. func UpdatePVSize(
  46. pv *v1.PersistentVolume,
  47. newSize resource.Quantity,
  48. kubeClient clientset.Interface) error {
  49. pvClone := pv.DeepCopy()
  50. oldData, err := json.Marshal(pvClone)
  51. if err != nil {
  52. return fmt.Errorf("unexpected error marshaling old PV %q with error : %v", pvClone.Name, err)
  53. }
  54. pvClone.Spec.Capacity[v1.ResourceStorage] = newSize
  55. newData, err := json.Marshal(pvClone)
  56. if err != nil {
  57. return fmt.Errorf("unexpected error marshaling new PV %q with error : %v", pvClone.Name, err)
  58. }
  59. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, pvClone)
  60. if err != nil {
  61. return fmt.Errorf("error Creating two way merge patch for PV %q with error : %v", pvClone.Name, err)
  62. }
  63. _, err = kubeClient.CoreV1().PersistentVolumes().Patch(pvClone.Name, types.StrategicMergePatchType, patchBytes)
  64. if err != nil {
  65. return fmt.Errorf("error Patching PV %q with error : %v", pvClone.Name, err)
  66. }
  67. return nil
  68. }
  69. // MarkResizeInProgressWithResizer marks cloudprovider resizing as in progress
  70. // and also annotates the PVC with the name of the resizer.
  71. func MarkResizeInProgressWithResizer(
  72. pvc *v1.PersistentVolumeClaim,
  73. resizerName string,
  74. kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {
  75. // Mark PVC as Resize Started
  76. progressCondition := v1.PersistentVolumeClaimCondition{
  77. Type: v1.PersistentVolumeClaimResizing,
  78. Status: v1.ConditionTrue,
  79. LastTransitionTime: metav1.Now(),
  80. }
  81. conditions := []v1.PersistentVolumeClaimCondition{progressCondition}
  82. newPVC := pvc.DeepCopy()
  83. newPVC = MergeResizeConditionOnPVC(newPVC, conditions)
  84. newPVC = setResizer(newPVC, resizerName)
  85. return PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)
  86. }
  87. // SetClaimResizer sets resizer annotation on PVC
  88. func SetClaimResizer(
  89. pvc *v1.PersistentVolumeClaim,
  90. resizerName string,
  91. kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {
  92. newPVC := pvc.DeepCopy()
  93. newPVC = setResizer(newPVC, resizerName)
  94. return PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)
  95. }
  96. func setResizer(pvc *v1.PersistentVolumeClaim, resizerName string) *v1.PersistentVolumeClaim {
  97. if val, ok := pvc.Annotations[volumetypes.VolumeResizerKey]; ok && val == resizerName {
  98. return pvc
  99. }
  100. metav1.SetMetaDataAnnotation(&pvc.ObjectMeta, volumetypes.VolumeResizerKey, resizerName)
  101. return pvc
  102. }
  103. // MarkForFSResize marks file system resizing as pending
  104. func MarkForFSResize(
  105. pvc *v1.PersistentVolumeClaim,
  106. kubeClient clientset.Interface) error {
  107. pvcCondition := v1.PersistentVolumeClaimCondition{
  108. Type: v1.PersistentVolumeClaimFileSystemResizePending,
  109. Status: v1.ConditionTrue,
  110. LastTransitionTime: metav1.Now(),
  111. Message: "Waiting for user to (re-)start a pod to finish file system resize of volume on node.",
  112. }
  113. conditions := []v1.PersistentVolumeClaimCondition{pvcCondition}
  114. newPVC := pvc.DeepCopy()
  115. newPVC = MergeResizeConditionOnPVC(newPVC, conditions)
  116. _, err := PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)
  117. return err
  118. }
  119. // MarkResizeFinished marks all resizing as done
  120. func MarkResizeFinished(
  121. pvc *v1.PersistentVolumeClaim,
  122. newSize resource.Quantity,
  123. kubeClient clientset.Interface) error {
  124. return MarkFSResizeFinished(pvc, newSize, kubeClient)
  125. }
  126. // MarkFSResizeFinished marks file system resizing as done
  127. func MarkFSResizeFinished(
  128. pvc *v1.PersistentVolumeClaim,
  129. newSize resource.Quantity,
  130. kubeClient clientset.Interface) error {
  131. newPVC := pvc.DeepCopy()
  132. newPVC.Status.Capacity[v1.ResourceStorage] = newSize
  133. newPVC = MergeResizeConditionOnPVC(newPVC, []v1.PersistentVolumeClaimCondition{})
  134. _, err := PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)
  135. return err
  136. }
  137. // PatchPVCStatus updates PVC status using PATCH verb
  138. // Don't use Update because this can be called from kubelet and if kubelet has an older client its
  139. // Updates will overwrite new fields. And to avoid writing to a stale object, add ResourceVersion
  140. // to the patch so that Patch will fail if the patch's RV != actual up-to-date RV like Update would
  141. func PatchPVCStatus(
  142. oldPVC *v1.PersistentVolumeClaim,
  143. newPVC *v1.PersistentVolumeClaim,
  144. kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {
  145. patchBytes, err := createPVCPatch(oldPVC, newPVC)
  146. if err != nil {
  147. return nil, fmt.Errorf("patchPVCStatus failed to patch PVC %q: %v", oldPVC.Name, err)
  148. }
  149. updatedClaim, updateErr := kubeClient.CoreV1().PersistentVolumeClaims(oldPVC.Namespace).
  150. Patch(oldPVC.Name, types.StrategicMergePatchType, patchBytes, "status")
  151. if updateErr != nil {
  152. return nil, fmt.Errorf("patchPVCStatus failed to patch PVC %q: %v", oldPVC.Name, updateErr)
  153. }
  154. return updatedClaim, nil
  155. }
  156. func createPVCPatch(
  157. oldPVC *v1.PersistentVolumeClaim,
  158. newPVC *v1.PersistentVolumeClaim) ([]byte, error) {
  159. oldData, err := json.Marshal(oldPVC)
  160. if err != nil {
  161. return nil, fmt.Errorf("failed to marshal old data: %v", err)
  162. }
  163. newData, err := json.Marshal(newPVC)
  164. if err != nil {
  165. return nil, fmt.Errorf("failed to marshal new data: %v", err)
  166. }
  167. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, oldPVC)
  168. if err != nil {
  169. return nil, fmt.Errorf("failed to create 2 way merge patch: %v", err)
  170. }
  171. patchBytes, err = addResourceVersion(patchBytes, oldPVC.ResourceVersion)
  172. if err != nil {
  173. return nil, fmt.Errorf("failed to add resource version: %v", err)
  174. }
  175. return patchBytes, nil
  176. }
  177. func addResourceVersion(patchBytes []byte, resourceVersion string) ([]byte, error) {
  178. var patchMap map[string]interface{}
  179. err := json.Unmarshal(patchBytes, &patchMap)
  180. if err != nil {
  181. return nil, fmt.Errorf("error unmarshalling patch: %v", err)
  182. }
  183. u := unstructured.Unstructured{Object: patchMap}
  184. a, err := meta.Accessor(&u)
  185. if err != nil {
  186. return nil, fmt.Errorf("error creating accessor: %v", err)
  187. }
  188. a.SetResourceVersion(resourceVersion)
  189. versionBytes, err := json.Marshal(patchMap)
  190. if err != nil {
  191. return nil, fmt.Errorf("error marshalling json patch: %v", err)
  192. }
  193. return versionBytes, nil
  194. }
  195. // MergeResizeConditionOnPVC updates pvc with requested resize conditions
  196. // leaving other conditions untouched.
  197. func MergeResizeConditionOnPVC(
  198. pvc *v1.PersistentVolumeClaim,
  199. resizeConditions []v1.PersistentVolumeClaimCondition) *v1.PersistentVolumeClaim {
  200. resizeConditionMap := map[v1.PersistentVolumeClaimConditionType]*resizeProcessStatus{}
  201. for _, condition := range resizeConditions {
  202. resizeConditionMap[condition.Type] = &resizeProcessStatus{condition, false}
  203. }
  204. oldConditions := pvc.Status.Conditions
  205. newConditions := []v1.PersistentVolumeClaimCondition{}
  206. for _, condition := range oldConditions {
  207. // If Condition is of not resize type, we keep it.
  208. if _, ok := knownResizeConditions[condition.Type]; !ok {
  209. newConditions = append(newConditions, condition)
  210. continue
  211. }
  212. if newCondition, ok := resizeConditionMap[condition.Type]; ok {
  213. if newCondition.condition.Status != condition.Status {
  214. newConditions = append(newConditions, newCondition.condition)
  215. } else {
  216. newConditions = append(newConditions, condition)
  217. }
  218. newCondition.processed = true
  219. }
  220. }
  221. // append all unprocessed conditions
  222. for _, newCondition := range resizeConditionMap {
  223. if !newCondition.processed {
  224. newConditions = append(newConditions, newCondition.condition)
  225. }
  226. }
  227. pvc.Status.Conditions = newConditions
  228. return pvc
  229. }
  230. // GenericResizeFS : call generic filesystem resizer for plugins that don't have any special filesystem resize requirements
  231. func GenericResizeFS(host volume.VolumeHost, pluginName, devicePath, deviceMountPath string) (bool, error) {
  232. mounter := host.GetMounter(pluginName)
  233. diskFormatter := &mount.SafeFormatAndMount{
  234. Interface: mounter,
  235. Exec: host.GetExec(pluginName),
  236. }
  237. resizer := resizefs.NewResizeFs(diskFormatter)
  238. return resizer.Resize(devicePath, deviceMountPath)
  239. }