utils.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 aws
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. )
  20. func GetBucketName(regionId string, imageId string) string {
  21. return fmt.Sprintf("imgcache-%s-%s", strings.ToLower(regionId), imageId)
  22. }
  23. func StrVal(s *string) string {
  24. if s != nil {
  25. return *s
  26. }
  27. return ""
  28. }
  29. func IntVal(s *int64) int64 {
  30. if s != nil {
  31. return *s
  32. }
  33. return 0
  34. }
  35. // fill a pointer struct with zero value.
  36. func FillZero(i interface{}) error {
  37. V := reflect.Indirect(reflect.ValueOf(i))
  38. if !V.CanSet() {
  39. return fmt.Errorf("input is not addressable: %#v", i)
  40. }
  41. if V.Kind() != reflect.Struct {
  42. return fmt.Errorf("only accept struct type")
  43. }
  44. for i := 0; i < V.NumField(); i++ {
  45. field := V.Field(i)
  46. if field.Kind() == reflect.Ptr && field.IsNil() {
  47. if field.CanSet() {
  48. field.Set(reflect.New(field.Type().Elem()))
  49. }
  50. }
  51. vField := reflect.Indirect(field)
  52. switch vField.Kind() {
  53. case reflect.Map:
  54. vField.Set(reflect.MakeMap(vField.Type()))
  55. case reflect.Struct:
  56. if field.CanInterface() {
  57. err := FillZero(field.Interface())
  58. if err != nil {
  59. return err
  60. }
  61. }
  62. }
  63. }
  64. return nil
  65. }
  66. func NextDeviceName(curDeviceNames []string) (string, error) {
  67. currents := []string{}
  68. for _, item := range curDeviceNames {
  69. currents = append(currents, strings.ToLower(item))
  70. }
  71. for _, prefix := range []string{"/dev/sd", "dev/vxd"} {
  72. for s := rune('a'); s < rune('z'); s++ {
  73. device := fmt.Sprintf("%s%c", prefix, s)
  74. found := false
  75. for _, item := range currents {
  76. if strings.HasPrefix(item, device) {
  77. found = true
  78. }
  79. }
  80. if !found {
  81. return device, nil
  82. }
  83. }
  84. }
  85. return "", fmt.Errorf("disk devicename out of index, current deivces: %s", currents)
  86. }