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.

548 lines
15 KiB

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