idempotency.go 13 KB

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