operation_generator.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 operationexecutor implements interfaces that enable execution of
  14. // register and unregister operations with a
  15. // goroutinemap so that more than one operation is never triggered
  16. // on the same plugin.
  17. package operationexecutor
  18. import (
  19. "context"
  20. "fmt"
  21. "net"
  22. "time"
  23. "github.com/pkg/errors"
  24. "google.golang.org/grpc"
  25. "k8s.io/client-go/tools/record"
  26. registerapi "k8s.io/kubernetes/pkg/kubelet/apis/pluginregistration/v1"
  27. "k8s.io/kubernetes/pkg/kubelet/pluginmanager/cache"
  28. )
  29. const (
  30. dialTimeoutDuration = 10 * time.Second
  31. notifyTimeoutDuration = 5 * time.Second
  32. )
  33. var _ OperationGenerator = &operationGenerator{}
  34. type operationGenerator struct {
  35. // recorder is used to record events in the API server
  36. recorder record.EventRecorder
  37. }
  38. // NewOperationGenerator is returns instance of operationGenerator
  39. func NewOperationGenerator(recorder record.EventRecorder) OperationGenerator {
  40. return &operationGenerator{
  41. recorder: recorder,
  42. }
  43. }
  44. // OperationGenerator interface that extracts out the functions from operation_executor to make it dependency injectable
  45. type OperationGenerator interface {
  46. // Generates the RegisterPlugin function needed to perform the registration of a plugin
  47. GenerateRegisterPluginFunc(
  48. socketPath string,
  49. foundInDeprecatedDir bool,
  50. timestamp time.Time,
  51. pluginHandlers map[string]cache.PluginHandler,
  52. actualStateOfWorldUpdater ActualStateOfWorldUpdater) func() error
  53. // Generates the UnregisterPlugin function needed to perform the unregistration of a plugin
  54. GenerateUnregisterPluginFunc(
  55. socketPath string,
  56. pluginHandlers map[string]cache.PluginHandler,
  57. actualStateOfWorldUpdater ActualStateOfWorldUpdater) func() error
  58. }
  59. func (og *operationGenerator) GenerateRegisterPluginFunc(
  60. socketPath string,
  61. foundInDeprecatedDir bool,
  62. timestamp time.Time,
  63. pluginHandlers map[string]cache.PluginHandler,
  64. actualStateOfWorldUpdater ActualStateOfWorldUpdater) func() error {
  65. registerPluginFunc := func() error {
  66. client, conn, err := dial(socketPath, dialTimeoutDuration)
  67. if err != nil {
  68. return fmt.Errorf("RegisterPlugin error -- dial failed at socket %s, err: %v", socketPath, err)
  69. }
  70. defer conn.Close()
  71. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  72. defer cancel()
  73. infoResp, err := client.GetInfo(ctx, &registerapi.InfoRequest{})
  74. if err != nil {
  75. return fmt.Errorf("RegisterPlugin error -- failed to get plugin info using RPC GetInfo at socket %s, err: %v", socketPath, err)
  76. }
  77. handler, ok := pluginHandlers[infoResp.Type]
  78. if !ok {
  79. if err := og.notifyPlugin(client, false, fmt.Sprintf("RegisterPlugin error -- no handler registered for plugin type: %s at socket %s", infoResp.Type, socketPath)); err != nil {
  80. return fmt.Errorf("RegisterPlugin error -- failed to send error at socket %s, err: %v", socketPath, err)
  81. }
  82. return fmt.Errorf("RegisterPlugin error -- no handler registered for plugin type: %s at socket %s", infoResp.Type, socketPath)
  83. }
  84. if infoResp.Endpoint == "" {
  85. infoResp.Endpoint = socketPath
  86. }
  87. if err := handler.ValidatePlugin(infoResp.Name, infoResp.Endpoint, infoResp.SupportedVersions, foundInDeprecatedDir); err != nil {
  88. if err = og.notifyPlugin(client, false, fmt.Sprintf("RegisterPlugin error -- plugin validation failed with err: %v", err)); err != nil {
  89. return fmt.Errorf("RegisterPlugin error -- failed to send error at socket %s, err: %v", socketPath, err)
  90. }
  91. return fmt.Errorf("RegisterPlugin error -- pluginHandler.ValidatePluginFunc failed")
  92. }
  93. // We add the plugin to the actual state of world cache before calling a plugin consumer's Register handle
  94. // so that if we receive a delete event during Register Plugin, we can process it as a DeRegister call.
  95. actualStateOfWorldUpdater.AddPlugin(cache.PluginInfo{
  96. SocketPath: socketPath,
  97. FoundInDeprecatedDir: foundInDeprecatedDir,
  98. Timestamp: timestamp,
  99. })
  100. if err := handler.RegisterPlugin(infoResp.Name, infoResp.Endpoint, infoResp.SupportedVersions); err != nil {
  101. return og.notifyPlugin(client, false, fmt.Sprintf("RegisterPlugin error -- plugin registration failed with err: %v", err))
  102. }
  103. // Notify is called after register to guarantee that even if notify throws an error Register will always be called after validate
  104. if err := og.notifyPlugin(client, true, ""); err != nil {
  105. return fmt.Errorf("RegisterPlugin error -- failed to send registration status at socket %s, err: %v", socketPath, err)
  106. }
  107. return nil
  108. }
  109. return registerPluginFunc
  110. }
  111. func (og *operationGenerator) GenerateUnregisterPluginFunc(
  112. socketPath string,
  113. pluginHandlers map[string]cache.PluginHandler,
  114. actualStateOfWorldUpdater ActualStateOfWorldUpdater) func() error {
  115. unregisterPluginFunc := func() error {
  116. client, conn, err := dial(socketPath, dialTimeoutDuration)
  117. if err != nil {
  118. return fmt.Errorf("UnregisterPlugin error -- dial failed at socket %s, err: %v", socketPath, err)
  119. }
  120. defer conn.Close()
  121. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  122. defer cancel()
  123. infoResp, err := client.GetInfo(ctx, &registerapi.InfoRequest{})
  124. if err != nil {
  125. return fmt.Errorf("UnregisterPlugin error -- failed to get plugin info using RPC GetInfo at socket %s, err: %v", socketPath, err)
  126. }
  127. handler, ok := pluginHandlers[infoResp.Type]
  128. if !ok {
  129. return fmt.Errorf("UnregisterPlugin error -- no handler registered for plugin type: %s at socket %s", infoResp.Type, socketPath)
  130. }
  131. // We remove the plugin to the actual state of world cache before calling a plugin consumer's Unregister handle
  132. // so that if we receive a register event during Register Plugin, we can process it as a Register call.
  133. actualStateOfWorldUpdater.RemovePlugin(socketPath)
  134. handler.DeRegisterPlugin(infoResp.Name)
  135. return nil
  136. }
  137. return unregisterPluginFunc
  138. }
  139. func (og *operationGenerator) notifyPlugin(client registerapi.RegistrationClient, registered bool, errStr string) error {
  140. ctx, cancel := context.WithTimeout(context.Background(), notifyTimeoutDuration)
  141. defer cancel()
  142. status := &registerapi.RegistrationStatus{
  143. PluginRegistered: registered,
  144. Error: errStr,
  145. }
  146. if _, err := client.NotifyRegistrationStatus(ctx, status); err != nil {
  147. return errors.Wrap(err, errStr)
  148. }
  149. if errStr != "" {
  150. return errors.New(errStr)
  151. }
  152. return nil
  153. }
  154. // Dial establishes the gRPC communication with the picked up plugin socket. https://godoc.org/google.golang.org/grpc#Dial
  155. func dial(unixSocketPath string, timeout time.Duration) (registerapi.RegistrationClient, *grpc.ClientConn, error) {
  156. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  157. defer cancel()
  158. c, err := grpc.DialContext(ctx, unixSocketPath, grpc.WithInsecure(), grpc.WithBlock(),
  159. grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
  160. return net.DialTimeout("unix", addr, timeout)
  161. }),
  162. )
  163. if err != nil {
  164. return nil, nil, fmt.Errorf("failed to dial socket %s, err: %v", unixSocketPath, err)
  165. }
  166. return registerapi.NewRegistrationClient(c), c, nil
  167. }