You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

341 lines
8.8 KiB

  1. package main
  2. import (
  3. "bufio"
  4. "code.google.com/p/weed-fs/go/glog"
  5. "code.google.com/p/weed-fs/go/operation"
  6. "code.google.com/p/weed-fs/go/util"
  7. "fmt"
  8. "io"
  9. "math"
  10. "os"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. type BenchmarkOptions struct {
  16. server *string
  17. concurrency *int
  18. numberOfFiles *int
  19. fileSize *int
  20. idListFile *string
  21. write *bool
  22. read *bool
  23. vid2server map[string]string //cache for vid locations
  24. }
  25. var (
  26. b BenchmarkOptions
  27. )
  28. func init() {
  29. cmdBenchmark.Run = runbenchmark // break init cycle
  30. cmdBenchmark.IsDebug = cmdBenchmark.Flag.Bool("debug", false, "verbose debug information")
  31. b.server = cmdBenchmark.Flag.String("server", "localhost:9333", "weedfs master location")
  32. b.concurrency = cmdBenchmark.Flag.Int("c", 7, "number of concurrent write or read processes")
  33. b.fileSize = cmdBenchmark.Flag.Int("size", 1024, "simulated file size in bytes")
  34. b.numberOfFiles = cmdBenchmark.Flag.Int("n", 1024*1024, "number of files to write for each thread")
  35. b.idListFile = cmdBenchmark.Flag.String("list", os.TempDir()+"/benchmark_list.txt", "list of uploaded file ids")
  36. b.write = cmdBenchmark.Flag.Bool("write", true, "enable write")
  37. b.read = cmdBenchmark.Flag.Bool("read", true, "enable read")
  38. }
  39. var cmdBenchmark = &Command{
  40. UsageLine: "benchmark -server=localhost:9333 -c=10 -n=100000",
  41. Short: "benchmark on writing millions of files and read out",
  42. Long: `benchmark on an empty weed file system.
  43. Two tests during benchmark:
  44. 1) write lots of small files to the system
  45. 2) read the files out
  46. The file content is mostly zero, but no compression is done.
  47. By default, write 1 million files of 1KB each with 7 concurrent threads,
  48. and randomly read them out with 7 concurrent threads.
  49. You can choose to only benchmark read or write.
  50. During write, the list of uploaded file ids is stored in "-list" specified file.
  51. You can also use your own list of file ids to run read test.
  52. Write speed and read speed will be collected.
  53. The numbers are used to get a sense of the system.
  54. But usually your network or the hard drive is
  55. the real bottleneck.
  56. `,
  57. }
  58. var (
  59. wait sync.WaitGroup
  60. writeStats *stats
  61. readStats *stats
  62. )
  63. func runbenchmark(cmd *Command, args []string) bool {
  64. finishChan := make(chan bool)
  65. fileIdLineChan := make(chan string)
  66. b.vid2server = make(map[string]string)
  67. if *b.write {
  68. writeStats = newStats()
  69. idChan := make(chan int)
  70. wait.Add(*b.concurrency)
  71. go writeFileIds(*b.idListFile, fileIdLineChan, finishChan)
  72. for i := 0; i < *b.concurrency; i++ {
  73. go writeFiles(idChan, fileIdLineChan, writeStats)
  74. }
  75. writeStats.start = time.Now()
  76. for i := 0; i < *b.numberOfFiles; i++ {
  77. idChan <- i
  78. }
  79. close(idChan)
  80. wait.Wait()
  81. writeStats.end = time.Now()
  82. wait.Add(1)
  83. finishChan <- true
  84. wait.Wait()
  85. writeStats.printStats("Writing Benchmark")
  86. }
  87. if *b.read {
  88. readStats = newStats()
  89. wait.Add(*b.concurrency)
  90. go readFileIds(*b.idListFile, fileIdLineChan)
  91. readStats.start = time.Now()
  92. for i := 0; i < *b.concurrency; i++ {
  93. go readFiles(fileIdLineChan, readStats)
  94. }
  95. wait.Wait()
  96. readStats.end = time.Now()
  97. readStats.printStats("Randomly Reading Benchmark")
  98. }
  99. return true
  100. }
  101. func writeFiles(idChan chan int, fileIdLineChan chan string, s *stats) {
  102. for {
  103. if id, ok := <-idChan; ok {
  104. start := time.Now()
  105. fp := &operation.FilePart{Reader: &FakeReader{id: uint64(id), size: int64(*b.fileSize)}, FileSize: int64(*b.fileSize)}
  106. if assignResult, err := operation.Assign(*b.server, 1, ""); err == nil {
  107. fp.Server, fp.Fid = assignResult.PublicUrl, assignResult.Fid
  108. fp.Upload(0, *b.server, "")
  109. writeStats.addSample(time.Now().Sub(start))
  110. fileIdLineChan <- fp.Fid
  111. s.transferred += int64(*b.fileSize)
  112. s.completed++
  113. if *cmdBenchmark.IsDebug {
  114. fmt.Printf("writing %d file %s\n", id, fp.Fid)
  115. }
  116. } else {
  117. s.failed++
  118. println("writing file error:", err.Error())
  119. }
  120. } else {
  121. break
  122. }
  123. }
  124. wait.Done()
  125. }
  126. func readFiles(fileIdLineChan chan string, s *stats) {
  127. for {
  128. if fid, ok := <-fileIdLineChan; ok {
  129. if len(fid) == 0 {
  130. continue
  131. }
  132. if fid[0] == '#' {
  133. continue
  134. }
  135. if *cmdBenchmark.IsDebug {
  136. fmt.Printf("reading file %s\n", fid)
  137. }
  138. parts := strings.SplitN(fid, ",", 2)
  139. vid := parts[0]
  140. start := time.Now()
  141. if server, ok := b.vid2server[vid]; !ok {
  142. if ret, err := operation.Lookup(*b.server, vid); err == nil {
  143. if len(ret.Locations) > 0 {
  144. server = ret.Locations[0].PublicUrl
  145. b.vid2server[vid] = server
  146. }
  147. }
  148. }
  149. if server, ok := b.vid2server[vid]; ok {
  150. url := "http://" + server + "/" + fid
  151. if bytesRead, err := util.Get(url); err == nil {
  152. s.completed++
  153. s.transferred += int64(len(bytesRead))
  154. readStats.addSample(time.Now().Sub(start))
  155. } else {
  156. s.failed++
  157. println("!!!! Failed to read from ", url, " !!!!!")
  158. }
  159. } else {
  160. s.failed++
  161. println("!!!! volume id ", vid, " location not found!!!!!")
  162. }
  163. } else {
  164. break
  165. }
  166. }
  167. wait.Done()
  168. }
  169. func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
  170. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  171. if err != nil {
  172. glog.Fatalf("File to create file %s: %s\n", fileName, err)
  173. }
  174. defer file.Close()
  175. for {
  176. select {
  177. case <-finishChan:
  178. wait.Done()
  179. return
  180. case line := <-fileIdLineChan:
  181. file.Write([]byte(line))
  182. file.Write([]byte("\n"))
  183. }
  184. }
  185. }
  186. func readFileIds(fileName string, fileIdLineChan chan string) {
  187. file, err := os.Open(fileName) // For read access.
  188. if err != nil {
  189. glog.Fatalf("File to read file %s: %s\n", fileName, err)
  190. }
  191. defer file.Close()
  192. r := bufio.NewReader(file)
  193. for {
  194. if line, err := Readln(r); err == nil {
  195. fileIdLineChan <- string(line)
  196. } else {
  197. break
  198. }
  199. }
  200. close(fileIdLineChan)
  201. }
  202. const (
  203. benchResolution = 10000 //0.1 microsecond
  204. benchBucket = 1000000000 / benchResolution
  205. )
  206. type stats struct {
  207. data []int
  208. completed int
  209. failed int
  210. transferred int64
  211. start time.Time
  212. end time.Time
  213. }
  214. var percentages = []int{50, 66, 75, 80, 90, 95, 98, 99, 100}
  215. func newStats() *stats {
  216. return &stats{data: make([]int, benchResolution)}
  217. }
  218. func (s stats) addSample(d time.Duration) {
  219. s.data[int(d/benchBucket)]++
  220. }
  221. func (s stats) printStats(testName string) {
  222. fmt.Printf("\n------------ %s ----------\n", testName)
  223. timeTaken := float64(int64(s.end.Sub(s.start))) / 1000000000
  224. fmt.Printf("Concurrency Level: %d\n", *b.concurrency)
  225. fmt.Printf("Time taken for tests: %.3f seconds\n", timeTaken)
  226. fmt.Printf("Complete requests: %d\n", s.completed)
  227. fmt.Printf("Failed requests: %d\n", s.failed)
  228. fmt.Printf("Total transferred: %d bytes\n", s.transferred)
  229. fmt.Printf("Requests per second: %.2f [#/sec]\n", float64(s.completed)/timeTaken)
  230. fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", float64(s.transferred)/1024/timeTaken)
  231. n, sum := 0, 0
  232. min, max := 10000000, 0
  233. for i := 0; i < len(s.data); i++ {
  234. n += s.data[i]
  235. sum += s.data[i] * i
  236. if s.data[i] > 0 {
  237. if min > i {
  238. min = i
  239. }
  240. if max < i {
  241. max = i
  242. }
  243. }
  244. }
  245. avg := float64(sum) / float64(n)
  246. varianceSum := 0.0
  247. for i := 0; i < len(s.data); i++ {
  248. if s.data[i] > 0 {
  249. d := float64(i) - avg
  250. varianceSum += d * d * float64(s.data[i])
  251. }
  252. }
  253. std := math.Sqrt(varianceSum / float64(n))
  254. fmt.Printf("\nConnection Times (ms)\n")
  255. fmt.Printf(" min avg max std\n")
  256. fmt.Printf("Total: %2.1f %3.1f %3.1f %3.1f\n", float32(min)/10, float32(avg)/10, float32(max)/10, std/10)
  257. //printing percentiles
  258. fmt.Printf("\nPercentage of the requests served within a certain time (ms)\n")
  259. percentiles := make([]int, len(percentages))
  260. for i := 0; i < len(percentages); i++ {
  261. percentiles[i] = n * percentages[i] / 100
  262. }
  263. percentiles[len(percentiles)-1] = n
  264. percentileIndex := 0
  265. currentSum := 0
  266. for i := 0; i < len(s.data); i++ {
  267. currentSum += s.data[i]
  268. if s.data[i] > 0 && percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  269. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(i)/10.0)
  270. percentileIndex++
  271. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  272. percentileIndex++
  273. }
  274. }
  275. }
  276. }
  277. // a fake reader to generate content to upload
  278. type FakeReader struct {
  279. id uint64 // an id number
  280. size int64 // max bytes
  281. }
  282. func (l *FakeReader) Read(p []byte) (n int, err error) {
  283. if l.size <= 0 {
  284. return 0, io.EOF
  285. }
  286. if int64(len(p)) > l.size {
  287. n = int(l.size)
  288. } else {
  289. n = len(p)
  290. }
  291. for i := 0; i < n-8; i += 8 {
  292. for s := uint(0); s < 8; s++ {
  293. p[i] = byte(l.id >> (s * 8))
  294. }
  295. }
  296. l.size -= int64(n)
  297. return
  298. }
  299. func Readln(r *bufio.Reader) ([]byte, error) {
  300. var (
  301. isPrefix bool = true
  302. err error = nil
  303. line, ln []byte
  304. )
  305. for isPrefix && err == nil {
  306. line, isPrefix, err = r.ReadLine()
  307. ln = append(ln, line...)
  308. }
  309. return ln, err
  310. }