dryrunclient.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. "bufio"
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "strings"
  20. "github.com/pkg/errors"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/runtime/schema"
  23. clientset "k8s.io/client-go/kubernetes"
  24. fakeclientset "k8s.io/client-go/kubernetes/fake"
  25. core "k8s.io/client-go/testing"
  26. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  27. )
  28. // DryRunGetter is an interface that must be supplied to the NewDryRunClient function in order to contstruct a fully functional fake dryrun clientset
  29. type DryRunGetter interface {
  30. HandleGetAction(core.GetAction) (bool, runtime.Object, error)
  31. HandleListAction(core.ListAction) (bool, runtime.Object, error)
  32. }
  33. // MarshalFunc takes care of converting any object to a byte array for displaying the object to the user
  34. type MarshalFunc func(runtime.Object, schema.GroupVersion) ([]byte, error)
  35. // DefaultMarshalFunc is the default MarshalFunc used; uses YAML to print objects to the user
  36. func DefaultMarshalFunc(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {
  37. return kubeadmutil.MarshalToYaml(obj, gv)
  38. }
  39. // DryRunClientOptions specifies options to pass to NewDryRunClientWithOpts in order to get a dryrun clientset
  40. type DryRunClientOptions struct {
  41. Writer io.Writer
  42. Getter DryRunGetter
  43. PrependReactors []core.Reactor
  44. AppendReactors []core.Reactor
  45. MarshalFunc MarshalFunc
  46. PrintGETAndLIST bool
  47. }
  48. // GetDefaultDryRunClientOptions returns the default DryRunClientOptions values
  49. func GetDefaultDryRunClientOptions(drg DryRunGetter, w io.Writer) DryRunClientOptions {
  50. return DryRunClientOptions{
  51. Writer: w,
  52. Getter: drg,
  53. PrependReactors: []core.Reactor{},
  54. AppendReactors: []core.Reactor{},
  55. MarshalFunc: DefaultMarshalFunc,
  56. PrintGETAndLIST: false,
  57. }
  58. }
  59. // actionWithName is the generic interface for an action that has a name associated with it
  60. // This just makes it easier to catch all actions that has a name; instead of hard-coding all request that has it associated
  61. type actionWithName interface {
  62. core.Action
  63. GetName() string
  64. }
  65. // actionWithObject is the generic interface for an action that has an object associated with it
  66. // This just makes it easier to catch all actions that has an object; instead of hard-coding all request that has it associated
  67. type actionWithObject interface {
  68. core.Action
  69. GetObject() runtime.Object
  70. }
  71. // NewDryRunClient is a wrapper for NewDryRunClientWithOpts using some default values
  72. func NewDryRunClient(drg DryRunGetter, w io.Writer) clientset.Interface {
  73. return NewDryRunClientWithOpts(GetDefaultDryRunClientOptions(drg, w))
  74. }
  75. // NewDryRunClientWithOpts returns a clientset.Interface that can be used normally for talking to the Kubernetes API.
  76. // This client doesn't apply changes to the backend. The client gets GET/LIST values from the DryRunGetter implementation.
  77. // This client logs all I/O to the writer w in YAML format
  78. func NewDryRunClientWithOpts(opts DryRunClientOptions) clientset.Interface {
  79. // Build a chain of reactors to act like a normal clientset; but log everything that is happening and don't change any state
  80. client := fakeclientset.NewSimpleClientset()
  81. // Build the chain of reactors. Order matters; first item here will be invoked first on match, then the second one will be evaluated, etc.
  82. defaultReactorChain := []core.Reactor{
  83. // Log everything that happens. Default the object if it's about to be created/updated so that the logged object is representative.
  84. &core.SimpleReactor{
  85. Verb: "*",
  86. Resource: "*",
  87. Reaction: func(action core.Action) (bool, runtime.Object, error) {
  88. logDryRunAction(action, opts.Writer, opts.MarshalFunc)
  89. return false, nil, nil
  90. },
  91. },
  92. // Let the DryRunGetter implementation take care of all GET requests.
  93. // The DryRunGetter implementation may call a real API Server behind the scenes or just fake everything
  94. &core.SimpleReactor{
  95. Verb: "get",
  96. Resource: "*",
  97. Reaction: func(action core.Action) (bool, runtime.Object, error) {
  98. getAction, ok := action.(core.GetAction)
  99. if !ok {
  100. // something's wrong, we can't handle this event
  101. return true, nil, errors.New("can't cast get reactor event action object to GetAction interface")
  102. }
  103. handled, obj, err := opts.Getter.HandleGetAction(getAction)
  104. if opts.PrintGETAndLIST {
  105. // Print the marshalled object format with one tab indentation
  106. objBytes, err := opts.MarshalFunc(obj, action.GetResource().GroupVersion())
  107. if err == nil {
  108. fmt.Println("[dryrun] Returning faked GET response:")
  109. PrintBytesWithLinePrefix(opts.Writer, objBytes, "\t")
  110. }
  111. }
  112. return handled, obj, err
  113. },
  114. },
  115. // Let the DryRunGetter implementation take care of all GET requests.
  116. // The DryRunGetter implementation may call a real API Server behind the scenes or just fake everything
  117. &core.SimpleReactor{
  118. Verb: "list",
  119. Resource: "*",
  120. Reaction: func(action core.Action) (bool, runtime.Object, error) {
  121. listAction, ok := action.(core.ListAction)
  122. if !ok {
  123. // something's wrong, we can't handle this event
  124. return true, nil, errors.New("can't cast list reactor event action object to ListAction interface")
  125. }
  126. handled, objs, err := opts.Getter.HandleListAction(listAction)
  127. if opts.PrintGETAndLIST {
  128. // Print the marshalled object format with one tab indentation
  129. objBytes, err := opts.MarshalFunc(objs, action.GetResource().GroupVersion())
  130. if err == nil {
  131. fmt.Println("[dryrun] Returning faked LIST response:")
  132. PrintBytesWithLinePrefix(opts.Writer, objBytes, "\t")
  133. }
  134. }
  135. return handled, objs, err
  136. },
  137. },
  138. // For the verbs that modify anything on the server; just return the object if present and exit successfully
  139. &core.SimpleReactor{
  140. Verb: "create",
  141. Resource: "*",
  142. Reaction: successfulModificationReactorFunc,
  143. },
  144. &core.SimpleReactor{
  145. Verb: "update",
  146. Resource: "*",
  147. Reaction: successfulModificationReactorFunc,
  148. },
  149. &core.SimpleReactor{
  150. Verb: "delete",
  151. Resource: "*",
  152. Reaction: successfulModificationReactorFunc,
  153. },
  154. &core.SimpleReactor{
  155. Verb: "delete-collection",
  156. Resource: "*",
  157. Reaction: successfulModificationReactorFunc,
  158. },
  159. &core.SimpleReactor{
  160. Verb: "patch",
  161. Resource: "*",
  162. Reaction: successfulModificationReactorFunc,
  163. },
  164. }
  165. // The chain of reactors will look like this:
  166. // opts.PrependReactors | defaultReactorChain | opts.AppendReactors | client.Fake.ReactionChain (default reactors for the fake clientset)
  167. fullReactorChain := append(opts.PrependReactors, defaultReactorChain...)
  168. fullReactorChain = append(fullReactorChain, opts.AppendReactors...)
  169. // Prepend the reaction chain with our reactors. Important, these MUST be prepended; not appended due to how the fake clientset works by default
  170. client.Fake.ReactionChain = append(fullReactorChain, client.Fake.ReactionChain...)
  171. return client
  172. }
  173. // successfulModificationReactorFunc is a no-op that just returns the POSTed/PUTed value if present; but does nothing to edit any backing data store.
  174. func successfulModificationReactorFunc(action core.Action) (bool, runtime.Object, error) {
  175. objAction, ok := action.(actionWithObject)
  176. if ok {
  177. return true, objAction.GetObject(), nil
  178. }
  179. return true, nil, nil
  180. }
  181. // logDryRunAction logs the action that was recorded by the "catch-all" (*,*) reactor and tells the user what would have happened in an user-friendly way
  182. func logDryRunAction(action core.Action, w io.Writer, marshalFunc MarshalFunc) {
  183. group := action.GetResource().Group
  184. if len(group) == 0 {
  185. group = "core"
  186. }
  187. fmt.Fprintf(w, "[dryrun] Would perform action %s on resource %q in API group \"%s/%s\"\n", strings.ToUpper(action.GetVerb()), action.GetResource().Resource, group, action.GetResource().Version)
  188. namedAction, ok := action.(actionWithName)
  189. if ok {
  190. fmt.Fprintf(w, "[dryrun] Resource name: %q\n", namedAction.GetName())
  191. }
  192. objAction, ok := action.(actionWithObject)
  193. if ok && objAction.GetObject() != nil {
  194. // Print the marshalled object with a tab indentation
  195. objBytes, err := marshalFunc(objAction.GetObject(), action.GetResource().GroupVersion())
  196. if err == nil {
  197. fmt.Println("[dryrun] Attached object:")
  198. PrintBytesWithLinePrefix(w, objBytes, "\t")
  199. }
  200. }
  201. patchAction, ok := action.(core.PatchAction)
  202. if ok {
  203. // Replace all occurrences of \" with a simple " when printing
  204. fmt.Fprintf(w, "[dryrun] Attached patch:\n\t%s\n", strings.Replace(string(patchAction.GetPatch()), `\"`, `"`, -1))
  205. }
  206. }
  207. // PrintBytesWithLinePrefix prints objBytes to writer w with linePrefix in the beginning of every line
  208. func PrintBytesWithLinePrefix(w io.Writer, objBytes []byte, linePrefix string) {
  209. scanner := bufio.NewScanner(bytes.NewReader(objBytes))
  210. for scanner.Scan() {
  211. fmt.Fprintf(w, "%s%s\n", linePrefix, scanner.Text())
  212. }
  213. }