util.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 redirect(node string, etcd bool, w http.ResponseWriter, req *http.Request) {
  58. var url string
  59. path := req.URL.Path
  60. if etcd {
  61. etcdAddr, _ := nameToEtcdURL(node)
  62. url = etcdAddr + path
  63. } else {
  64. raftAddr, _ := nameToRaftURL(node)
  65. url = raftAddr + path
  66. }
  67. debugf("Redirect to %s", url)
  68. http.Redirect(w, req, url, http.StatusTemporaryRedirect)
  69. }
  70. func decodeJsonRequest(req *http.Request, data interface{}) error {
  71. decoder := json.NewDecoder(req.Body)
  72. if err := decoder.Decode(&data); err != nil && err != io.EOF {
  73. warnf("Malformed json request: %v", err)
  74. return fmt.Errorf("Malformed json request: %v", err)
  75. }
  76. return nil
  77. }
  78. func encodeJsonResponse(w http.ResponseWriter, status int, data interface{}) {
  79. w.Header().Set("Content-Type", "application/json")
  80. w.WriteHeader(status)
  81. if data != nil {
  82. encoder := json.NewEncoder(w)
  83. encoder.Encode(data)
  84. }
  85. }
  86. // sanitizeURL will cleanup a host string in the format hostname:port and
  87. // attach a schema.
  88. func sanitizeURL(host string, defaultScheme string) string {
  89. // Blank URLs are fine input, just return it
  90. if len(host) == 0 {
  91. return host
  92. }
  93. p, err := url.Parse(host)
  94. if err != nil {
  95. fatal(err)
  96. }
  97. // Make sure the host is in Host:Port format
  98. _, _, err = net.SplitHostPort(host)
  99. if err != nil {
  100. fatal(err)
  101. }
  102. p = &url.URL{Host: host, Scheme: defaultScheme}
  103. return p.String()
  104. }
  105. // sanitizeListenHost cleans up the ListenHost parameter and appends a port
  106. // if necessary based on the advertised port.
  107. func sanitizeListenHost(listen string, advertised string) string {
  108. aurl, err := url.Parse(advertised)
  109. if err != nil {
  110. fatal(err)
  111. }
  112. ahost, aport, err := net.SplitHostPort(aurl.Host)
  113. if err != nil {
  114. fatal(err)
  115. }
  116. // If the listen host isn't set use the advertised host
  117. if listen == "" {
  118. listen = ahost
  119. }
  120. return net.JoinHostPort(listen, aport)
  121. }
  122. func check(err error) {
  123. if err != nil {
  124. fatal(err)
  125. }
  126. }
  127. //--------------------------------------
  128. // Log
  129. //--------------------------------------
  130. var logger *log.Logger
  131. func init() {
  132. logger = log.New(os.Stdout, "[etcd] ", log.Lmicroseconds)
  133. }
  134. func infof(msg string, v ...interface{}) {
  135. logger.Printf("INFO "+msg+"\n", v...)
  136. }
  137. func debugf(msg string, v ...interface{}) {
  138. if verbose {
  139. logger.Printf("DEBUG "+msg+"\n", v...)
  140. }
  141. }
  142. func debug(v ...interface{}) {
  143. if verbose {
  144. logger.Println("DEBUG " + fmt.Sprint(v...))
  145. }
  146. }
  147. func warnf(msg string, v ...interface{}) {
  148. logger.Printf("WARN "+msg+"\n", v...)
  149. }
  150. func warn(v ...interface{}) {
  151. logger.Println("WARN " + fmt.Sprint(v...))
  152. }
  153. func fatalf(msg string, v ...interface{}) {
  154. logger.Printf("FATAL "+msg+"\n", v...)
  155. os.Exit(1)
  156. }
  157. func fatal(v ...interface{}) {
  158. logger.Println("FATAL " + fmt.Sprint(v...))
  159. os.Exit(1)
  160. }
  161. //--------------------------------------
  162. // CPU profile
  163. //--------------------------------------
  164. func runCPUProfile() {
  165. f, err := os.Create(cpuprofile)
  166. if err != nil {
  167. fatal(err)
  168. }
  169. pprof.StartCPUProfile(f)
  170. c := make(chan os.Signal, 1)
  171. signal.Notify(c, os.Interrupt)
  172. go func() {
  173. for sig := range c {
  174. infof("captured %v, stopping profiler and exiting..", sig)
  175. pprof.StopCPUProfile()
  176. os.Exit(1)
  177. }
  178. }()
  179. }
  180. //--------------------------------------
  181. // Testing
  182. //--------------------------------------
  183. func directSet() {
  184. c := make(chan bool, 1000)
  185. for i := 0; i < 1000; i++ {
  186. go send(c)
  187. }
  188. for i := 0; i < 1000; i++ {
  189. <-c
  190. }
  191. }
  192. func send(c chan bool) {
  193. for i := 0; i < 10; i++ {
  194. command := &SetCommand{}
  195. command.Key = "foo"
  196. command.Value = "bar"
  197. command.ExpireTime = time.Unix(0, 0)
  198. r.Do(command)
  199. }
  200. c <- true
  201. }