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.

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