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.

526 lines
14 KiB

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