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.

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