utils.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package util
  7. import (
  8. "context"
  9. "fmt"
  10. "net"
  11. "net/url"
  12. "reflect"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/thejerf/suture/v4"
  17. )
  18. type defaultParser interface {
  19. ParseDefault(string) error
  20. }
  21. // SetDefaults sets default values on a struct, based on the default annotation.
  22. func SetDefaults(data interface{}) {
  23. s := reflect.ValueOf(data).Elem()
  24. t := s.Type()
  25. for i := 0; i < s.NumField(); i++ {
  26. f := s.Field(i)
  27. tag := t.Field(i).Tag
  28. v := tag.Get("default")
  29. if len(v) > 0 {
  30. if f.CanInterface() {
  31. if parser, ok := f.Interface().(defaultParser); ok {
  32. if err := parser.ParseDefault(v); err != nil {
  33. panic(err)
  34. }
  35. continue
  36. }
  37. }
  38. if f.CanAddr() && f.Addr().CanInterface() {
  39. if parser, ok := f.Addr().Interface().(defaultParser); ok {
  40. if err := parser.ParseDefault(v); err != nil {
  41. panic(err)
  42. }
  43. continue
  44. }
  45. }
  46. switch f.Interface().(type) {
  47. case string:
  48. f.SetString(v)
  49. case int, uint32, int32, int64, uint64:
  50. i, err := strconv.ParseInt(v, 10, 64)
  51. if err != nil {
  52. panic(err)
  53. }
  54. f.SetInt(i)
  55. case float64, float32:
  56. i, err := strconv.ParseFloat(v, 64)
  57. if err != nil {
  58. panic(err)
  59. }
  60. f.SetFloat(i)
  61. case bool:
  62. f.SetBool(v == "true")
  63. case []string:
  64. // We don't do anything with string slices here. Any default
  65. // we set will be appended to by the XML decoder, so we fill
  66. // those after decoding.
  67. default:
  68. panic(f.Type())
  69. }
  70. } else if f.CanSet() && f.Kind() == reflect.Struct && f.CanAddr() {
  71. if addr := f.Addr(); addr.CanInterface() {
  72. SetDefaults(addr.Interface())
  73. }
  74. }
  75. }
  76. }
  77. // CopyMatchingTag copies fields tagged tag:"value" from "from" struct onto "to" struct.
  78. func CopyMatchingTag(from interface{}, to interface{}, tag string, shouldCopy func(value string) bool) {
  79. fromStruct := reflect.ValueOf(from).Elem()
  80. fromType := fromStruct.Type()
  81. toStruct := reflect.ValueOf(to).Elem()
  82. toType := toStruct.Type()
  83. if fromType != toType {
  84. panic(fmt.Sprintf("non equal types: %s != %s", fromType, toType))
  85. }
  86. for i := 0; i < toStruct.NumField(); i++ {
  87. fromField := fromStruct.Field(i)
  88. toField := toStruct.Field(i)
  89. if !toField.CanSet() {
  90. // Unexported fields
  91. continue
  92. }
  93. structTag := toType.Field(i).Tag
  94. v := structTag.Get(tag)
  95. if shouldCopy(v) {
  96. toField.Set(fromField)
  97. }
  98. }
  99. }
  100. // UniqueTrimmedStrings returns a list of all unique strings in ss,
  101. // in the order in which they first appear in ss, after trimming away
  102. // leading and trailing spaces.
  103. func UniqueTrimmedStrings(ss []string) []string {
  104. var m = make(map[string]struct{}, len(ss))
  105. var us = make([]string, 0, len(ss))
  106. for _, v := range ss {
  107. v = strings.Trim(v, " ")
  108. if _, ok := m[v]; ok {
  109. continue
  110. }
  111. m[v] = struct{}{}
  112. us = append(us, v)
  113. }
  114. return us
  115. }
  116. func FillNilExceptDeprecated(data interface{}) {
  117. fillNil(data, true)
  118. }
  119. func FillNil(data interface{}) {
  120. fillNil(data, false)
  121. }
  122. func fillNil(data interface{}, skipDeprecated bool) {
  123. s := reflect.ValueOf(data).Elem()
  124. t := s.Type()
  125. for i := 0; i < s.NumField(); i++ {
  126. if skipDeprecated && strings.HasPrefix(t.Field(i).Name, "Deprecated") {
  127. continue
  128. }
  129. f := s.Field(i)
  130. for f.Kind() == reflect.Ptr && f.IsZero() && f.CanSet() {
  131. newValue := reflect.New(f.Type().Elem())
  132. f.Set(newValue)
  133. f = f.Elem()
  134. }
  135. if f.CanSet() {
  136. if f.IsZero() {
  137. switch f.Kind() {
  138. case reflect.Map:
  139. f.Set(reflect.MakeMap(f.Type()))
  140. case reflect.Slice:
  141. f.Set(reflect.MakeSlice(f.Type(), 0, 0))
  142. case reflect.Chan:
  143. f.Set(reflect.MakeChan(f.Type(), 0))
  144. }
  145. }
  146. switch f.Kind() {
  147. case reflect.Slice:
  148. if f.Type().Elem().Kind() != reflect.Struct {
  149. continue
  150. }
  151. for i := 0; i < f.Len(); i++ {
  152. fillNil(f.Index(i).Addr().Interface(), skipDeprecated)
  153. }
  154. case reflect.Struct:
  155. if f.CanAddr() {
  156. if addr := f.Addr(); addr.CanInterface() {
  157. fillNil(addr.Interface(), skipDeprecated)
  158. }
  159. }
  160. }
  161. }
  162. }
  163. }
  164. // FillNilSlices sets default value on slices that are still nil.
  165. func FillNilSlices(data interface{}) error {
  166. s := reflect.ValueOf(data).Elem()
  167. t := s.Type()
  168. for i := 0; i < s.NumField(); i++ {
  169. f := s.Field(i)
  170. tag := t.Field(i).Tag
  171. v := tag.Get("default")
  172. if len(v) > 0 {
  173. switch f.Interface().(type) {
  174. case []string:
  175. if f.IsNil() {
  176. // Treat the default as a comma separated slice
  177. vs := strings.Split(v, ",")
  178. for i := range vs {
  179. vs[i] = strings.TrimSpace(vs[i])
  180. }
  181. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  182. for i, v := range vs {
  183. rv.Index(i).SetString(v)
  184. }
  185. f.Set(rv)
  186. }
  187. }
  188. }
  189. }
  190. return nil
  191. }
  192. // Address constructs a URL from the given network and hostname.
  193. func Address(network, host string) string {
  194. u := url.URL{
  195. Scheme: network,
  196. Host: host,
  197. }
  198. return u.String()
  199. }
  200. // AddressUnspecifiedLess is a comparator function preferring least specific network address (most widely listening,
  201. // namely preferring 0.0.0.0 over some IP), if both IPs are equal, it prefers the less restrictive network (prefers tcp
  202. // over tcp4)
  203. func AddressUnspecifiedLess(a, b net.Addr) bool {
  204. aIsUnspecified := false
  205. bIsUnspecified := false
  206. if host, _, err := net.SplitHostPort(a.String()); err == nil {
  207. aIsUnspecified = host == "" || net.ParseIP(host).IsUnspecified()
  208. }
  209. if host, _, err := net.SplitHostPort(b.String()); err == nil {
  210. bIsUnspecified = host == "" || net.ParseIP(host).IsUnspecified()
  211. }
  212. if aIsUnspecified == bIsUnspecified {
  213. return len(a.Network()) < len(b.Network())
  214. }
  215. return aIsUnspecified
  216. }
  217. type FatalErr struct {
  218. Err error
  219. Status ExitStatus
  220. }
  221. func (e *FatalErr) Error() string {
  222. return e.Err.Error()
  223. }
  224. func (e *FatalErr) Unwrap() error {
  225. return e.Err
  226. }
  227. func (e *FatalErr) Is(target error) bool {
  228. return target == suture.ErrTerminateSupervisorTree
  229. }
  230. // NoRestartErr wraps the given error err (which may be nil) to make sure that
  231. // `errors.Is(err, suture.ErrDoNotRestart) == true`.
  232. func NoRestartErr(err error) error {
  233. if err == nil {
  234. return suture.ErrDoNotRestart
  235. }
  236. return &noRestartErr{err}
  237. }
  238. type noRestartErr struct {
  239. err error
  240. }
  241. func (e *noRestartErr) Error() string {
  242. return e.err.Error()
  243. }
  244. func (e *noRestartErr) Unwrap() error {
  245. return e.err
  246. }
  247. func (e *noRestartErr) Is(target error) bool {
  248. return target == suture.ErrDoNotRestart
  249. }
  250. type ExitStatus int
  251. const (
  252. ExitSuccess ExitStatus = 0
  253. ExitError ExitStatus = 1
  254. ExitNoUpgradeAvailable ExitStatus = 2
  255. ExitRestart ExitStatus = 3
  256. ExitUpgrade ExitStatus = 4
  257. )
  258. func (s ExitStatus) AsInt() int {
  259. return int(s)
  260. }
  261. // OnDone calls fn when ctx is cancelled.
  262. func OnDone(ctx context.Context, fn func()) {
  263. go func() {
  264. <-ctx.Done()
  265. fn()
  266. }()
  267. }
  268. func CallWithContext(ctx context.Context, fn func() error) error {
  269. var err error
  270. done := make(chan struct{})
  271. go func() {
  272. err = fn()
  273. close(done)
  274. }()
  275. select {
  276. case <-done:
  277. return err
  278. case <-ctx.Done():
  279. return ctx.Err()
  280. }
  281. }
  282. func NiceDurationString(d time.Duration) string {
  283. switch {
  284. case d > 24*time.Hour:
  285. d = d.Round(time.Hour)
  286. case d > time.Hour:
  287. d = d.Round(time.Minute)
  288. case d > time.Minute:
  289. d = d.Round(time.Second)
  290. case d > time.Second:
  291. d = d.Round(time.Millisecond)
  292. case d > time.Millisecond:
  293. d = d.Round(time.Microsecond)
  294. }
  295. return d.String()
  296. }