idempotency.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. Copyright 2017 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 apiclient
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "time"
  19. "github.com/pkg/errors"
  20. apps "k8s.io/api/apps/v1"
  21. v1 "k8s.io/api/core/v1"
  22. rbac "k8s.io/api/rbac/v1"
  23. apierrors "k8s.io/apimachinery/pkg/api/errors"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/types"
  26. "k8s.io/apimachinery/pkg/util/strategicpatch"
  27. "k8s.io/apimachinery/pkg/util/wait"
  28. clientset "k8s.io/client-go/kubernetes"
  29. clientsetretry "k8s.io/client-go/util/retry"
  30. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  31. )
  32. // ConfigMapMutator is a function that mutates the given ConfigMap and optionally returns an error
  33. type ConfigMapMutator func(*v1.ConfigMap) error
  34. // TODO: We should invent a dynamic mechanism for this using the dynamic client instead of hard-coding these functions per-type
  35. // CreateOrUpdateConfigMap creates a ConfigMap if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  36. func CreateOrUpdateConfigMap(client clientset.Interface, cm *v1.ConfigMap) error {
  37. if _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Create(context.TODO(), cm, metav1.CreateOptions{}); err != nil {
  38. if !apierrors.IsAlreadyExists(err) {
  39. return errors.Wrap(err, "unable to create ConfigMap")
  40. }
  41. if _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Update(context.TODO(), cm, metav1.UpdateOptions{}); err != nil {
  42. return errors.Wrap(err, "unable to update ConfigMap")
  43. }
  44. }
  45. return nil
  46. }
  47. // CreateOrMutateConfigMap tries to create the ConfigMap provided as cm. If the resource exists already, the latest version will be fetched from
  48. // the cluster and mutator callback will be called on it, then an Update of the mutated ConfigMap will be performed. This function is resilient
  49. // to conflicts, and a retry will be issued if the ConfigMap was modified on the server between the refresh and the update (while the mutation was
  50. // taking place)
  51. func CreateOrMutateConfigMap(client clientset.Interface, cm *v1.ConfigMap, mutator ConfigMapMutator) error {
  52. var lastError error
  53. err := wait.ExponentialBackoff(wait.Backoff{
  54. Steps: 20,
  55. Duration: 500 * time.Millisecond,
  56. Factor: 1.0,
  57. Jitter: 0.1,
  58. }, func() (bool, error) {
  59. if _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Create(context.TODO(), cm, metav1.CreateOptions{}); err != nil {
  60. lastError = err
  61. if apierrors.IsAlreadyExists(err) {
  62. lastError = MutateConfigMap(client, metav1.ObjectMeta{Namespace: cm.ObjectMeta.Namespace, Name: cm.ObjectMeta.Name}, mutator)
  63. return lastError == nil, nil
  64. }
  65. return false, nil
  66. }
  67. return true, nil
  68. })
  69. if err == nil {
  70. return nil
  71. }
  72. return lastError
  73. }
  74. // MutateConfigMap takes a ConfigMap Object Meta (namespace and name), retrieves the resource from the server and tries to mutate it
  75. // by calling to the mutator callback, then an Update of the mutated ConfigMap will be performed. This function is resilient
  76. // to conflicts, and a retry will be issued if the ConfigMap was modified on the server between the refresh and the update (while the mutation was
  77. // taking place).
  78. func MutateConfigMap(client clientset.Interface, meta metav1.ObjectMeta, mutator ConfigMapMutator) error {
  79. return clientsetretry.RetryOnConflict(wait.Backoff{
  80. Steps: 20,
  81. Duration: 500 * time.Millisecond,
  82. Factor: 1.0,
  83. Jitter: 0.1,
  84. }, func() error {
  85. configMap, err := client.CoreV1().ConfigMaps(meta.Namespace).Get(context.TODO(), meta.Name, metav1.GetOptions{})
  86. if err != nil {
  87. return err
  88. }
  89. if err = mutator(configMap); err != nil {
  90. return errors.Wrap(err, "unable to mutate ConfigMap")
  91. }
  92. _, err = client.CoreV1().ConfigMaps(configMap.ObjectMeta.Namespace).Update(context.TODO(), configMap, metav1.UpdateOptions{})
  93. return err
  94. })
  95. }
  96. // CreateOrRetainConfigMap creates a ConfigMap if the target resource doesn't exist. If the resource exists already, this function will retain the resource instead.
  97. func CreateOrRetainConfigMap(client clientset.Interface, cm *v1.ConfigMap, configMapName string) error {
  98. if _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Get(context.TODO(), configMapName, metav1.GetOptions{}); err != nil {
  99. if !apierrors.IsNotFound(err) {
  100. return nil
  101. }
  102. if _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Create(context.TODO(), cm, metav1.CreateOptions{}); err != nil {
  103. if !apierrors.IsAlreadyExists(err) {
  104. return errors.Wrap(err, "unable to create ConfigMap")
  105. }
  106. }
  107. }
  108. return nil
  109. }
  110. // CreateOrUpdateSecret creates a Secret if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  111. func CreateOrUpdateSecret(client clientset.Interface, secret *v1.Secret) error {
  112. if _, err := client.CoreV1().Secrets(secret.ObjectMeta.Namespace).Create(context.TODO(), secret, metav1.CreateOptions{}); err != nil {
  113. if !apierrors.IsAlreadyExists(err) {
  114. return errors.Wrap(err, "unable to create secret")
  115. }
  116. if _, err := client.CoreV1().Secrets(secret.ObjectMeta.Namespace).Update(context.TODO(), secret, metav1.UpdateOptions{}); err != nil {
  117. return errors.Wrap(err, "unable to update secret")
  118. }
  119. }
  120. return nil
  121. }
  122. // CreateOrUpdateServiceAccount creates a ServiceAccount if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  123. func CreateOrUpdateServiceAccount(client clientset.Interface, sa *v1.ServiceAccount) error {
  124. if _, err := client.CoreV1().ServiceAccounts(sa.ObjectMeta.Namespace).Create(context.TODO(), sa, metav1.CreateOptions{}); err != nil {
  125. // Note: We don't run .Update here afterwards as that's probably not required
  126. // Only thing that could be updated is annotations/labels in .metadata, but we don't use that currently
  127. if !apierrors.IsAlreadyExists(err) {
  128. return errors.Wrap(err, "unable to create serviceaccount")
  129. }
  130. }
  131. return nil
  132. }
  133. // CreateOrUpdateDeployment creates a Deployment if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  134. func CreateOrUpdateDeployment(client clientset.Interface, deploy *apps.Deployment) error {
  135. if _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Create(context.TODO(), deploy, metav1.CreateOptions{}); err != nil {
  136. if !apierrors.IsAlreadyExists(err) {
  137. return errors.Wrap(err, "unable to create deployment")
  138. }
  139. if _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Update(context.TODO(), deploy, metav1.UpdateOptions{}); err != nil {
  140. return errors.Wrap(err, "unable to update deployment")
  141. }
  142. }
  143. return nil
  144. }
  145. // CreateOrRetainDeployment creates a Deployment if the target resource doesn't exist. If the resource exists already, this function will retain the resource instead.
  146. func CreateOrRetainDeployment(client clientset.Interface, deploy *apps.Deployment, deployName string) error {
  147. if _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Get(context.TODO(), deployName, metav1.GetOptions{}); err != nil {
  148. if !apierrors.IsNotFound(err) {
  149. return nil
  150. }
  151. if _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Create(context.TODO(), deploy, metav1.CreateOptions{}); err != nil {
  152. if !apierrors.IsAlreadyExists(err) {
  153. return errors.Wrap(err, "unable to create deployment")
  154. }
  155. }
  156. }
  157. return nil
  158. }
  159. // CreateOrUpdateDaemonSet creates a DaemonSet if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  160. func CreateOrUpdateDaemonSet(client clientset.Interface, ds *apps.DaemonSet) error {
  161. if _, err := client.AppsV1().DaemonSets(ds.ObjectMeta.Namespace).Create(context.TODO(), ds, metav1.CreateOptions{}); err != nil {
  162. if !apierrors.IsAlreadyExists(err) {
  163. return errors.Wrap(err, "unable to create daemonset")
  164. }
  165. if _, err := client.AppsV1().DaemonSets(ds.ObjectMeta.Namespace).Update(context.TODO(), ds, metav1.UpdateOptions{}); err != nil {
  166. return errors.Wrap(err, "unable to update daemonset")
  167. }
  168. }
  169. return nil
  170. }
  171. // DeleteDaemonSetForeground deletes the specified DaemonSet in foreground mode; i.e. it blocks until/makes sure all the managed Pods are deleted
  172. func DeleteDaemonSetForeground(client clientset.Interface, namespace, name string) error {
  173. foregroundDelete := metav1.DeletePropagationForeground
  174. deleteOptions := &metav1.DeleteOptions{
  175. PropagationPolicy: &foregroundDelete,
  176. }
  177. return client.AppsV1().DaemonSets(namespace).Delete(context.TODO(), name, deleteOptions)
  178. }
  179. // DeleteDeploymentForeground deletes the specified Deployment in foreground mode; i.e. it blocks until/makes sure all the managed Pods are deleted
  180. func DeleteDeploymentForeground(client clientset.Interface, namespace, name string) error {
  181. foregroundDelete := metav1.DeletePropagationForeground
  182. deleteOptions := &metav1.DeleteOptions{
  183. PropagationPolicy: &foregroundDelete,
  184. }
  185. return client.AppsV1().Deployments(namespace).Delete(context.TODO(), name, deleteOptions)
  186. }
  187. // CreateOrUpdateRole creates a Role if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  188. func CreateOrUpdateRole(client clientset.Interface, role *rbac.Role) error {
  189. if _, err := client.RbacV1().Roles(role.ObjectMeta.Namespace).Create(context.TODO(), role, metav1.CreateOptions{}); err != nil {
  190. if !apierrors.IsAlreadyExists(err) {
  191. return errors.Wrap(err, "unable to create RBAC role")
  192. }
  193. if _, err := client.RbacV1().Roles(role.ObjectMeta.Namespace).Update(context.TODO(), role, metav1.UpdateOptions{}); err != nil {
  194. return errors.Wrap(err, "unable to update RBAC role")
  195. }
  196. }
  197. return nil
  198. }
  199. // CreateOrUpdateRoleBinding creates a RoleBinding if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  200. func CreateOrUpdateRoleBinding(client clientset.Interface, roleBinding *rbac.RoleBinding) error {
  201. if _, err := client.RbacV1().RoleBindings(roleBinding.ObjectMeta.Namespace).Create(context.TODO(), roleBinding, metav1.CreateOptions{}); err != nil {
  202. if !apierrors.IsAlreadyExists(err) {
  203. return errors.Wrap(err, "unable to create RBAC rolebinding")
  204. }
  205. if _, err := client.RbacV1().RoleBindings(roleBinding.ObjectMeta.Namespace).Update(context.TODO(), roleBinding, metav1.UpdateOptions{}); err != nil {
  206. return errors.Wrap(err, "unable to update RBAC rolebinding")
  207. }
  208. }
  209. return nil
  210. }
  211. // CreateOrUpdateClusterRole creates a ClusterRole if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  212. func CreateOrUpdateClusterRole(client clientset.Interface, clusterRole *rbac.ClusterRole) error {
  213. if _, err := client.RbacV1().ClusterRoles().Create(context.TODO(), clusterRole, metav1.CreateOptions{}); err != nil {
  214. if !apierrors.IsAlreadyExists(err) {
  215. return errors.Wrap(err, "unable to create RBAC clusterrole")
  216. }
  217. if _, err := client.RbacV1().ClusterRoles().Update(context.TODO(), clusterRole, metav1.UpdateOptions{}); err != nil {
  218. return errors.Wrap(err, "unable to update RBAC clusterrole")
  219. }
  220. }
  221. return nil
  222. }
  223. // CreateOrUpdateClusterRoleBinding creates a ClusterRoleBinding if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.
  224. func CreateOrUpdateClusterRoleBinding(client clientset.Interface, clusterRoleBinding *rbac.ClusterRoleBinding) error {
  225. if _, err := client.RbacV1().ClusterRoleBindings().Create(context.TODO(), clusterRoleBinding, metav1.CreateOptions{}); err != nil {
  226. if !apierrors.IsAlreadyExists(err) {
  227. return errors.Wrap(err, "unable to create RBAC clusterrolebinding")
  228. }
  229. if _, err := client.RbacV1().ClusterRoleBindings().Update(context.TODO(), clusterRoleBinding, metav1.UpdateOptions{}); err != nil {
  230. return errors.Wrap(err, "unable to update RBAC clusterrolebinding")
  231. }
  232. }
  233. return nil
  234. }
  235. // PatchNodeOnce executes patchFn on the node object found by the node name.
  236. // This is a condition function meant to be used with wait.Poll. false, nil
  237. // implies it is safe to try again, an error indicates no more tries should be
  238. // made and true indicates success.
  239. func PatchNodeOnce(client clientset.Interface, nodeName string, patchFn func(*v1.Node)) func() (bool, error) {
  240. return func() (bool, error) {
  241. // First get the node object
  242. n, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
  243. if err != nil {
  244. // TODO this should only be for timeouts
  245. return false, nil
  246. }
  247. // The node may appear to have no labels at first,
  248. // so we wait for it to get hostname label.
  249. if _, found := n.ObjectMeta.Labels[v1.LabelHostname]; !found {
  250. return false, nil
  251. }
  252. oldData, err := json.Marshal(n)
  253. if err != nil {
  254. return false, errors.Wrapf(err, "failed to marshal unmodified node %q into JSON", n.Name)
  255. }
  256. // Execute the mutating function
  257. patchFn(n)
  258. newData, err := json.Marshal(n)
  259. if err != nil {
  260. return false, errors.Wrapf(err, "failed to marshal modified node %q into JSON", n.Name)
  261. }
  262. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})
  263. if err != nil {
  264. return false, errors.Wrap(err, "failed to create two way merge patch")
  265. }
  266. if _, err := client.CoreV1().Nodes().Patch(context.TODO(), n.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}); err != nil {
  267. // TODO also check for timeouts
  268. if apierrors.IsConflict(err) {
  269. fmt.Println("Temporarily unable to update node metadata due to conflict (will retry)")
  270. return false, nil
  271. }
  272. return false, errors.Wrapf(err, "error patching node %q through apiserver", n.Name)
  273. }
  274. return true, nil
  275. }
  276. }
  277. // PatchNode tries to patch a node using patchFn for the actual mutating logic.
  278. // Retries are provided by the wait package.
  279. func PatchNode(client clientset.Interface, nodeName string, patchFn func(*v1.Node)) error {
  280. // wait.Poll will rerun the condition function every interval function if
  281. // the function returns false. If the condition function returns an error
  282. // then the retries end and the error is returned.
  283. return wait.Poll(constants.APICallRetryInterval, constants.PatchNodeTimeout, PatchNodeOnce(client, nodeName, patchFn))
  284. }
  285. // GetConfigMapWithRetry tries to retrieve a ConfigMap using the given client,
  286. // retrying if we get an unexpected error.
  287. //
  288. // TODO: evaluate if this can be done better. Potentially remove the retry if feasible.
  289. func GetConfigMapWithRetry(client clientset.Interface, namespace, name string) (*v1.ConfigMap, error) {
  290. var cm *v1.ConfigMap
  291. var lastError error
  292. err := wait.ExponentialBackoff(clientsetretry.DefaultBackoff, func() (bool, error) {
  293. var err error
  294. cm, err = client.CoreV1().ConfigMaps(namespace).Get(context.TODO(), name, metav1.GetOptions{})
  295. if err == nil {
  296. return true, nil
  297. }
  298. lastError = err
  299. return false, nil
  300. })
  301. if err == nil {
  302. return cm, nil
  303. }
  304. return nil, lastError
  305. }