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.

377 lines
9.9 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. go writeStats.checkProgress("Writing Benchmark", finishChan)
  82. for i := 0; i < *b.numberOfFiles; i++ {
  83. idChan <- i
  84. }
  85. close(idChan)
  86. wait.Wait()
  87. writeStats.end = time.Now()
  88. wait.Add(1)
  89. finishChan <- true
  90. finishChan <- true
  91. wait.Wait()
  92. writeStats.printStats()
  93. }
  94. if *b.read {
  95. readStats = newStats()
  96. wait.Add(*b.concurrency)
  97. go readFileIds(*b.idListFile, fileIdLineChan)
  98. readStats.start = time.Now()
  99. go readStats.checkProgress("Randomly Reading Benchmark", finishChan)
  100. for i := 0; i < *b.concurrency; i++ {
  101. go readFiles(fileIdLineChan, readStats)
  102. }
  103. wait.Wait()
  104. finishChan <- true
  105. readStats.end = time.Now()
  106. readStats.printStats()
  107. }
  108. return true
  109. }
  110. func writeFiles(idChan chan int, fileIdLineChan chan string, s *stats) {
  111. for {
  112. if id, ok := <-idChan; ok {
  113. start := time.Now()
  114. fp := &operation.FilePart{Reader: &FakeReader{id: uint64(id), size: int64(*b.fileSize)}, FileSize: int64(*b.fileSize)}
  115. if assignResult, err := operation.Assign(*b.server, 1, "", *b.collection); err == nil {
  116. fp.Server, fp.Fid, fp.Collection = assignResult.PublicUrl, assignResult.Fid, *b.collection
  117. fp.Upload(0, *b.server)
  118. writeStats.addSample(time.Now().Sub(start))
  119. fileIdLineChan <- fp.Fid
  120. s.transferred += int64(*b.fileSize)
  121. s.completed++
  122. if *cmdBenchmark.IsDebug {
  123. fmt.Printf("writing %d file %s\n", id, fp.Fid)
  124. }
  125. } else {
  126. s.failed++
  127. println("writing file error:", err.Error())
  128. }
  129. } else {
  130. break
  131. }
  132. }
  133. wait.Done()
  134. }
  135. func readFiles(fileIdLineChan chan string, s *stats) {
  136. for {
  137. if fid, ok := <-fileIdLineChan; ok {
  138. if len(fid) == 0 {
  139. continue
  140. }
  141. if fid[0] == '#' {
  142. continue
  143. }
  144. if *cmdBenchmark.IsDebug {
  145. fmt.Printf("reading file %s\n", fid)
  146. }
  147. parts := strings.SplitN(fid, ",", 2)
  148. vid := parts[0]
  149. start := time.Now()
  150. if server, ok := b.vid2server[vid]; !ok {
  151. if ret, err := operation.Lookup(*b.server, vid); err == nil {
  152. if len(ret.Locations) > 0 {
  153. server = ret.Locations[0].PublicUrl
  154. b.vid2server[vid] = server
  155. }
  156. }
  157. }
  158. if server, ok := b.vid2server[vid]; ok {
  159. url := "http://" + server + "/" + fid
  160. if bytesRead, err := util.Get(url); err == nil {
  161. s.completed++
  162. s.transferred += int64(len(bytesRead))
  163. readStats.addSample(time.Now().Sub(start))
  164. } else {
  165. s.failed++
  166. println("!!!! Failed to read from ", url, " !!!!!")
  167. }
  168. } else {
  169. s.failed++
  170. println("!!!! volume id ", vid, " location not found!!!!!")
  171. }
  172. } else {
  173. break
  174. }
  175. }
  176. wait.Done()
  177. }
  178. func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
  179. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  180. if err != nil {
  181. glog.Fatalf("File to create file %s: %s\n", fileName, err)
  182. }
  183. defer file.Close()
  184. for {
  185. select {
  186. case <-finishChan:
  187. wait.Done()
  188. return
  189. case line := <-fileIdLineChan:
  190. file.Write([]byte(line))
  191. file.Write([]byte("\n"))
  192. }
  193. }
  194. }
  195. func readFileIds(fileName string, fileIdLineChan chan string) {
  196. file, err := os.Open(fileName) // For read access.
  197. if err != nil {
  198. glog.Fatalf("File to read file %s: %s\n", fileName, err)
  199. }
  200. defer file.Close()
  201. r := bufio.NewReader(file)
  202. if *b.sequentialRead {
  203. for {
  204. if line, err := Readln(r); err == nil {
  205. fileIdLineChan <- string(line)
  206. } else {
  207. break
  208. }
  209. }
  210. } else {
  211. lines := make([]string, 0, *b.numberOfFiles)
  212. for {
  213. if line, err := Readln(r); err == nil {
  214. lines = append(lines, string(line))
  215. } else {
  216. break
  217. }
  218. }
  219. for i := 0; i < *b.numberOfFiles; i++ {
  220. fileIdLineChan <- lines[rand.Intn(len(lines))]
  221. }
  222. }
  223. close(fileIdLineChan)
  224. }
  225. const (
  226. benchResolution = 10000 //0.1 microsecond
  227. benchBucket = 1000000000 / benchResolution
  228. )
  229. type stats struct {
  230. data []int
  231. completed int
  232. failed int
  233. transferred int64
  234. start time.Time
  235. end time.Time
  236. }
  237. var percentages = []int{50, 66, 75, 80, 90, 95, 98, 99, 100}
  238. func newStats() *stats {
  239. return &stats{data: make([]int, benchResolution)}
  240. }
  241. func (s *stats) addSample(d time.Duration) {
  242. s.data[int(d/benchBucket)]++
  243. }
  244. func (s *stats) checkProgress(testName string, finishChan chan bool) {
  245. fmt.Printf("\n------------ %s ----------\n", testName)
  246. ticker := time.Tick(time.Second)
  247. for {
  248. select {
  249. case <-finishChan:
  250. break
  251. case <-ticker:
  252. fmt.Printf("Completed %d of %d requests, %3d%%\n", s.completed, *b.numberOfFiles, s.completed*100 / *b.numberOfFiles)
  253. }
  254. }
  255. }
  256. func (s *stats) printStats() {
  257. timeTaken := float64(int64(s.end.Sub(s.start))) / 1000000000
  258. fmt.Printf("\nConcurrency Level: %d\n", *b.concurrency)
  259. fmt.Printf("Time taken for tests: %.3f seconds\n", timeTaken)
  260. fmt.Printf("Complete requests: %d\n", s.completed)
  261. fmt.Printf("Failed requests: %d\n", s.failed)
  262. fmt.Printf("Total transferred: %d bytes\n", s.transferred)
  263. fmt.Printf("Requests per second: %.2f [#/sec]\n", float64(s.completed)/timeTaken)
  264. fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", float64(s.transferred)/1024/timeTaken)
  265. n, sum := 0, 0
  266. min, max := 10000000, 0
  267. for i := 0; i < len(s.data); i++ {
  268. n += s.data[i]
  269. sum += s.data[i] * i
  270. if s.data[i] > 0 {
  271. if min > i {
  272. min = i
  273. }
  274. if max < i {
  275. max = i
  276. }
  277. }
  278. }
  279. avg := float64(sum) / float64(n)
  280. varianceSum := 0.0
  281. for i := 0; i < len(s.data); i++ {
  282. if s.data[i] > 0 {
  283. d := float64(i) - avg
  284. varianceSum += d * d * float64(s.data[i])
  285. }
  286. }
  287. std := math.Sqrt(varianceSum / float64(n))
  288. fmt.Printf("\nConnection Times (ms)\n")
  289. fmt.Printf(" min avg max std\n")
  290. fmt.Printf("Total: %2.1f %3.1f %3.1f %3.1f\n", float32(min)/10, float32(avg)/10, float32(max)/10, std/10)
  291. //printing percentiles
  292. fmt.Printf("\nPercentage of the requests served within a certain time (ms)\n")
  293. percentiles := make([]int, len(percentages))
  294. for i := 0; i < len(percentages); i++ {
  295. percentiles[i] = n * percentages[i] / 100
  296. }
  297. percentiles[len(percentiles)-1] = n
  298. percentileIndex := 0
  299. currentSum := 0
  300. for i := 0; i < len(s.data); i++ {
  301. currentSum += s.data[i]
  302. if s.data[i] > 0 && percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  303. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(i)/10.0)
  304. percentileIndex++
  305. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  306. percentileIndex++
  307. }
  308. }
  309. }
  310. }
  311. // a fake reader to generate content to upload
  312. type FakeReader struct {
  313. id uint64 // an id number
  314. size int64 // max bytes
  315. }
  316. func (l *FakeReader) Read(p []byte) (n int, err error) {
  317. if l.size <= 0 {
  318. return 0, io.EOF
  319. }
  320. if int64(len(p)) > l.size {
  321. n = int(l.size)
  322. } else {
  323. n = len(p)
  324. }
  325. for i := 0; i < n-8; i += 8 {
  326. for s := uint(0); s < 8; s++ {
  327. p[i] = byte(l.id >> (s * 8))
  328. }
  329. }
  330. l.size -= int64(n)
  331. return
  332. }
  333. func Readln(r *bufio.Reader) ([]byte, error) {
  334. var (
  335. isPrefix bool = true
  336. err error = nil
  337. line, ln []byte
  338. )
  339. for isPrefix && err == nil {
  340. line, isPrefix, err = r.ReadLine()
  341. ln = append(ln, line...)
  342. }
  343. return ln, err
  344. }