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.

544 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{Reader: &FakeReader{id: uint64(id), size: fileSize}, FileSize: fileSize}
  191. ar := &operation.VolumeAssignRequest{
  192. Count: 1,
  193. Collection: *b.collection,
  194. }
  195. if assignResult, err := operation.Assign(masterClient.GetMaster(), ar); err == nil {
  196. fp.Server, fp.Fid, fp.Collection = assignResult.Url, assignResult.Fid, *b.collection
  197. if _, err := fp.Upload(0, masterClient.GetMaster(), secret); err == nil {
  198. if random.Intn(100) < *b.deletePercentage {
  199. s.total++
  200. delayedDeleteChan <- &delayedFile{time.Now().Add(time.Second), fp}
  201. } else {
  202. fileIdLineChan <- fp.Fid
  203. }
  204. s.completed++
  205. s.transferred += fileSize
  206. } else {
  207. s.failed++
  208. fmt.Printf("Failed to write with error:%v\n", err)
  209. }
  210. writeStats.addSample(time.Now().Sub(start))
  211. if *cmdBenchmark.IsDebug {
  212. fmt.Printf("writing %d file %s\n", id, fp.Fid)
  213. }
  214. } else {
  215. s.failed++
  216. println("writing file error:", err.Error())
  217. }
  218. }
  219. close(delayedDeleteChan)
  220. waitForDeletions.Wait()
  221. }
  222. func readFiles(fileIdLineChan chan string, s *stat) {
  223. defer wait.Done()
  224. for fid := range fileIdLineChan {
  225. if len(fid) == 0 {
  226. continue
  227. }
  228. if fid[0] == '#' {
  229. continue
  230. }
  231. if *cmdBenchmark.IsDebug {
  232. fmt.Printf("reading file %s\n", fid)
  233. }
  234. start := time.Now()
  235. url, err := masterClient.LookupFileId(fid)
  236. if err != nil {
  237. s.failed++
  238. println("!!!! ", fid, " location not found!!!!!")
  239. continue
  240. }
  241. if bytesRead, err := util.Get(url); err == nil {
  242. s.completed++
  243. s.transferred += int64(len(bytesRead))
  244. readStats.addSample(time.Now().Sub(start))
  245. } else {
  246. s.failed++
  247. fmt.Printf("Failed to read %s error:%v\n", url, err)
  248. }
  249. }
  250. }
  251. func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
  252. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  253. if err != nil {
  254. glog.Fatalf("File to create file %s: %s\n", fileName, err)
  255. }
  256. defer file.Close()
  257. for {
  258. select {
  259. case <-finishChan:
  260. wait.Done()
  261. return
  262. case line := <-fileIdLineChan:
  263. file.Write([]byte(line))
  264. file.Write([]byte("\n"))
  265. }
  266. }
  267. }
  268. func readFileIds(fileName string, fileIdLineChan chan string) {
  269. file, err := os.Open(fileName) // For read access.
  270. if err != nil {
  271. glog.Fatalf("File to read file %s: %s\n", fileName, err)
  272. }
  273. defer file.Close()
  274. random := rand.New(rand.NewSource(time.Now().UnixNano()))
  275. r := bufio.NewReader(file)
  276. if *b.sequentialRead {
  277. for {
  278. if line, err := Readln(r); err == nil {
  279. fileIdLineChan <- string(line)
  280. } else {
  281. break
  282. }
  283. }
  284. } else {
  285. lines := make([]string, 0, readStats.total)
  286. for {
  287. if line, err := Readln(r); err == nil {
  288. lines = append(lines, string(line))
  289. } else {
  290. break
  291. }
  292. }
  293. if len(lines) > 0 {
  294. for i := 0; i < readStats.total; i++ {
  295. fileIdLineChan <- lines[random.Intn(len(lines))]
  296. }
  297. }
  298. }
  299. close(fileIdLineChan)
  300. }
  301. const (
  302. benchResolution = 10000 //0.1 microsecond
  303. benchBucket = 1000000000 / benchResolution
  304. )
  305. // An efficient statics collecting and rendering
  306. type stats struct {
  307. data []int
  308. overflow []int
  309. localStats []stat
  310. start time.Time
  311. end time.Time
  312. total int
  313. }
  314. type stat struct {
  315. completed int
  316. failed int
  317. total int
  318. transferred int64
  319. }
  320. var percentages = []int{50, 66, 75, 80, 90, 95, 98, 99, 100}
  321. func newStats(n int) *stats {
  322. return &stats{
  323. data: make([]int, benchResolution),
  324. overflow: make([]int, 0),
  325. localStats: make([]stat, n),
  326. }
  327. }
  328. func (s *stats) addSample(d time.Duration) {
  329. index := int(d / benchBucket)
  330. if index < 0 {
  331. fmt.Printf("This request takes %3.1f seconds, skipping!\n", float64(index)/10000)
  332. } else if index < len(s.data) {
  333. s.data[int(d/benchBucket)]++
  334. } else {
  335. s.overflow = append(s.overflow, index)
  336. }
  337. }
  338. func (s *stats) checkProgress(testName string, finishChan chan bool) {
  339. fmt.Printf("\n------------ %s ----------\n", testName)
  340. ticker := time.Tick(time.Second)
  341. lastCompleted, lastTransferred, lastTime := 0, int64(0), time.Now()
  342. for {
  343. select {
  344. case <-finishChan:
  345. wait.Done()
  346. return
  347. case t := <-ticker:
  348. completed, transferred, taken, total := 0, int64(0), t.Sub(lastTime), s.total
  349. for _, localStat := range s.localStats {
  350. completed += localStat.completed
  351. transferred += localStat.transferred
  352. total += localStat.total
  353. }
  354. fmt.Printf("Completed %d of %d requests, %3.1f%% %3.1f/s %3.1fMB/s\n",
  355. completed, total, float64(completed)*100/float64(total),
  356. float64(completed-lastCompleted)*float64(int64(time.Second))/float64(int64(taken)),
  357. float64(transferred-lastTransferred)*float64(int64(time.Second))/float64(int64(taken))/float64(1024*1024),
  358. )
  359. lastCompleted, lastTransferred, lastTime = completed, transferred, t
  360. }
  361. }
  362. }
  363. func (s *stats) printStats() {
  364. completed, failed, transferred, total := 0, 0, int64(0), s.total
  365. for _, localStat := range s.localStats {
  366. completed += localStat.completed
  367. failed += localStat.failed
  368. transferred += localStat.transferred
  369. total += localStat.total
  370. }
  371. timeTaken := float64(int64(s.end.Sub(s.start))) / 1000000000
  372. fmt.Printf("\nConcurrency Level: %d\n", *b.concurrency)
  373. fmt.Printf("Time taken for tests: %.3f seconds\n", timeTaken)
  374. fmt.Printf("Complete requests: %d\n", completed)
  375. fmt.Printf("Failed requests: %d\n", failed)
  376. fmt.Printf("Total transferred: %d bytes\n", transferred)
  377. fmt.Printf("Requests per second: %.2f [#/sec]\n", float64(completed)/timeTaken)
  378. fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", float64(transferred)/1024/timeTaken)
  379. n, sum := 0, 0
  380. min, max := 10000000, 0
  381. for i := 0; i < len(s.data); i++ {
  382. n += s.data[i]
  383. sum += s.data[i] * i
  384. if s.data[i] > 0 {
  385. if min > i {
  386. min = i
  387. }
  388. if max < i {
  389. max = i
  390. }
  391. }
  392. }
  393. n += len(s.overflow)
  394. for i := 0; i < len(s.overflow); i++ {
  395. sum += s.overflow[i]
  396. if min > s.overflow[i] {
  397. min = s.overflow[i]
  398. }
  399. if max < s.overflow[i] {
  400. max = s.overflow[i]
  401. }
  402. }
  403. avg := float64(sum) / float64(n)
  404. varianceSum := 0.0
  405. for i := 0; i < len(s.data); i++ {
  406. if s.data[i] > 0 {
  407. d := float64(i) - avg
  408. varianceSum += d * d * float64(s.data[i])
  409. }
  410. }
  411. for i := 0; i < len(s.overflow); i++ {
  412. d := float64(s.overflow[i]) - avg
  413. varianceSum += d * d
  414. }
  415. std := math.Sqrt(varianceSum / float64(n))
  416. fmt.Printf("\nConnection Times (ms)\n")
  417. fmt.Printf(" min avg max std\n")
  418. fmt.Printf("Total: %2.1f %3.1f %3.1f %3.1f\n", float32(min)/10, float32(avg)/10, float32(max)/10, std/10)
  419. //printing percentiles
  420. fmt.Printf("\nPercentage of the requests served within a certain time (ms)\n")
  421. percentiles := make([]int, len(percentages))
  422. for i := 0; i < len(percentages); i++ {
  423. percentiles[i] = n * percentages[i] / 100
  424. }
  425. percentiles[len(percentiles)-1] = n
  426. percentileIndex := 0
  427. currentSum := 0
  428. for i := 0; i < len(s.data); i++ {
  429. currentSum += s.data[i]
  430. if s.data[i] > 0 && percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  431. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(i)/10.0)
  432. percentileIndex++
  433. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  434. percentileIndex++
  435. }
  436. }
  437. }
  438. sort.Ints(s.overflow)
  439. for i := 0; i < len(s.overflow); i++ {
  440. currentSum++
  441. if percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  442. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(s.overflow[i])/10.0)
  443. percentileIndex++
  444. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  445. percentileIndex++
  446. }
  447. }
  448. }
  449. }
  450. // a fake reader to generate content to upload
  451. type FakeReader struct {
  452. id uint64 // an id number
  453. size int64 // max bytes
  454. }
  455. func (l *FakeReader) Read(p []byte) (n int, err error) {
  456. if l.size <= 0 {
  457. return 0, io.EOF
  458. }
  459. if int64(len(p)) > l.size {
  460. n = int(l.size)
  461. } else {
  462. n = len(p)
  463. }
  464. if n >= 8 {
  465. for i := 0; i < 8; i++ {
  466. p[i] = byte(l.id >> uint(i*8))
  467. }
  468. }
  469. l.size -= int64(n)
  470. return
  471. }
  472. func (l *FakeReader) WriteTo(w io.Writer) (n int64, err error) {
  473. size := int(l.size)
  474. bufferSize := len(sharedBytes)
  475. for size > 0 {
  476. tempBuffer := sharedBytes
  477. if size < bufferSize {
  478. tempBuffer = sharedBytes[0:size]
  479. }
  480. count, e := w.Write(tempBuffer)
  481. if e != nil {
  482. return int64(size), e
  483. }
  484. size -= count
  485. }
  486. return l.size, nil
  487. }
  488. func Readln(r *bufio.Reader) ([]byte, error) {
  489. var (
  490. isPrefix = true
  491. err error
  492. line, ln []byte
  493. )
  494. for isPrefix && err == nil {
  495. line, isPrefix, err = r.ReadLine()
  496. ln = append(ln, line...)
  497. }
  498. return ln, err
  499. }