util.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package main
  2. import (
  3. "net"
  4. "net/url"
  5. "os"
  6. "os/signal"
  7. "runtime/pprof"
  8. "github.com/coreos/etcd/log"
  9. )
  10. //--------------------------------------
  11. // HTTP Utilities
  12. //--------------------------------------
  13. // sanitizeURL will cleanup a host string in the format hostname:port and
  14. // attach a schema.
  15. func sanitizeURL(host string, defaultScheme string) string {
  16. // Blank URLs are fine input, just return it
  17. if len(host) == 0 {
  18. return host
  19. }
  20. p, err := url.Parse(host)
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. // Make sure the host is in Host:Port format
  25. _, _, err = net.SplitHostPort(host)
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. p = &url.URL{Host: host, Scheme: defaultScheme}
  30. return p.String()
  31. }
  32. // sanitizeListenHost cleans up the ListenHost parameter and appends a port
  33. // if necessary based on the advertised port.
  34. func sanitizeListenHost(listen string, advertised string) string {
  35. aurl, err := url.Parse(advertised)
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. ahost, aport, err := net.SplitHostPort(aurl.Host)
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. // If the listen host isn't set use the advertised host
  44. if listen == "" {
  45. listen = ahost
  46. }
  47. return net.JoinHostPort(listen, aport)
  48. }
  49. func check(err error) {
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. }
  54. //--------------------------------------
  55. // CPU profile
  56. //--------------------------------------
  57. func runCPUProfile() {
  58. f, err := os.Create(cpuprofile)
  59. if err != nil {
  60. log.Fatal(err)
  61. }
  62. pprof.StartCPUProfile(f)
  63. c := make(chan os.Signal, 1)
  64. signal.Notify(c, os.Interrupt)
  65. go func() {
  66. for sig := range c {
  67. log.Infof("captured %v, stopping profiler and exiting..", sig)
  68. pprof.StopCPUProfile()
  69. os.Exit(1)
  70. }
  71. }()
  72. }