exec.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // Copyright 2015 CNI authors
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package invoke
  15. import (
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "os"
  20. "github.com/containernetworking/cni/pkg/types"
  21. "github.com/containernetworking/cni/pkg/types/create"
  22. "github.com/containernetworking/cni/pkg/version"
  23. )
  24. // Exec is an interface encapsulates all operations that deal with finding
  25. // and executing a CNI plugin. Tests may provide a fake implementation
  26. // to avoid writing fake plugins to temporary directories during the test.
  27. type Exec interface {
  28. ExecPlugin(ctx context.Context, pluginPath string, stdinData []byte, environ []string) ([]byte, error)
  29. FindInPath(plugin string, paths []string) (string, error)
  30. Decode(jsonBytes []byte) (version.PluginInfo, error)
  31. }
  32. // Plugin must return result in same version as specified in netconf; but
  33. // for backwards compatibility reasons if the result version is empty use
  34. // config version (rather than technically correct 0.1.0).
  35. // https://github.com/containernetworking/cni/issues/895
  36. func fixupResultVersion(netconf, result []byte) (string, []byte, error) {
  37. versionDecoder := &version.ConfigDecoder{}
  38. confVersion, err := versionDecoder.Decode(netconf)
  39. if err != nil {
  40. return "", nil, err
  41. }
  42. var rawResult map[string]interface{}
  43. if err := json.Unmarshal(result, &rawResult); err != nil {
  44. return "", nil, fmt.Errorf("failed to unmarshal raw result: %w", err)
  45. }
  46. // plugin output of "null" is successfully unmarshalled, but results in a nil
  47. // map which causes a panic when the confVersion is assigned below.
  48. if rawResult == nil {
  49. rawResult = make(map[string]interface{})
  50. }
  51. // Manually decode Result version; we need to know whether its cniVersion
  52. // is empty, while built-in decoders (correctly) substitute 0.1.0 for an
  53. // empty version per the CNI spec.
  54. if resultVerRaw, ok := rawResult["cniVersion"]; ok {
  55. resultVer, ok := resultVerRaw.(string)
  56. if ok && resultVer != "" {
  57. return resultVer, result, nil
  58. }
  59. }
  60. // If the cniVersion is not present or empty, assume the result is
  61. // the same CNI spec version as the config
  62. rawResult["cniVersion"] = confVersion
  63. newBytes, err := json.Marshal(rawResult)
  64. if err != nil {
  65. return "", nil, fmt.Errorf("failed to remarshal fixed result: %w", err)
  66. }
  67. return confVersion, newBytes, nil
  68. }
  69. // For example, a testcase could pass an instance of the following fakeExec
  70. // object to ExecPluginWithResult() to verify the incoming stdin and environment
  71. // and provide a tailored response:
  72. //
  73. // import (
  74. // "encoding/json"
  75. // "path"
  76. // "strings"
  77. // )
  78. //
  79. // type fakeExec struct {
  80. // version.PluginDecoder
  81. // }
  82. //
  83. // func (f *fakeExec) ExecPlugin(pluginPath string, stdinData []byte, environ []string) ([]byte, error) {
  84. // net := &types.NetConf{}
  85. // err := json.Unmarshal(stdinData, net)
  86. // if err != nil {
  87. // return nil, fmt.Errorf("failed to unmarshal configuration: %v", err)
  88. // }
  89. // pluginName := path.Base(pluginPath)
  90. // if pluginName != net.Type {
  91. // return nil, fmt.Errorf("plugin name %q did not match config type %q", pluginName, net.Type)
  92. // }
  93. // for _, e := range environ {
  94. // // Check environment for forced failure request
  95. // parts := strings.Split(e, "=")
  96. // if len(parts) > 0 && parts[0] == "FAIL" {
  97. // return nil, fmt.Errorf("failed to execute plugin %s", pluginName)
  98. // }
  99. // }
  100. // return []byte("{\"CNIVersion\":\"0.4.0\"}"), nil
  101. // }
  102. //
  103. // func (f *fakeExec) FindInPath(plugin string, paths []string) (string, error) {
  104. // if len(paths) > 0 {
  105. // return path.Join(paths[0], plugin), nil
  106. // }
  107. // return "", fmt.Errorf("failed to find plugin %s in paths %v", plugin, paths)
  108. // }
  109. func ExecPluginWithResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) (types.Result, error) {
  110. if exec == nil {
  111. exec = defaultExec
  112. }
  113. stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv())
  114. if err != nil {
  115. return nil, err
  116. }
  117. resultVersion, fixedBytes, err := fixupResultVersion(netconf, stdoutBytes)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return create.Create(resultVersion, fixedBytes)
  122. }
  123. func ExecPluginWithoutResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) error {
  124. if exec == nil {
  125. exec = defaultExec
  126. }
  127. _, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv())
  128. return err
  129. }
  130. // GetVersionInfo returns the version information available about the plugin.
  131. // For recent-enough plugins, it uses the information returned by the VERSION
  132. // command. For older plugins which do not recognize that command, it reports
  133. // version 0.1.0
  134. func GetVersionInfo(ctx context.Context, pluginPath string, exec Exec) (version.PluginInfo, error) {
  135. if exec == nil {
  136. exec = defaultExec
  137. }
  138. args := &Args{
  139. Command: "VERSION",
  140. // set fake values required by plugins built against an older version of skel
  141. NetNS: "dummy",
  142. IfName: "dummy",
  143. Path: "dummy",
  144. }
  145. stdin := []byte(fmt.Sprintf(`{"cniVersion":%q}`, version.Current()))
  146. stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, stdin, args.AsEnv())
  147. if err != nil {
  148. if err.Error() == "unknown CNI_COMMAND: VERSION" {
  149. return version.PluginSupports("0.1.0"), nil
  150. }
  151. return nil, err
  152. }
  153. return exec.Decode(stdoutBytes)
  154. }
  155. // DefaultExec is an object that implements the Exec interface which looks
  156. // for and executes plugins from disk.
  157. type DefaultExec struct {
  158. *RawExec
  159. version.PluginDecoder
  160. }
  161. // DefaultExec implements the Exec interface
  162. var _ Exec = &DefaultExec{}
  163. var defaultExec = &DefaultExec{
  164. RawExec: &RawExec{Stderr: os.Stderr},
  165. }