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.

458 lines
12 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. "runtime"
  13. "runtime/pprof"
  14. "sort"
  15. "strings"
  16. "sync"
  17. "time"
  18. )
  19. type BenchmarkOptions struct {
  20. server *string
  21. concurrency *int
  22. numberOfFiles *int
  23. fileSize *int
  24. idListFile *string
  25. write *bool
  26. read *bool
  27. sequentialRead *bool
  28. collection *string
  29. cpuprofile *string
  30. vid2server map[string]string //cache for vid locations
  31. }
  32. var (
  33. b BenchmarkOptions
  34. )
  35. func init() {
  36. cmdBenchmark.Run = runbenchmark // break init cycle
  37. cmdBenchmark.IsDebug = cmdBenchmark.Flag.Bool("debug", false, "verbose debug information")
  38. b.server = cmdBenchmark.Flag.String("server", "localhost:9333", "weedfs master location")
  39. b.concurrency = cmdBenchmark.Flag.Int("c", 64, "number of concurrent write or read processes")
  40. b.fileSize = cmdBenchmark.Flag.Int("size", 1024, "simulated file size in bytes")
  41. b.numberOfFiles = cmdBenchmark.Flag.Int("n", 1024*1024, "number of files to write for each thread")
  42. b.idListFile = cmdBenchmark.Flag.String("list", os.TempDir()+"/benchmark_list.txt", "list of uploaded file ids")
  43. b.write = cmdBenchmark.Flag.Bool("write", true, "enable write")
  44. b.read = cmdBenchmark.Flag.Bool("read", true, "enable read")
  45. b.sequentialRead = cmdBenchmark.Flag.Bool("readSequentially", false, "randomly read by ids from \"-list\" specified file")
  46. b.collection = cmdBenchmark.Flag.String("collection", "benchmark", "write data to this collection")
  47. b.cpuprofile = cmdBenchmark.Flag.String("cpuprofile", "", "write cpu profile to file")
  48. b.vid2server = make(map[string]string)
  49. }
  50. var cmdBenchmark = &Command{
  51. UsageLine: "benchmark -server=localhost:9333 -c=10 -n=100000",
  52. Short: "benchmark on writing millions of files and read out",
  53. Long: `benchmark on an empty weed file system.
  54. Two tests during benchmark:
  55. 1) write lots of small files to the system
  56. 2) read the files out
  57. The file content is mostly zero, but no compression is done.
  58. You can choose to only benchmark read or write.
  59. During write, the list of uploaded file ids is stored in "-list" specified file.
  60. You can also use your own list of file ids to run read test.
  61. Write speed and read speed will be collected.
  62. The numbers are used to get a sense of the system.
  63. Usually your network or the hard drive is the real bottleneck.
  64. Another thing to watch is whether the volumes are evenly distributed
  65. to each volume server. Because the 7 more benchmark volumes are randomly distributed
  66. to servers with free slots, it's highly possible some servers have uneven amount of
  67. benchmark volumes. To remedy this, you can use this to grow the benchmark volumes
  68. before starting the benchmark command:
  69. http://localhost:9333/vol/grow?collection=benchmark&count=5
  70. `,
  71. }
  72. var (
  73. wait sync.WaitGroup
  74. writeStats *stats
  75. readStats *stats
  76. )
  77. func runbenchmark(cmd *Command, args []string) bool {
  78. fmt.Printf("This is Weed File System version %s %s %s\n", VERSION, runtime.GOOS, runtime.GOARCH)
  79. if *b.cpuprofile != "" {
  80. f, err := os.Create(*b.cpuprofile)
  81. if err != nil {
  82. glog.Fatal(err)
  83. }
  84. pprof.StartCPUProfile(f)
  85. defer pprof.StopCPUProfile()
  86. }
  87. if *b.write {
  88. bench_write()
  89. }
  90. if *b.read {
  91. bench_read()
  92. }
  93. return true
  94. }
  95. func bench_write() {
  96. fileIdLineChan := make(chan string)
  97. finishChan := make(chan bool)
  98. writeStats = newStats()
  99. idChan := make(chan int)
  100. wait.Add(*b.concurrency)
  101. go writeFileIds(*b.idListFile, fileIdLineChan, finishChan)
  102. for i := 0; i < *b.concurrency; i++ {
  103. go writeFiles(idChan, fileIdLineChan, writeStats)
  104. }
  105. writeStats.start = time.Now()
  106. go writeStats.checkProgress("Writing Benchmark", finishChan)
  107. for i := 0; i < *b.numberOfFiles; i++ {
  108. idChan <- i
  109. }
  110. close(idChan)
  111. wait.Wait()
  112. writeStats.end = time.Now()
  113. wait.Add(1)
  114. finishChan <- true
  115. finishChan <- true
  116. close(finishChan)
  117. wait.Wait()
  118. writeStats.printStats()
  119. }
  120. func bench_read() {
  121. fileIdLineChan := make(chan string)
  122. finishChan := make(chan bool)
  123. readStats = newStats()
  124. wait.Add(*b.concurrency)
  125. go readFileIds(*b.idListFile, fileIdLineChan)
  126. readStats.start = time.Now()
  127. go readStats.checkProgress("Randomly Reading Benchmark", finishChan)
  128. for i := 0; i < *b.concurrency; i++ {
  129. go readFiles(fileIdLineChan, readStats)
  130. }
  131. wait.Wait()
  132. finishChan <- true
  133. close(finishChan)
  134. readStats.end = time.Now()
  135. readStats.printStats()
  136. }
  137. func writeFiles(idChan chan int, fileIdLineChan chan string, s *stats) {
  138. serverLimitChan := make(map[string]chan bool)
  139. for {
  140. if id, ok := <-idChan; ok {
  141. start := time.Now()
  142. fp := &operation.FilePart{Reader: &FakeReader{id: uint64(id), size: int64(*b.fileSize)}, FileSize: int64(*b.fileSize)}
  143. if assignResult, err := operation.Assign(*b.server, 1, "", *b.collection); err == nil {
  144. fp.Server, fp.Fid, fp.Collection = assignResult.PublicUrl, assignResult.Fid, *b.collection
  145. if _, ok := serverLimitChan[fp.Server]; !ok {
  146. serverLimitChan[fp.Server] = make(chan bool, 7)
  147. }
  148. serverLimitChan[fp.Server] <- true
  149. if _, err := fp.Upload(0, *b.server); err == nil {
  150. fileIdLineChan <- fp.Fid
  151. s.completed++
  152. s.transferred += int64(*b.fileSize)
  153. } else {
  154. s.failed++
  155. }
  156. writeStats.addSample(time.Now().Sub(start))
  157. <-serverLimitChan[fp.Server]
  158. if *cmdBenchmark.IsDebug {
  159. fmt.Printf("writing %d file %s\n", id, fp.Fid)
  160. }
  161. } else {
  162. s.failed++
  163. println("writing file error:", err.Error())
  164. }
  165. } else {
  166. break
  167. }
  168. }
  169. wait.Done()
  170. }
  171. func readFiles(fileIdLineChan chan string, s *stats) {
  172. serverLimitChan := make(map[string]chan bool)
  173. masterLimitChan := make(chan bool, 7)
  174. for {
  175. if fid, ok := <-fileIdLineChan; ok {
  176. if len(fid) == 0 {
  177. continue
  178. }
  179. if fid[0] == '#' {
  180. continue
  181. }
  182. if *cmdBenchmark.IsDebug {
  183. fmt.Printf("reading file %s\n", fid)
  184. }
  185. parts := strings.SplitN(fid, ",", 2)
  186. vid := parts[0]
  187. start := time.Now()
  188. if server, ok := b.vid2server[vid]; !ok {
  189. masterLimitChan <- true
  190. if ret, err := operation.Lookup(*b.server, vid); err == nil {
  191. if len(ret.Locations) > 0 {
  192. server = ret.Locations[0].PublicUrl
  193. b.vid2server[vid] = server
  194. }
  195. }
  196. <-masterLimitChan
  197. }
  198. if server, ok := b.vid2server[vid]; ok {
  199. if _, ok := serverLimitChan[server]; !ok {
  200. serverLimitChan[server] = make(chan bool, 7)
  201. }
  202. serverLimitChan[server] <- true
  203. url := "http://" + server + "/" + fid
  204. if bytesRead, err := util.Get(url); err == nil {
  205. s.completed++
  206. s.transferred += int64(len(bytesRead))
  207. readStats.addSample(time.Now().Sub(start))
  208. } else {
  209. s.failed++
  210. println("!!!! Failed to read from ", url, " !!!!!")
  211. }
  212. <-serverLimitChan[server]
  213. } else {
  214. s.failed++
  215. println("!!!! volume id ", vid, " location not found!!!!!")
  216. }
  217. } else {
  218. break
  219. }
  220. }
  221. wait.Done()
  222. }
  223. func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
  224. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  225. if err != nil {
  226. glog.Fatalf("File to create file %s: %s\n", fileName, err)
  227. }
  228. defer file.Close()
  229. for {
  230. select {
  231. case <-finishChan:
  232. wait.Done()
  233. return
  234. case line := <-fileIdLineChan:
  235. file.Write([]byte(line))
  236. file.Write([]byte("\n"))
  237. }
  238. }
  239. }
  240. func readFileIds(fileName string, fileIdLineChan chan string) {
  241. file, err := os.Open(fileName) // For read access.
  242. if err != nil {
  243. glog.Fatalf("File to read file %s: %s\n", fileName, err)
  244. }
  245. defer file.Close()
  246. r := bufio.NewReader(file)
  247. if *b.sequentialRead {
  248. for {
  249. if line, err := Readln(r); err == nil {
  250. fileIdLineChan <- string(line)
  251. } else {
  252. break
  253. }
  254. }
  255. } else {
  256. lines := make([]string, 0, *b.numberOfFiles)
  257. for {
  258. if line, err := Readln(r); err == nil {
  259. lines = append(lines, string(line))
  260. } else {
  261. break
  262. }
  263. }
  264. for i := 0; i < *b.numberOfFiles; i++ {
  265. fileIdLineChan <- lines[rand.Intn(len(lines))]
  266. }
  267. }
  268. close(fileIdLineChan)
  269. }
  270. const (
  271. benchResolution = 10000 //0.1 microsecond
  272. benchBucket = 1000000000 / benchResolution
  273. )
  274. // An efficient statics collecting and rendering
  275. type stats struct {
  276. data []int
  277. overflow []int
  278. completed int
  279. failed int
  280. transferred int64
  281. start time.Time
  282. end time.Time
  283. }
  284. var percentages = []int{50, 66, 75, 80, 90, 95, 98, 99, 100}
  285. func newStats() *stats {
  286. return &stats{data: make([]int, benchResolution), overflow: make([]int, 0)}
  287. }
  288. func (s *stats) addSample(d time.Duration) {
  289. index := int(d / benchBucket)
  290. if index < 0 {
  291. fmt.Printf("This request takes %3.1f seconds, skipping!\n", float64(index)/10000)
  292. } else if index < len(s.data) {
  293. s.data[int(d/benchBucket)]++
  294. } else {
  295. s.overflow = append(s.overflow, index)
  296. }
  297. }
  298. func (s *stats) checkProgress(testName string, finishChan chan bool) {
  299. fmt.Printf("\n------------ %s ----------\n", testName)
  300. ticker := time.Tick(time.Second)
  301. for {
  302. select {
  303. case <-finishChan:
  304. return
  305. case <-ticker:
  306. fmt.Printf("Completed %d of %d requests, %3.1f%%\n", s.completed, *b.numberOfFiles, float64(s.completed)*100/float64(*b.numberOfFiles))
  307. }
  308. }
  309. }
  310. func (s *stats) printStats() {
  311. timeTaken := float64(int64(s.end.Sub(s.start))) / 1000000000
  312. fmt.Printf("\nConcurrency Level: %d\n", *b.concurrency)
  313. fmt.Printf("Time taken for tests: %.3f seconds\n", timeTaken)
  314. fmt.Printf("Complete requests: %d\n", s.completed)
  315. fmt.Printf("Failed requests: %d\n", s.failed)
  316. fmt.Printf("Total transferred: %d bytes\n", s.transferred)
  317. fmt.Printf("Requests per second: %.2f [#/sec]\n", float64(s.completed)/timeTaken)
  318. fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", float64(s.transferred)/1024/timeTaken)
  319. n, sum := 0, 0
  320. min, max := 10000000, 0
  321. for i := 0; i < len(s.data); i++ {
  322. n += s.data[i]
  323. sum += s.data[i] * i
  324. if s.data[i] > 0 {
  325. if min > i {
  326. min = i
  327. }
  328. if max < i {
  329. max = i
  330. }
  331. }
  332. }
  333. n += len(s.overflow)
  334. for i := 0; i < len(s.overflow); i++ {
  335. sum += s.overflow[i]
  336. if min > s.overflow[i] {
  337. min = s.overflow[i]
  338. }
  339. if max < s.overflow[i] {
  340. max = s.overflow[i]
  341. }
  342. }
  343. avg := float64(sum) / float64(n)
  344. varianceSum := 0.0
  345. for i := 0; i < len(s.data); i++ {
  346. if s.data[i] > 0 {
  347. d := float64(i) - avg
  348. varianceSum += d * d * float64(s.data[i])
  349. }
  350. }
  351. for i := 0; i < len(s.overflow); i++ {
  352. d := float64(s.overflow[i]) - avg
  353. varianceSum += d * d
  354. }
  355. std := math.Sqrt(varianceSum / float64(n))
  356. fmt.Printf("\nConnection Times (ms)\n")
  357. fmt.Printf(" min avg max std\n")
  358. fmt.Printf("Total: %2.1f %3.1f %3.1f %3.1f\n", float32(min)/10, float32(avg)/10, float32(max)/10, std/10)
  359. //printing percentiles
  360. fmt.Printf("\nPercentage of the requests served within a certain time (ms)\n")
  361. percentiles := make([]int, len(percentages))
  362. for i := 0; i < len(percentages); i++ {
  363. percentiles[i] = n * percentages[i] / 100
  364. }
  365. percentiles[len(percentiles)-1] = n
  366. percentileIndex := 0
  367. currentSum := 0
  368. for i := 0; i < len(s.data); i++ {
  369. currentSum += s.data[i]
  370. if s.data[i] > 0 && percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  371. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(i)/10.0)
  372. percentileIndex++
  373. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  374. percentileIndex++
  375. }
  376. }
  377. }
  378. sort.Ints(s.overflow)
  379. for i := 0; i < len(s.overflow); i++ {
  380. currentSum++
  381. if percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  382. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(s.overflow[i])/10.0)
  383. percentileIndex++
  384. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  385. percentileIndex++
  386. }
  387. }
  388. }
  389. }
  390. // a fake reader to generate content to upload
  391. type FakeReader struct {
  392. id uint64 // an id number
  393. size int64 // max bytes
  394. }
  395. func (l *FakeReader) Read(p []byte) (n int, err error) {
  396. if l.size <= 0 {
  397. return 0, io.EOF
  398. }
  399. if int64(len(p)) > l.size {
  400. n = int(l.size)
  401. } else {
  402. n = len(p)
  403. }
  404. for i := 0; i < n-8; i += 8 {
  405. for s := uint(0); s < 8; s++ {
  406. p[i] = byte(l.id >> (s * 8))
  407. }
  408. }
  409. l.size -= int64(n)
  410. return
  411. }
  412. func Readln(r *bufio.Reader) ([]byte, error) {
  413. var (
  414. isPrefix bool = true
  415. err error = nil
  416. line, ln []byte
  417. )
  418. for isPrefix && err == nil {
  419. line, isPrefix, err = r.ReadLine()
  420. ln = append(ln, line...)
  421. }
  422. return ln, err
  423. }