args.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. "os"
  17. "strings"
  18. )
  19. type CNIArgs interface {
  20. // For use with os/exec; i.e., return nil to inherit the
  21. // environment from this process
  22. AsEnv() []string
  23. }
  24. type inherited struct{}
  25. var inheritArgsFromEnv inherited
  26. func (_ *inherited) AsEnv() []string {
  27. return nil
  28. }
  29. func ArgsFromEnv() CNIArgs {
  30. return &inheritArgsFromEnv
  31. }
  32. type Args struct {
  33. Command string
  34. ContainerID string
  35. NetNS string
  36. PluginArgs [][2]string
  37. PluginArgsStr string
  38. IfName string
  39. Path string
  40. }
  41. // Args implements the CNIArgs interface
  42. var _ CNIArgs = &Args{}
  43. func (args *Args) AsEnv() []string {
  44. env := os.Environ()
  45. pluginArgsStr := args.PluginArgsStr
  46. if pluginArgsStr == "" {
  47. pluginArgsStr = stringify(args.PluginArgs)
  48. }
  49. // Ensure that the custom values are first, so any value present in
  50. // the process environment won't override them.
  51. env = append([]string{
  52. "CNI_COMMAND=" + args.Command,
  53. "CNI_CONTAINERID=" + args.ContainerID,
  54. "CNI_NETNS=" + args.NetNS,
  55. "CNI_ARGS=" + pluginArgsStr,
  56. "CNI_IFNAME=" + args.IfName,
  57. "CNI_PATH=" + args.Path,
  58. }, env...)
  59. return env
  60. }
  61. // taken from rkt/networking/net_plugin.go
  62. func stringify(pluginArgs [][2]string) string {
  63. entries := make([]string, len(pluginArgs))
  64. for i, kv := range pluginArgs {
  65. entries[i] = strings.Join(kv[:], "=")
  66. }
  67. return strings.Join(entries, ";")
  68. }