exec.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "os"
  20. "os/exec"
  21. "github.com/containernetworking/cni/pkg/types"
  22. )
  23. func pluginErr(err error, output []byte) error {
  24. if _, ok := err.(*exec.ExitError); ok {
  25. emsg := types.Error{}
  26. if perr := json.Unmarshal(output, &emsg); perr != nil {
  27. return fmt.Errorf("netplugin failed but error parsing its diagnostic message %q: %v", string(output), perr)
  28. }
  29. details := ""
  30. if emsg.Details != "" {
  31. details = fmt.Sprintf("; %v", emsg.Details)
  32. }
  33. return fmt.Errorf("%v%v", emsg.Msg, details)
  34. }
  35. return err
  36. }
  37. func ExecPluginWithResult(pluginPath string, netconf []byte, args CNIArgs) (*types.Result, error) {
  38. stdoutBytes, err := execPlugin(pluginPath, netconf, args)
  39. if err != nil {
  40. return nil, err
  41. }
  42. res := &types.Result{}
  43. err = json.Unmarshal(stdoutBytes, res)
  44. return res, err
  45. }
  46. func ExecPluginWithoutResult(pluginPath string, netconf []byte, args CNIArgs) error {
  47. _, err := execPlugin(pluginPath, netconf, args)
  48. return err
  49. }
  50. func execPlugin(pluginPath string, netconf []byte, args CNIArgs) ([]byte, error) {
  51. stdout := &bytes.Buffer{}
  52. c := exec.Cmd{
  53. Env: args.AsEnv(),
  54. Path: pluginPath,
  55. Args: []string{pluginPath},
  56. Stdin: bytes.NewBuffer(netconf),
  57. Stdout: stdout,
  58. Stderr: os.Stderr,
  59. }
  60. if err := c.Run(); err != nil {
  61. return nil, pluginErr(err, stdout.Bytes())
  62. }
  63. return stdout.Bytes(), nil
  64. }