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.

455 lines
12 KiB

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