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.

608 lines
17 KiB

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