util.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "os/signal"
  12. "runtime/pprof"
  13. "strconv"
  14. "time"
  15. "github.com/coreos/etcd/web"
  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
  117. func init() {
  118. logger = log.New(os.Stdout, "[etcd] ", log.Lmicroseconds)
  119. }
  120. func infof(msg string, v ...interface{}) {
  121. logger.Printf("INFO "+msg+"\n", v...)
  122. }
  123. func debugf(msg string, v ...interface{}) {
  124. if verbose {
  125. logger.Printf("DEBUG "+msg+"\n", v...)
  126. }
  127. }
  128. func debug(v ...interface{}) {
  129. if verbose {
  130. logger.Println("DEBUG " + fmt.Sprint(v...))
  131. }
  132. }
  133. func warnf(msg string, v ...interface{}) {
  134. logger.Printf("WARN "+msg+"\n", v...)
  135. }
  136. func warn(v ...interface{}) {
  137. logger.Println("WARN " + fmt.Sprint(v...))
  138. }
  139. func fatalf(msg string, v ...interface{}) {
  140. logger.Printf("FATAL "+msg+"\n", v...)
  141. os.Exit(1)
  142. }
  143. func fatal(v ...interface{}) {
  144. logger.Println("FATAL " + fmt.Sprint(v...))
  145. os.Exit(1)
  146. }
  147. //--------------------------------------
  148. // CPU profile
  149. //--------------------------------------
  150. func runCPUProfile() {
  151. f, err := os.Create(cpuprofile)
  152. if err != nil {
  153. fatal(err)
  154. }
  155. pprof.StartCPUProfile(f)
  156. c := make(chan os.Signal, 1)
  157. signal.Notify(c, os.Interrupt)
  158. go func() {
  159. for sig := range c {
  160. infof("captured %v, stopping profiler and exiting..", sig)
  161. pprof.StopCPUProfile()
  162. os.Exit(1)
  163. }
  164. }()
  165. }
  166. //--------------------------------------
  167. // Testing
  168. //--------------------------------------
  169. func directSet() {
  170. c := make(chan bool, 1000)
  171. for i := 0; i < 1000; i++ {
  172. go send(c)
  173. }
  174. for i := 0; i < 1000; i++ {
  175. <-c
  176. }
  177. }
  178. func send(c chan bool) {
  179. for i := 0; i < 10; i++ {
  180. command := &SetCommand{}
  181. command.Key = "foo"
  182. command.Value = "bar"
  183. command.ExpireTime = time.Unix(0, 0)
  184. r.Do(command)
  185. }
  186. c <- true
  187. }