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.

563 lines
15 KiB

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