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.

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