helper.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2019 Yunion
  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 volume_mount
  15. import (
  16. "fmt"
  17. "yunion.io/x/pkg/errors"
  18. hostapi "yunion.io/x/onecloud/pkg/apis/host"
  19. "yunion.io/x/onecloud/pkg/util/procutils"
  20. )
  21. func TouchFile(file string) error {
  22. out, err := procutils.NewRemoteCommandAsFarAsPossible("touch", file).Output()
  23. if err != nil {
  24. return errors.Wrapf(err, "touch %s: %s", file, out)
  25. }
  26. return nil
  27. }
  28. func EnsureDir(dir string) error {
  29. out, err := procutils.NewRemoteCommandAsFarAsPossible("mkdir", "-p", dir).Output()
  30. if err != nil {
  31. return errors.Wrapf(err, "mkdir -p %s: %s", dir, out)
  32. }
  33. return nil
  34. }
  35. func RemoveDir(dir string) error {
  36. out, err := procutils.NewRemoteCommandAsFarAsPossible("rm", "-rf", dir).Output()
  37. if err != nil {
  38. return errors.Wrapf(err, "rm -rf %s: %s", dir, out)
  39. }
  40. return nil
  41. }
  42. func ChangeDirOwner(pod IPodInfo, drv IVolumeMount, ctrId string, vol *hostapi.ContainerVolumeMount) error {
  43. if vol.FsUser == nil && vol.FsGroup == nil {
  44. return errors.Errorf("specify fs_user or fs_group")
  45. }
  46. hostPath, err := drv.GetRuntimeMountHostPath(pod, ctrId, vol)
  47. if err != nil {
  48. return errors.Wrap(err, "GetRuntimeMountHostPath")
  49. }
  50. return ChangeDirOwnerDirectly(hostPath, vol.FsUser, vol.FsGroup)
  51. }
  52. func ChangeDirOwnerDirectly(hostPath string, fsUser, fsGroup *int64) error {
  53. args := ""
  54. if fsUser != nil {
  55. args = fmt.Sprintf("%d", *fsUser)
  56. }
  57. if fsGroup != nil {
  58. args = fmt.Sprintf("%s:%d", args, *fsGroup)
  59. }
  60. if args == "" {
  61. return nil
  62. }
  63. out, err := procutils.NewRemoteCommandAsFarAsPossible("chown", args, hostPath).Output()
  64. if err != nil {
  65. return errors.Wrapf(err, "chown %s %s: %s", args, hostPath, string(out))
  66. }
  67. return nil
  68. }
  69. func CopyFile(src, dst string) error {
  70. out, err := procutils.NewRemoteCommandAsFarAsPossible("cp", src, dst).Output()
  71. if err != nil {
  72. return errors.Wrapf(err, "cp %s %s: %s", src, dst, string(out))
  73. }
  74. return nil
  75. }