driver-call.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. Copyright 2017 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 flexvolume
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "time"
  19. "k8s.io/klog"
  20. "k8s.io/kubernetes/pkg/volume"
  21. )
  22. const (
  23. // Driver calls
  24. initCmd = "init"
  25. getVolumeNameCmd = "getvolumename"
  26. isAttached = "isattached"
  27. attachCmd = "attach"
  28. waitForAttachCmd = "waitforattach"
  29. mountDeviceCmd = "mountdevice"
  30. detachCmd = "detach"
  31. unmountDeviceCmd = "unmountdevice"
  32. mountCmd = "mount"
  33. unmountCmd = "unmount"
  34. expandVolumeCmd = "expandvolume"
  35. expandFSCmd = "expandfs"
  36. // Option keys
  37. optionFSType = "kubernetes.io/fsType"
  38. optionReadWrite = "kubernetes.io/readwrite"
  39. optionKeySecret = "kubernetes.io/secret"
  40. optionFSGroup = "kubernetes.io/mounterArgs.FsGroup"
  41. optionMountsDir = "kubernetes.io/mountsDir"
  42. optionPVorVolumeName = "kubernetes.io/pvOrVolumeName"
  43. optionKeyPodName = "kubernetes.io/pod.name"
  44. optionKeyPodNamespace = "kubernetes.io/pod.namespace"
  45. optionKeyPodUID = "kubernetes.io/pod.uid"
  46. optionKeyServiceAccountName = "kubernetes.io/serviceAccount.name"
  47. )
  48. const (
  49. // StatusSuccess represents the successful completion of command.
  50. StatusSuccess = "Success"
  51. // StatusNotSupported represents that the command is not supported.
  52. StatusNotSupported = "Not supported"
  53. )
  54. var (
  55. errTimeout = fmt.Errorf("Timeout")
  56. )
  57. // DriverCall implements the basic contract between FlexVolume and its driver.
  58. // The caller is responsible for providing the required args.
  59. type DriverCall struct {
  60. Command string
  61. Timeout time.Duration
  62. plugin *flexVolumePlugin
  63. args []string
  64. }
  65. func (plugin *flexVolumePlugin) NewDriverCall(command string) *DriverCall {
  66. return plugin.NewDriverCallWithTimeout(command, 0)
  67. }
  68. func (plugin *flexVolumePlugin) NewDriverCallWithTimeout(command string, timeout time.Duration) *DriverCall {
  69. return &DriverCall{
  70. Command: command,
  71. Timeout: timeout,
  72. plugin: plugin,
  73. args: []string{command},
  74. }
  75. }
  76. // Append appends arg into driver call argument list
  77. func (dc *DriverCall) Append(arg string) {
  78. dc.args = append(dc.args, arg)
  79. }
  80. // AppendSpec appends volume spec to driver call argument list
  81. func (dc *DriverCall) AppendSpec(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) error {
  82. optionsForDriver, err := NewOptionsForDriver(spec, host, extraOptions)
  83. if err != nil {
  84. return err
  85. }
  86. jsonBytes, err := json.Marshal(optionsForDriver)
  87. if err != nil {
  88. return fmt.Errorf("Failed to marshal spec, error: %s", err.Error())
  89. }
  90. dc.Append(string(jsonBytes))
  91. return nil
  92. }
  93. // Run executes the driver call
  94. func (dc *DriverCall) Run() (*DriverStatus, error) {
  95. if dc.plugin.isUnsupported(dc.Command) {
  96. return nil, errors.New(StatusNotSupported)
  97. }
  98. execPath := dc.plugin.getExecutable()
  99. cmd := dc.plugin.runner.Command(execPath, dc.args...)
  100. timeout := false
  101. if dc.Timeout > 0 {
  102. timer := time.AfterFunc(dc.Timeout, func() {
  103. timeout = true
  104. cmd.Stop()
  105. })
  106. defer timer.Stop()
  107. }
  108. output, execErr := cmd.CombinedOutput()
  109. if execErr != nil {
  110. if timeout {
  111. return nil, errTimeout
  112. }
  113. _, err := handleCmdResponse(dc.Command, output)
  114. if err == nil {
  115. klog.Errorf("FlexVolume: driver bug: %s: exec error (%s) but no error in response.", execPath, execErr)
  116. return nil, execErr
  117. }
  118. if isCmdNotSupportedErr(err) {
  119. dc.plugin.unsupported(dc.Command)
  120. } else {
  121. klog.Warningf("FlexVolume: driver call failed: executable: %s, args: %s, error: %s, output: %q", execPath, dc.args, execErr.Error(), output)
  122. }
  123. return nil, err
  124. }
  125. status, err := handleCmdResponse(dc.Command, output)
  126. if err != nil {
  127. if isCmdNotSupportedErr(err) {
  128. dc.plugin.unsupported(dc.Command)
  129. }
  130. return nil, err
  131. }
  132. return status, nil
  133. }
  134. // OptionsForDriver represents the spec given to the driver.
  135. type OptionsForDriver map[string]string
  136. // NewOptionsForDriver create driver options given volume spec
  137. func NewOptionsForDriver(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) (OptionsForDriver, error) {
  138. volSourceFSType, err := getFSType(spec)
  139. if err != nil {
  140. return nil, err
  141. }
  142. readOnly, err := getReadOnly(spec)
  143. if err != nil {
  144. return nil, err
  145. }
  146. volSourceOptions, err := getOptions(spec)
  147. if err != nil {
  148. return nil, err
  149. }
  150. options := map[string]string{}
  151. options[optionFSType] = volSourceFSType
  152. if readOnly {
  153. options[optionReadWrite] = "ro"
  154. } else {
  155. options[optionReadWrite] = "rw"
  156. }
  157. options[optionPVorVolumeName] = spec.Name()
  158. for key, value := range extraOptions {
  159. options[key] = value
  160. }
  161. for key, value := range volSourceOptions {
  162. options[key] = value
  163. }
  164. return OptionsForDriver(options), nil
  165. }
  166. // DriverStatus represents the return value of the driver callout.
  167. type DriverStatus struct {
  168. // Status of the callout. One of "Success", "Failure" or "Not supported".
  169. Status string `json:"status"`
  170. // Reason for success/failure.
  171. Message string `json:"message,omitempty"`
  172. // Path to the device attached. This field is valid only for attach calls.
  173. // ie: /dev/sdx
  174. DevicePath string `json:"device,omitempty"`
  175. // Cluster wide unique name of the volume.
  176. VolumeName string `json:"volumeName,omitempty"`
  177. // Represents volume is attached on the node
  178. Attached bool `json:"attached,omitempty"`
  179. // Returns capabilities of the driver.
  180. // By default we assume all the capabilities are supported.
  181. // If the plugin does not support a capability, it can return false for that capability.
  182. Capabilities *DriverCapabilities `json:",omitempty"`
  183. // Returns the actual size of the volume after resizing is done, the size is in bytes.
  184. ActualVolumeSize int64 `json:"volumeNewSize,omitempty"`
  185. }
  186. // DriverCapabilities represents what driver can do
  187. type DriverCapabilities struct {
  188. Attach bool `json:"attach"`
  189. SELinuxRelabel bool `json:"selinuxRelabel"`
  190. SupportsMetrics bool `json:"supportsMetrics"`
  191. FSGroup bool `json:"fsGroup"`
  192. RequiresFSResize bool `json:"requiresFSResize"`
  193. }
  194. func defaultCapabilities() *DriverCapabilities {
  195. return &DriverCapabilities{
  196. Attach: true,
  197. SELinuxRelabel: true,
  198. SupportsMetrics: false,
  199. FSGroup: true,
  200. RequiresFSResize: true,
  201. }
  202. }
  203. // isCmdNotSupportedErr checks if the error corresponds to command not supported by
  204. // driver.
  205. func isCmdNotSupportedErr(err error) bool {
  206. if err != nil && err.Error() == StatusNotSupported {
  207. return true
  208. }
  209. return false
  210. }
  211. // handleCmdResponse processes the command output and returns the appropriate
  212. // error code or message.
  213. func handleCmdResponse(cmd string, output []byte) (*DriverStatus, error) {
  214. status := DriverStatus{
  215. Capabilities: defaultCapabilities(),
  216. }
  217. if err := json.Unmarshal(output, &status); err != nil {
  218. klog.Errorf("Failed to unmarshal output for command: %s, output: %q, error: %s", cmd, string(output), err.Error())
  219. return nil, err
  220. } else if status.Status == StatusNotSupported {
  221. klog.V(5).Infof("%s command is not supported by the driver", cmd)
  222. return nil, errors.New(status.Status)
  223. } else if status.Status != StatusSuccess {
  224. errMsg := fmt.Sprintf("%s command failed, status: %s, reason: %s", cmd, status.Status, status.Message)
  225. klog.Errorf(errMsg)
  226. return nil, fmt.Errorf("%s", errMsg)
  227. }
  228. return &status, nil
  229. }