util.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "os/signal"
  11. "runtime/pprof"
  12. "strconv"
  13. "time"
  14. "github.com/coreos/etcd/web"
  15. "github.com/coreos/go-log/log"
  16. )
  17. //--------------------------------------
  18. // etcd http Helper
  19. //--------------------------------------
  20. // Convert string duration to time format
  21. func durationToExpireTime(strDuration string) (time.Time, error) {
  22. if strDuration != "" {
  23. duration, err := strconv.Atoi(strDuration)
  24. if err != nil {
  25. return time.Unix(0, 0), err
  26. }
  27. return time.Now().Add(time.Second * (time.Duration)(duration)), nil
  28. } else {
  29. return time.Unix(0, 0), nil
  30. }
  31. }
  32. //--------------------------------------
  33. // Web Helper
  34. //--------------------------------------
  35. var storeMsg chan string
  36. // Help to send msg from store to webHub
  37. func webHelper() {
  38. storeMsg = make(chan string)
  39. etcdStore.SetMessager(storeMsg)
  40. for {
  41. // transfer the new msg to webHub
  42. web.Hub().Send(<-storeMsg)
  43. }
  44. }
  45. // startWebInterface starts web interface if webURL is not empty
  46. func startWebInterface() {
  47. if argInfo.WebURL != "" {
  48. // start web
  49. go webHelper()
  50. go web.Start(r.Server, argInfo.WebURL)
  51. }
  52. }
  53. //--------------------------------------
  54. // HTTP Utilities
  55. //--------------------------------------
  56. func decodeJsonRequest(req *http.Request, data interface{}) error {
  57. decoder := json.NewDecoder(req.Body)
  58. if err := decoder.Decode(&data); err != nil && err != io.EOF {
  59. warnf("Malformed json request: %v", err)
  60. return fmt.Errorf("Malformed json request: %v", err)
  61. }
  62. return nil
  63. }
  64. func encodeJsonResponse(w http.ResponseWriter, status int, data interface{}) {
  65. w.Header().Set("Content-Type", "application/json")
  66. w.WriteHeader(status)
  67. if data != nil {
  68. encoder := json.NewEncoder(w)
  69. encoder.Encode(data)
  70. }
  71. }
  72. // sanitizeURL will cleanup a host string in the format hostname:port and
  73. // attach a schema.
  74. func sanitizeURL(host string, defaultScheme string) string {
  75. // Blank URLs are fine input, just return it
  76. if len(host) == 0 {
  77. return host
  78. }
  79. p, err := url.Parse(host)
  80. if err != nil {
  81. fatal(err)
  82. }
  83. // Make sure the host is in Host:Port format
  84. _, _, err = net.SplitHostPort(host)
  85. if err != nil {
  86. fatal(err)
  87. }
  88. p = &url.URL{Host: host, Scheme: defaultScheme}
  89. return p.String()
  90. }
  91. // sanitizeListenHost cleans up the ListenHost parameter and appends a port
  92. // if necessary based on the advertised port.
  93. func sanitizeListenHost(listen string, advertised string) string {
  94. aurl, err := url.Parse(advertised)
  95. if err != nil {
  96. fatal(err)
  97. }
  98. ahost, aport, err := net.SplitHostPort(aurl.Host)
  99. if err != nil {
  100. fatal(err)
  101. }
  102. // If the listen host isn't set use the advertised host
  103. if listen == "" {
  104. listen = ahost
  105. }
  106. return net.JoinHostPort(listen, aport)
  107. }
  108. func check(err error) {
  109. if err != nil {
  110. fatal(err)
  111. }
  112. }
  113. //--------------------------------------
  114. // Log
  115. //--------------------------------------
  116. var logger *log.Logger = log.New("etcd", false,
  117. log.CombinedSink(os.Stdout, "[%s] %s %-9s | %s\n", []string{"prefix", "time", "priority", "message"}))
  118. func infof(format string, v ...interface{}) {
  119. logger.Infof(format, v...)
  120. }
  121. func debugf(format string, v ...interface{}) {
  122. if verbose {
  123. logger.Debugf(format, v...)
  124. }
  125. }
  126. func debug(v ...interface{}) {
  127. if verbose {
  128. logger.Debug(v...)
  129. }
  130. }
  131. func warnf(format string, v ...interface{}) {
  132. logger.Warningf(format, v...)
  133. }
  134. func warn(v ...interface{}) {
  135. logger.Warning(v...)
  136. }
  137. func fatalf(format string, v ...interface{}) {
  138. logger.Fatalf(format, v...)
  139. }
  140. func fatal(v ...interface{}) {
  141. logger.Fatalln(v...)
  142. }
  143. //--------------------------------------
  144. // CPU profile
  145. //--------------------------------------
  146. func runCPUProfile() {
  147. f, err := os.Create(cpuprofile)
  148. if err != nil {
  149. fatal(err)
  150. }
  151. pprof.StartCPUProfile(f)
  152. c := make(chan os.Signal, 1)
  153. signal.Notify(c, os.Interrupt)
  154. go func() {
  155. for sig := range c {
  156. infof("captured %v, stopping profiler and exiting..", sig)
  157. pprof.StopCPUProfile()
  158. os.Exit(1)
  159. }
  160. }()
  161. }
  162. //--------------------------------------
  163. // Testing
  164. //--------------------------------------
  165. func directSet() {
  166. c := make(chan bool, 1000)
  167. for i := 0; i < 1000; i++ {
  168. go send(c)
  169. }
  170. for i := 0; i < 1000; i++ {
  171. <-c
  172. }
  173. }
  174. func send(c chan bool) {
  175. for i := 0; i < 10; i++ {
  176. command := &SetCommand{}
  177. command.Key = "foo"
  178. command.Value = "bar"
  179. command.ExpireTime = time.Unix(0, 0)
  180. r.Do(command)
  181. }
  182. c <- true
  183. }