util.go 4.4 KB

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