raw_exec.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2016 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. "io"
  20. "os/exec"
  21. "github.com/containernetworking/cni/pkg/types"
  22. )
  23. type RawExec struct {
  24. Stderr io.Writer
  25. }
  26. func (e *RawExec) ExecPlugin(pluginPath string, stdinData []byte, environ []string) ([]byte, error) {
  27. stdout := &bytes.Buffer{}
  28. c := exec.Cmd{
  29. Env: environ,
  30. Path: pluginPath,
  31. Args: []string{pluginPath},
  32. Stdin: bytes.NewBuffer(stdinData),
  33. Stdout: stdout,
  34. Stderr: e.Stderr,
  35. }
  36. if err := c.Run(); err != nil {
  37. return nil, pluginErr(err, stdout.Bytes())
  38. }
  39. return stdout.Bytes(), nil
  40. }
  41. func pluginErr(err error, output []byte) error {
  42. if _, ok := err.(*exec.ExitError); ok {
  43. emsg := types.Error{}
  44. if perr := json.Unmarshal(output, &emsg); perr != nil {
  45. emsg.Msg = fmt.Sprintf("netplugin failed but error parsing its diagnostic message %q: %v", string(output), perr)
  46. }
  47. return &emsg
  48. }
  49. return err
  50. }