Debian Codegraph @

cmd/bolt/main.go

raw symbols SCIP
1 package main
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "flag"
8 "fmt"
9 "io"
10 "io/ioutil"
11 "math/rand"
12 "os"
13 "runtime"
14 "runtime/pprof"
15 "strconv"
16 "strings"
17 "time"
18 "unicode"
19 "unicode/utf8"
20 "unsafe"
21
22 "github.com/NebulousLabs/bolt"
23 )
24
25 var (
26 // ErrUsage is returned when a usage message was printed and the process
27 // should simply exit with an error.
28 ErrUsage = errors.New("usage")
29
30 // ErrUnknownCommand is returned when a CLI command is not specified.
31 ErrUnknownCommand = errors.New("unknown command")
32
33 // ErrPathRequired is returned when the path to a Bolt database is not specified.
34 ErrPathRequired = errors.New("path required")
35
36 // ErrFileNotFound is returned when a Bolt database does not exist.
37 ErrFileNotFound = errors.New("file not found")
38
39 // ErrInvalidValue is returned when a benchmark reads an unexpected value.
40 ErrInvalidValue = errors.New("invalid value")
41
42 // ErrCorrupt is returned when a checking a data file finds errors.
43 ErrCorrupt = errors.New("invalid value")
44
45 // ErrNonDivisibleBatchSize is returned when the batch size can't be evenly
46 // divided by the iteration count.
47 ErrNonDivisibleBatchSize = errors.New("number of iterations must be divisible by the batch size")
48
49 // ErrPageIDRequired is returned when a required page id is not specified.
50 ErrPageIDRequired = errors.New("page id required")
51
52 // ErrPageNotFound is returned when specifying a page above the high water mark.
53 ErrPageNotFound = errors.New("page not found")
54
55 // ErrPageFreed is returned when reading a page that has already been freed.
56 ErrPageFreed = errors.New("page freed")
57 )
58
59 // PageHeaderSize represents the size of the bolt.page header.
60 const PageHeaderSize = 16
61
62 func main() {
63 m := NewMain()
64 if err := m.Run(os.Args[1:]...); err == ErrUsage {
65 os.Exit(2)
66 } else if err != nil {
67 fmt.Println(err.Error())
68 os.Exit(1)
69 }
70 }
71
72 // Main represents the main program execution.
73 type Main struct {
74 Stdin io.Reader
75 Stdout io.Writer
76 Stderr io.Writer
77 }
78
79 // NewMain returns a new instance of Main connect to the standard input/output.
80 func NewMain() *Main {
81 return &Main{
82 Stdin: os.Stdin,
83 Stdout: os.Stdout,
84 Stderr: os.Stderr,
85 }
86 }
87
88 // Run executes the program.
89 func (m *Main) Run(args ...string) error {
90 // Require a command at the beginning.
91 if len(args) == 0 || strings.HasPrefix(args[0], "-") {
92 fmt.Fprintln(m.Stderr, m.Usage())
93 return ErrUsage
94 }
95
96 // Execute command.
97 switch args[0] {
98 case "help":
99 fmt.Fprintln(m.Stderr, m.Usage())
100 return ErrUsage
101 case "bench":
102 return newBenchCommand(m).Run(args[1:]...)
103 case "check":
104 return newCheckCommand(m).Run(args[1:]...)
105 case "compact":
106 return newCompactCommand(m).Run(args[1:]...)
107 case "dump":
108 return newDumpCommand(m).Run(args[1:]...)
109 case "info":
110 return newInfoCommand(m).Run(args[1:]...)
111 case "page":
112 return newPageCommand(m).Run(args[1:]...)
113 case "pages":
114 return newPagesCommand(m).Run(args[1:]...)
115 case "stats":
116 return newStatsCommand(m).Run(args[1:]...)
117 default:
118 return ErrUnknownCommand
119 }
120 }
121
122 // Usage returns the help message.
123 func (m *Main) Usage() string {
124 return strings.TrimLeft(`
125 Bolt is a tool for inspecting bolt databases.
126
127 Usage:
128
129 bolt command [arguments]
130
131 The commands are:
132
133 bench run synthetic benchmark against bolt
134 check verifies integrity of bolt database
135 compact copies a bolt database, compacting it in the process
136 info print basic info
137 help print this screen
138 pages print list of pages with their types
139 stats iterate over all pages and generate usage stats
140
141 Use "bolt [command] -h" for more information about a command.
142 `, "\n")
143 }
144
145 // CheckCommand represents the "check" command execution.
146 type CheckCommand struct {
147 Stdin io.Reader
148 Stdout io.Writer
149 Stderr io.Writer
150 }
151
152 // NewCheckCommand returns a CheckCommand.
153 func newCheckCommand(m *Main) *CheckCommand {
154 return &CheckCommand{
155 Stdin: m.Stdin,
156 Stdout: m.Stdout,
157 Stderr: m.Stderr,
158 }
159 }
160
161 // Run executes the command.
162 func (cmd *CheckCommand) Run(args ...string) error {
163 // Parse flags.
164 fs := flag.NewFlagSet("", flag.ContinueOnError)
165 help := fs.Bool("h", false, "")
166 if err := fs.Parse(args); err != nil {
167 return err
168 } else if *help {
169 fmt.Fprintln(cmd.Stderr, cmd.Usage())
170 return ErrUsage
171 }
172
173 // Require database path.
174 path := fs.Arg(0)
175 if path == "" {
176 return ErrPathRequired
177 } else if _, err := os.Stat(path); os.IsNotExist(err) {
178 return ErrFileNotFound
179 }
180
181 // Open database.
182 db, err := bolt.Open(path, 0666, nil)
183 if err != nil {
184 return err
185 }
186 defer db.Close()
187
188 // Perform consistency check.
189 return db.View(func(tx *bolt.Tx) error {
190 var count int
191 ch := tx.Check()
192 loop:
193 for {
194 select {
195 case err, ok := <-ch:
196 if !ok {
197 break loop
198 }
199 fmt.Fprintln(cmd.Stdout, err)
200 count++
201 }
202 }
203
204 // Print summary of errors.
205 if count > 0 {
206 fmt.Fprintf(cmd.Stdout, "%d errors found\n", count)
207 return ErrCorrupt
208 }
209
210 // Notify user that database is valid.
211 fmt.Fprintln(cmd.Stdout, "OK")
212 return nil
213 })
214 }
215
216 // Usage returns the help message.
217 func (cmd *CheckCommand) Usage() string {
218 return strings.TrimLeft(`
219 usage: bolt check PATH
220
221 Check opens a database at PATH and runs an exhaustive check to verify that
222 all pages are accessible or are marked as freed. It also verifies that no
223 pages are double referenced.
224
225 Verification errors will stream out as they are found and the process will
226 return after all pages have been checked.
227 `, "\n")
228 }
229
230 // InfoCommand represents the "info" command execution.
231 type InfoCommand struct {
232 Stdin io.Reader
233 Stdout io.Writer
234 Stderr io.Writer
235 }
236
237 // NewInfoCommand returns a InfoCommand.
238 func newInfoCommand(m *Main) *InfoCommand {
239 return &InfoCommand{
240 Stdin: m.Stdin,
241 Stdout: m.Stdout,
242 Stderr: m.Stderr,
243 }
244 }
245
246 // Run executes the command.
247 func (cmd *InfoCommand) Run(args ...string) error {
248 // Parse flags.
249 fs := flag.NewFlagSet("", flag.ContinueOnError)
250 help := fs.Bool("h", false, "")
251 if err := fs.Parse(args); err != nil {
252 return err
253 } else if *help {
254 fmt.Fprintln(cmd.Stderr, cmd.Usage())
255 return ErrUsage
256 }
257
258 // Require database path.
259 path := fs.Arg(0)
260 if path == "" {
261 return ErrPathRequired
262 } else if _, err := os.Stat(path); os.IsNotExist(err) {
263 return ErrFileNotFound
264 }
265
266 // Open the database.
267 db, err := bolt.Open(path, 0666, nil)
268 if err != nil {
269 return err
270 }
271 defer db.Close()
272
273 // Print basic database info.
274 info := db.Info()
275 fmt.Fprintf(cmd.Stdout, "Page Size: %d\n", info.PageSize)
276
277 return nil
278 }
279
280 // Usage returns the help message.
281 func (cmd *InfoCommand) Usage() string {
282 return strings.TrimLeft(`
283 usage: bolt info PATH
284
285 Info prints basic information about the Bolt database at PATH.
286 `, "\n")
287 }
288
289 // DumpCommand represents the "dump" command execution.
290 type DumpCommand struct {
291 Stdin io.Reader
292 Stdout io.Writer
293 Stderr io.Writer
294 }
295
296 // newDumpCommand returns a DumpCommand.
297 func newDumpCommand(m *Main) *DumpCommand {
298 return &DumpCommand{
299 Stdin: m.Stdin,
300 Stdout: m.Stdout,
301 Stderr: m.Stderr,
302 }
303 }
304
305 // Run executes the command.
306 func (cmd *DumpCommand) Run(args ...string) error {
307 // Parse flags.
308 fs := flag.NewFlagSet("", flag.ContinueOnError)
309 help := fs.Bool("h", false, "")
310 if err := fs.Parse(args); err != nil {
311 return err
312 } else if *help {
313 fmt.Fprintln(cmd.Stderr, cmd.Usage())
314 return ErrUsage
315 }
316
317 // Require database path and page id.
318 path := fs.Arg(0)
319 if path == "" {
320 return ErrPathRequired
321 } else if _, err := os.Stat(path); os.IsNotExist(err) {
322 return ErrFileNotFound
323 }
324
325 // Read page ids.
326 pageIDs, err := atois(fs.Args()[1:])
327 if err != nil {
328 return err
329 } else if len(pageIDs) == 0 {
330 return ErrPageIDRequired
331 }
332
333 // Open database to retrieve page size.
334 pageSize, err := ReadPageSize(path)
335 if err != nil {
336 return err
337 }
338
339 // Open database file handler.
340 f, err := os.Open(path)
341 if err != nil {
342 return err
343 }
344 defer func() { _ = f.Close() }()
345
346 // Print each page listed.
347 for i, pageID := range pageIDs {
348 // Print a separator.
349 if i > 0 {
350 fmt.Fprintln(cmd.Stdout, "===============================================")
351 }
352
353 // Print page to stdout.
354 if err := cmd.PrintPage(cmd.Stdout, f, pageID, pageSize); err != nil {
355 return err
356 }
357 }
358
359 return nil
360 }
361
362 // PrintPage prints a given page as hexadecimal.
363 func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error {
364 const bytesPerLineN = 16
365
366 // Read page into buffer.
367 buf := make([]byte, pageSize)
368 addr := pageID * pageSize
369 if n, err := r.ReadAt(buf, int64(addr)); err != nil {
370 return err
371 } else if n != pageSize {
372 return io.ErrUnexpectedEOF
373 }
374
375 // Write out to writer in 16-byte lines.
376 var prev []byte
377 var skipped bool
378 for offset := 0; offset < pageSize; offset += bytesPerLineN {
379 // Retrieve current 16-byte line.
380 line := buf[offset : offset+bytesPerLineN]
381 isLastLine := (offset == (pageSize - bytesPerLineN))
382
383 // If it's the same as the previous line then print a skip.
384 if bytes.Equal(line, prev) && !isLastLine {
385 if !skipped {
386 fmt.Fprintf(w, "%07x *\n", addr+offset)
387 skipped = true
388 }
389 } else {
390 // Print line as hexadecimal in 2-byte groups.
391 fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset,
392 line[0:2], line[2:4], line[4:6], line[6:8],
393 line[8:10], line[10:12], line[12:14], line[14:16],
394 )
395
396 skipped = false
397 }
398
399 // Save the previous line.
400 prev = line
401 }
402 fmt.Fprint(w, "\n")
403
404 return nil
405 }
406
407 // Usage returns the help message.
408 func (cmd *DumpCommand) Usage() string {
409 return strings.TrimLeft(`
410 usage: bolt dump -page PAGEID PATH
411
412 Dump prints a hexadecimal dump of a single page.
413 `, "\n")
414 }
415
416 // PageCommand represents the "page" command execution.
417 type PageCommand struct {
418 Stdin io.Reader
419 Stdout io.Writer
420 Stderr io.Writer
421 }
422
423 // newPageCommand returns a PageCommand.
424 func newPageCommand(m *Main) *PageCommand {
425 return &PageCommand{
426 Stdin: m.Stdin,
427 Stdout: m.Stdout,
428 Stderr: m.Stderr,
429 }
430 }
431
432 // Run executes the command.
433 func (cmd *PageCommand) Run(args ...string) error {
434 // Parse flags.
435 fs := flag.NewFlagSet("", flag.ContinueOnError)
436 help := fs.Bool("h", false, "")
437 if err := fs.Parse(args); err != nil {
438 return err
439 } else if *help {
440 fmt.Fprintln(cmd.Stderr, cmd.Usage())
441 return ErrUsage
442 }
443
444 // Require database path and page id.
445 path := fs.Arg(0)
446 if path == "" {
447 return ErrPathRequired
448 } else if _, err := os.Stat(path); os.IsNotExist(err) {
449 return ErrFileNotFound
450 }
451
452 // Read page ids.
453 pageIDs, err := atois(fs.Args()[1:])
454 if err != nil {
455 return err
456 } else if len(pageIDs) == 0 {
457 return ErrPageIDRequired
458 }
459
460 // Open database file handler.
461 f, err := os.Open(path)
462 if err != nil {
463 return err
464 }
465 defer func() { _ = f.Close() }()
466
467 // Print each page listed.
468 for i, pageID := range pageIDs {
469 // Print a separator.
470 if i > 0 {
471 fmt.Fprintln(cmd.Stdout, "===============================================")
472 }
473
474 // Retrieve page info and page size.
475 p, buf, err := ReadPage(path, pageID)
476 if err != nil {
477 return err
478 }
479
480 // Print basic page info.
481 fmt.Fprintf(cmd.Stdout, "Page ID: %d\n", p.id)
482 fmt.Fprintf(cmd.Stdout, "Page Type: %s\n", p.Type())
483 fmt.Fprintf(cmd.Stdout, "Total Size: %d bytes\n", len(buf))
484
485 // Print type-specific data.
486 switch p.Type() {
487 case "meta":
488 err = cmd.PrintMeta(cmd.Stdout, buf)
489 case "leaf":
490 err = cmd.PrintLeaf(cmd.Stdout, buf)
491 case "branch":
492 err = cmd.PrintBranch(cmd.Stdout, buf)
493 case "freelist":
494 err = cmd.PrintFreelist(cmd.Stdout, buf)
495 }
496 if err != nil {
497 return err
498 }
499 }
500
501 return nil
502 }
503
504 // PrintMeta prints the data from the meta page.
505 func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error {
506 m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize]))
507 fmt.Fprintf(w, "Version: %d\n", m.version)
508 fmt.Fprintf(w, "Page Size: %d bytes\n", m.pageSize)
509 fmt.Fprintf(w, "Flags: %08x\n", m.flags)
510 fmt.Fprintf(w, "Root: <pgid=%d>\n", m.root.root)
511 fmt.Fprintf(w, "Freelist: <pgid=%d>\n", m.freelist)
512 fmt.Fprintf(w, "HWM: <pgid=%d>\n", m.pgid)
513 fmt.Fprintf(w, "Txn ID: %d\n", m.txid)
514 fmt.Fprintf(w, "Checksum: %016x\n", m.checksum)
515 fmt.Fprintf(w, "\n")
516 return nil
517 }
518
519 // PrintLeaf prints the data for a leaf page.
520 func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error {
521 p := (*page)(unsafe.Pointer(&buf[0]))
522
523 // Print number of items.
524 fmt.Fprintf(w, "Item Count: %d\n", p.count)
525 fmt.Fprintf(w, "\n")
526
527 // Print each key/value.
528 for i := uint16(0); i < p.count; i++ {
529 e := p.leafPageElement(i)
530
531 // Format key as string.
532 var k string
533 if isPrintable(string(e.key())) {
534 k = fmt.Sprintf("%q", string(e.key()))
535 } else {
536 k = fmt.Sprintf("%x", string(e.key()))
537 }
538
539 // Format value as string.
540 var v string
541 if (e.flags & uint32(bucketLeafFlag)) != 0 {
542 b := (*bucket)(unsafe.Pointer(&e.value()[0]))
543 v = fmt.Sprintf("<pgid=%d,seq=%d>", b.root, b.sequence)
544 } else if isPrintable(string(e.value())) {
545 v = fmt.Sprintf("%q", string(e.value()))
546 } else {
547 v = fmt.Sprintf("%x", string(e.value()))
548 }
549
550 fmt.Fprintf(w, "%s: %s\n", k, v)
551 }
552 fmt.Fprintf(w, "\n")
553 return nil
554 }
555
556 // PrintBranch prints the data for a leaf page.
557 func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error {
558 p := (*page)(unsafe.Pointer(&buf[0]))
559
560 // Print number of items.
561 fmt.Fprintf(w, "Item Count: %d\n", p.count)
562 fmt.Fprintf(w, "\n")
563
564 // Print each key/value.
565 for i := uint16(0); i < p.count; i++ {
566 e := p.branchPageElement(i)
567
568 // Format key as string.
569 var k string
570 if isPrintable(string(e.key())) {
571 k = fmt.Sprintf("%q", string(e.key()))
572 } else {
573 k = fmt.Sprintf("%x", string(e.key()))
574 }
575
576 fmt.Fprintf(w, "%s: <pgid=%d>\n", k, e.pgid)
577 }
578 fmt.Fprintf(w, "\n")
579 return nil
580 }
581
582 // PrintFreelist prints the data for a freelist page.
583 func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error {
584 p := (*page)(unsafe.Pointer(&buf[0]))
585
586 // Print number of items.
587 fmt.Fprintf(w, "Item Count: %d\n", p.count)
588 fmt.Fprintf(w, "\n")
589
590 // Print each page in the freelist.
591 ids := (*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr))
592 for i := uint16(0); i < p.count; i++ {
593 fmt.Fprintf(w, "%d\n", ids[i])
594 }
595 fmt.Fprintf(w, "\n")
596 return nil
597 }
598
599 // PrintPage prints a given page as hexadecimal.
600 func (cmd *PageCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error {
601 const bytesPerLineN = 16
602
603 // Read page into buffer.
604 buf := make([]byte, pageSize)
605 addr := pageID * pageSize
606 if n, err := r.ReadAt(buf, int64(addr)); err != nil {
607 return err
608 } else if n != pageSize {
609 return io.ErrUnexpectedEOF
610 }
611
612 // Write out to writer in 16-byte lines.
613 var prev []byte
614 var skipped bool
615 for offset := 0; offset < pageSize; offset += bytesPerLineN {
616 // Retrieve current 16-byte line.
617 line := buf[offset : offset+bytesPerLineN]
618 isLastLine := (offset == (pageSize - bytesPerLineN))
619
620 // If it's the same as the previous line then print a skip.
621 if bytes.Equal(line, prev) && !isLastLine {
622 if !skipped {
623 fmt.Fprintf(w, "%07x *\n", addr+offset)
624 skipped = true
625 }
626 } else {
627 // Print line as hexadecimal in 2-byte groups.
628 fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset,
629 line[0:2], line[2:4], line[4:6], line[6:8],
630 line[8:10], line[10:12], line[12:14], line[14:16],
631 )
632
633 skipped = false
634 }
635
636 // Save the previous line.
637 prev = line
638 }
639 fmt.Fprint(w, "\n")
640
641 return nil
642 }
643
644 // Usage returns the help message.
645 func (cmd *PageCommand) Usage() string {
646 return strings.TrimLeft(`
647 usage: bolt page -page PATH pageid [pageid...]
648
649 Page prints one or more pages in human readable format.
650 `, "\n")
651 }
652
653 // PagesCommand represents the "pages" command execution.
654 type PagesCommand struct {
655 Stdin io.Reader
656 Stdout io.Writer
657 Stderr io.Writer
658 }
659
660 // NewPagesCommand returns a PagesCommand.
661 func newPagesCommand(m *Main) *PagesCommand {
662 return &PagesCommand{
663 Stdin: m.Stdin,
664 Stdout: m.Stdout,
665 Stderr: m.Stderr,
666 }
667 }
668
669 // Run executes the command.
670 func (cmd *PagesCommand) Run(args ...string) error {
671 // Parse flags.
672 fs := flag.NewFlagSet("", flag.ContinueOnError)
673 help := fs.Bool("h", false, "")
674 if err := fs.Parse(args); err != nil {
675 return err
676 } else if *help {
677 fmt.Fprintln(cmd.Stderr, cmd.Usage())
678 return ErrUsage
679 }
680
681 // Require database path.
682 path := fs.Arg(0)
683 if path == "" {
684 return ErrPathRequired
685 } else if _, err := os.Stat(path); os.IsNotExist(err) {
686 return ErrFileNotFound
687 }
688
689 // Open database.
690 db, err := bolt.Open(path, 0666, nil)
691 if err != nil {
692 return err
693 }
694 defer func() { _ = db.Close() }()
695
696 // Write header.
697 fmt.Fprintln(cmd.Stdout, "ID TYPE ITEMS OVRFLW")
698 fmt.Fprintln(cmd.Stdout, "======== ========== ====== ======")
699
700 return db.Update(func(tx *bolt.Tx) error {
701 var id int
702 for {
703 p, err := tx.Page(id)
704 if err != nil {
705 return &PageError{ID: id, Err: err}
706 } else if p == nil {
707 break
708 }
709
710 // Only display count and overflow if this is a non-free page.
711 var count, overflow string
712 if p.Type != "free" {
713 count = strconv.Itoa(p.Count)
714 if p.OverflowCount > 0 {
715 overflow = strconv.Itoa(p.OverflowCount)
716 }
717 }
718
719 // Print table row.
720 fmt.Fprintf(cmd.Stdout, "%-8d %-10s %-6s %-6s\n", p.ID, p.Type, count, overflow)
721
722 // Move to the next non-overflow page.
723 id += 1
724 if p.Type != "free" {
725 id += p.OverflowCount
726 }
727 }
728 return nil
729 })
730 }
731
732 // Usage returns the help message.
733 func (cmd *PagesCommand) Usage() string {
734 return strings.TrimLeft(`
735 usage: bolt pages PATH
736
737 Pages prints a table of pages with their type (meta, leaf, branch, freelist).
738 Leaf and branch pages will show a key count in the "items" column while the
739 freelist will show the number of free pages in the "items" column.
740
741 The "overflow" column shows the number of blocks that the page spills over
742 into. Normally there is no overflow but large keys and values can cause
743 a single page to take up multiple blocks.
744 `, "\n")
745 }
746
747 // StatsCommand represents the "stats" command execution.
748 type StatsCommand struct {
749 Stdin io.Reader
750 Stdout io.Writer
751 Stderr io.Writer
752 }
753
754 // NewStatsCommand returns a StatsCommand.
755 func newStatsCommand(m *Main) *StatsCommand {
756 return &StatsCommand{
757 Stdin: m.Stdin,
758 Stdout: m.Stdout,
759 Stderr: m.Stderr,
760 }
761 }
762
763 // Run executes the command.
764 func (cmd *StatsCommand) Run(args ...string) error {
765 // Parse flags.
766 fs := flag.NewFlagSet("", flag.ContinueOnError)
767 help := fs.Bool("h", false, "")
768 if err := fs.Parse(args); err != nil {
769 return err
770 } else if *help {
771 fmt.Fprintln(cmd.Stderr, cmd.Usage())
772 return ErrUsage
773 }
774
775 // Require database path.
776 path, prefix := fs.Arg(0), fs.Arg(1)
777 if path == "" {
778 return ErrPathRequired
779 } else if _, err := os.Stat(path); os.IsNotExist(err) {
780 return ErrFileNotFound
781 }
782
783 // Open database.
784 db, err := bolt.Open(path, 0666, nil)
785 if err != nil {
786 return err
787 }
788 defer db.Close()
789
790 return db.View(func(tx *bolt.Tx) error {
791 var s bolt.BucketStats
792 var count int
793 if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error {
794 if bytes.HasPrefix(name, []byte(prefix)) {
795 s.Add(b.Stats())
796 count += 1
797 }
798 return nil
799 }); err != nil {
800 return err
801 }
802
803 fmt.Fprintf(cmd.Stdout, "Aggregate statistics for %d buckets\n\n", count)
804
805 fmt.Fprintln(cmd.Stdout, "Page count statistics")
806 fmt.Fprintf(cmd.Stdout, "\tNumber of logical branch pages: %d\n", s.BranchPageN)
807 fmt.Fprintf(cmd.Stdout, "\tNumber of physical branch overflow pages: %d\n", s.BranchOverflowN)
808 fmt.Fprintf(cmd.Stdout, "\tNumber of logical leaf pages: %d\n", s.LeafPageN)
809 fmt.Fprintf(cmd.Stdout, "\tNumber of physical leaf overflow pages: %d\n", s.LeafOverflowN)
810
811 fmt.Fprintln(cmd.Stdout, "Tree statistics")
812 fmt.Fprintf(cmd.Stdout, "\tNumber of keys/value pairs: %d\n", s.KeyN)
813 fmt.Fprintf(cmd.Stdout, "\tNumber of levels in B+tree: %d\n", s.Depth)
814
815 fmt.Fprintln(cmd.Stdout, "Page size utilization")
816 fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical branch pages: %d\n", s.BranchAlloc)
817 var percentage int
818 if s.BranchAlloc != 0 {
819 percentage = int(float32(s.BranchInuse) * 100.0 / float32(s.BranchAlloc))
820 }
821 fmt.Fprintf(cmd.Stdout, "\tBytes actually used for branch data: %d (%d%%)\n", s.BranchInuse, percentage)
822 fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical leaf pages: %d\n", s.LeafAlloc)
823 percentage = 0
824 if s.LeafAlloc != 0 {
825 percentage = int(float32(s.LeafInuse) * 100.0 / float32(s.LeafAlloc))
826 }
827 fmt.Fprintf(cmd.Stdout, "\tBytes actually used for leaf data: %d (%d%%)\n", s.LeafInuse, percentage)
828
829 fmt.Fprintln(cmd.Stdout, "Bucket statistics")
830 fmt.Fprintf(cmd.Stdout, "\tTotal number of buckets: %d\n", s.BucketN)
831 percentage = 0
832 if s.BucketN != 0 {
833 percentage = int(float32(s.InlineBucketN) * 100.0 / float32(s.BucketN))
834 }
835 fmt.Fprintf(cmd.Stdout, "\tTotal number on inlined buckets: %d (%d%%)\n", s.InlineBucketN, percentage)
836 percentage = 0
837 if s.LeafInuse != 0 {
838 percentage = int(float32(s.InlineBucketInuse) * 100.0 / float32(s.LeafInuse))
839 }
840 fmt.Fprintf(cmd.Stdout, "\tBytes used for inlined buckets: %d (%d%%)\n", s.InlineBucketInuse, percentage)
841
842 return nil
843 })
844 }
845
846 // Usage returns the help message.
847 func (cmd *StatsCommand) Usage() string {
848 return strings.TrimLeft(`
849 usage: bolt stats PATH
850
851 Stats performs an extensive search of the database to track every page
852 reference. It starts at the current meta page and recursively iterates
853 through every accessible bucket.
854
855 The following errors can be reported:
856
857 already freed
858 The page is referenced more than once in the freelist.
859
860 unreachable unfreed
861 The page is not referenced by a bucket or in the freelist.
862
863 reachable freed
864 The page is referenced by a bucket but is also in the freelist.
865
866 out of bounds
867 A page is referenced that is above the high water mark.
868
869 multiple references
870 A page is referenced by more than one other page.
871
872 invalid type
873 The page type is not "meta", "leaf", "branch", or "freelist".
874
875 No errors should occur in your database. However, if for some reason you
876 experience corruption, please submit a ticket to the Bolt project page:
877
878 https://github.com/boltdb/bolt/issues
879 `, "\n")
880 }
881
882 var benchBucketName = []byte("bench")
883
884 // BenchCommand represents the "bench" command execution.
885 type BenchCommand struct {
886 Stdin io.Reader
887 Stdout io.Writer
888 Stderr io.Writer
889 }
890
891 // NewBenchCommand returns a BenchCommand using the
892 func newBenchCommand(m *Main) *BenchCommand {
893 return &BenchCommand{
894 Stdin: m.Stdin,
895 Stdout: m.Stdout,
896 Stderr: m.Stderr,
897 }
898 }
899
900 // Run executes the "bench" command.
901 func (cmd *BenchCommand) Run(args ...string) error {
902 // Parse CLI arguments.
903 options, err := cmd.ParseFlags(args)
904 if err != nil {
905 return err
906 }
907
908 // Remove path if "-work" is not set. Otherwise keep path.
909 if options.Work {
910 fmt.Fprintf(cmd.Stdout, "work: %s\n", options.Path)
911 } else {
912 defer os.Remove(options.Path)
913 }
914
915 // Create database.
916 db, err := bolt.Open(options.Path, 0666, nil)
917 if err != nil {
918 return err
919 }
920 db.NoSync = options.NoSync
921 defer db.Close()
922
923 // Write to the database.
924 var results BenchResults
925 if err := cmd.runWrites(db, options, &results); err != nil {
926 return fmt.Errorf("write: %v", err)
927 }
928
929 // Read from the database.
930 if err := cmd.runReads(db, options, &results); err != nil {
931 return fmt.Errorf("bench: read: %s", err)
932 }
933
934 // Print results.
935 fmt.Fprintf(os.Stderr, "# Write\t%v\t(%v/op)\t(%v op/sec)\n", results.WriteDuration, results.WriteOpDuration(), results.WriteOpsPerSecond())
936 fmt.Fprintf(os.Stderr, "# Read\t%v\t(%v/op)\t(%v op/sec)\n", results.ReadDuration, results.ReadOpDuration(), results.ReadOpsPerSecond())
937 fmt.Fprintln(os.Stderr, "")
938 return nil
939 }
940
941 // ParseFlags parses the command line flags.
942 func (cmd *BenchCommand) ParseFlags(args []string) (*BenchOptions, error) {
943 var options BenchOptions
944
945 // Parse flagset.
946 fs := flag.NewFlagSet("", flag.ContinueOnError)
947 fs.StringVar(&options.ProfileMode, "profile-mode", "rw", "")
948 fs.StringVar(&options.WriteMode, "write-mode", "seq", "")
949 fs.StringVar(&options.ReadMode, "read-mode", "seq", "")
950 fs.IntVar(&options.Iterations, "count", 1000, "")
951 fs.IntVar(&options.BatchSize, "batch-size", 0, "")
952 fs.IntVar(&options.KeySize, "key-size", 8, "")
953 fs.IntVar(&options.ValueSize, "value-size", 32, "")
954 fs.StringVar(&options.CPUProfile, "cpuprofile", "", "")
955 fs.StringVar(&options.MemProfile, "memprofile", "", "")
956 fs.StringVar(&options.BlockProfile, "blockprofile", "", "")
957 fs.Float64Var(&options.FillPercent, "fill-percent", bolt.DefaultFillPercent, "")
958 fs.BoolVar(&options.NoSync, "no-sync", false, "")
959 fs.BoolVar(&options.Work, "work", false, "")
960 fs.StringVar(&options.Path, "path", "", "")
961 fs.SetOutput(cmd.Stderr)
962 if err := fs.Parse(args); err != nil {
963 return nil, err
964 }
965
966 // Set batch size to iteration size if not set.
967 // Require that batch size can be evenly divided by the iteration count.
968 if options.BatchSize == 0 {
969 options.BatchSize = options.Iterations
970 } else if options.Iterations%options.BatchSize != 0 {
971 return nil, ErrNonDivisibleBatchSize
972 }
973
974 // Generate temp path if one is not passed in.
975 if options.Path == "" {
976 f, err := ioutil.TempFile("", "bolt-bench-")
977 if err != nil {
978 return nil, fmt.Errorf("temp file: %s", err)
979 }
980 f.Close()
981 os.Remove(f.Name())
982 options.Path = f.Name()
983 }
984
985 return &options, nil
986 }
987
988 // Writes to the database.
989 func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
990 // Start profiling for writes.
991 if options.ProfileMode == "rw" || options.ProfileMode == "w" {
992 cmd.startProfiling(options)
993 }
994
995 t := time.Now()
996
997 var err error
998 switch options.WriteMode {
999 case "seq":
1000 err = cmd.runWritesSequential(db, options, results)
1001 case "rnd":
1002 err = cmd.runWritesRandom(db, options, results)
1003 case "seq-nest":
1004 err = cmd.runWritesSequentialNested(db, options, results)
1005 case "rnd-nest":
1006 err = cmd.runWritesRandomNested(db, options, results)
1007 default:
1008 return fmt.Errorf("invalid write mode: %s", options.WriteMode)
1009 }
1010
1011 // Save time to write.
1012 results.WriteDuration = time.Since(t)
1013
1014 // Stop profiling for writes only.
1015 if options.ProfileMode == "w" {
1016 cmd.stopProfiling()
1017 }
1018
1019 return err
1020 }
1021
1022 func (cmd *BenchCommand) runWritesSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
1023 var i = uint32(0)
1024 return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i })
1025 }
1026
1027 func (cmd *BenchCommand) runWritesRandom(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
1028 r := rand.New(rand.NewSource(time.Now().UnixNano()))
1029 return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() })
1030 }
1031
1032 func (cmd *BenchCommand) runWritesSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
1033 var i = uint32(0)
1034 return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i })
1035 }
1036
1037 func (cmd *BenchCommand) runWritesRandomNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
1038 r := rand.New(rand.NewSource(time.Now().UnixNano()))
1039 return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() })
1040 }
1041
1042 func (cmd *BenchCommand) runWritesWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error {
1043 results.WriteOps = options.Iterations
1044
1045 for i := 0; i < options.Iterations; i += options.BatchSize {
1046 if err := db.Update(func(tx *bolt.Tx) error {
1047 b, _ := tx.CreateBucketIfNotExists(benchBucketName)
1048 b.FillPercent = options.FillPercent
1049
1050 for j := 0; j < options.BatchSize; j++ {
1051 key := make([]byte, options.KeySize)
1052 value := make([]byte, options.ValueSize)
1053
1054 // Write key as uint32.
1055 binary.BigEndian.PutUint32(key, keySource())
1056
1057 // Insert key/value.
1058 if err := b.Put(key, value); err != nil {
1059 return err
1060 }
1061 }
1062
1063 return nil
1064 }); err != nil {
1065 return err
1066 }
1067 }
1068 return nil
1069 }
1070
1071 func (cmd *BenchCommand) runWritesNestedWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error {
1072 results.WriteOps = options.Iterations
1073
1074 for i := 0; i < options.Iterations; i += options.BatchSize {
1075 if err := db.Update(func(tx *bolt.Tx) error {
1076 top, err := tx.CreateBucketIfNotExists(benchBucketName)
1077 if err != nil {
1078 return err
1079 }
1080 top.FillPercent = options.FillPercent
1081
1082 // Create bucket key.
1083 name := make([]byte, options.KeySize)
1084 binary.BigEndian.PutUint32(name, keySource())
1085
1086 // Create bucket.
1087 b, err := top.CreateBucketIfNotExists(name)
1088 if err != nil {
1089 return err
1090 }
1091 b.FillPercent = options.FillPercent
1092
1093 for j := 0; j < options.BatchSize; j++ {
1094 var key = make([]byte, options.KeySize)
1095 var value = make([]byte, options.ValueSize)
1096
1097 // Generate key as uint32.
1098 binary.BigEndian.PutUint32(key, keySource())
1099
1100 // Insert value into subbucket.
1101 if err := b.Put(key, value); err != nil {
1102 return err
1103 }
1104 }
1105
1106 return nil
1107 }); err != nil {
1108 return err
1109 }
1110 }
1111 return nil
1112 }
1113
1114 // Reads from the database.
1115 func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
1116 // Start profiling for reads.
1117 if options.ProfileMode == "r" {
1118 cmd.startProfiling(options)
1119 }
1120
1121 t := time.Now()
1122
1123 var err error
1124 switch options.ReadMode {
1125 case "seq":
1126 switch options.WriteMode {
1127 case "seq-nest", "rnd-nest":
1128 err = cmd.runReadsSequentialNested(db, options, results)
1129 default:
1130 err = cmd.runReadsSequential(db, options, results)
1131 }
1132 default:
1133 return fmt.Errorf("invalid read mode: %s", options.ReadMode)
1134 }
1135
1136 // Save read time.
1137 results.ReadDuration = time.Since(t)
1138
1139 // Stop profiling for reads.
1140 if options.ProfileMode == "rw" || options.ProfileMode == "r" {
1141 cmd.stopProfiling()
1142 }
1143
1144 return err
1145 }
1146
1147 func (cmd *BenchCommand) runReadsSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
1148 return db.View(func(tx *bolt.Tx) error {
1149 t := time.Now()
1150
1151 for {
1152 var count int
1153
1154 c := tx.Bucket(benchBucketName).Cursor()
1155 for k, v := c.First(); k != nil; k, v = c.Next() {
1156 if v == nil {
1157 return errors.New("invalid value")
1158 }
1159 count++
1160 }
1161
1162 if options.WriteMode == "seq" && count != options.Iterations {
1163 return fmt.Errorf("read seq: iter mismatch: expected %d, got %d", options.Iterations, count)
1164 }
1165
1166 results.ReadOps += count
1167
1168 // Make sure we do this for at least a second.
1169 if time.Since(t) >= time.Second {
1170 break
1171 }
1172 }
1173
1174 return nil
1175 })
1176 }
1177
1178 func (cmd *BenchCommand) runReadsSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
1179 return db.View(func(tx *bolt.Tx) error {
1180 t := time.Now()
1181
1182 for {
1183 var count int
1184 var top = tx.Bucket(benchBucketName)
1185 if err := top.ForEach(func(name, _ []byte) error {
1186 c := top.Bucket(name).Cursor()
1187 for k, v := c.First(); k != nil; k, v = c.Next() {
1188 if v == nil {
1189 return ErrInvalidValue
1190 }
1191 count++
1192 }
1193 return nil
1194 }); err != nil {
1195 return err
1196 }
1197
1198 if options.WriteMode == "seq-nest" && count != options.Iterations {
1199 return fmt.Errorf("read seq-nest: iter mismatch: expected %d, got %d", options.Iterations, count)
1200 }
1201
1202 results.ReadOps += count
1203
1204 // Make sure we do this for at least a second.
1205 if time.Since(t) >= time.Second {
1206 break
1207 }
1208 }
1209
1210 return nil
1211 })
1212 }
1213
1214 // File handlers for the various profiles.
1215 var cpuprofile, memprofile, blockprofile *os.File
1216
1217 // Starts all profiles set on the options.
1218 func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
1219 var err error
1220
1221 // Start CPU profiling.
1222 if options.CPUProfile != "" {
1223 cpuprofile, err = os.Create(options.CPUProfile)
1224 if err != nil {
1225 fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err)
1226 os.Exit(1)
1227 }
1228 pprof.StartCPUProfile(cpuprofile)
1229 }
1230
1231 // Start memory profiling.
1232 if options.MemProfile != "" {
1233 memprofile, err = os.Create(options.MemProfile)
1234 if err != nil {
1235 fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err)
1236 os.Exit(1)
1237 }
1238 runtime.MemProfileRate = 4096
1239 }
1240
1241 // Start fatal profiling.
1242 if options.BlockProfile != "" {
1243 blockprofile, err = os.Create(options.BlockProfile)
1244 if err != nil {
1245 fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err)
1246 os.Exit(1)
1247 }
1248 runtime.SetBlockProfileRate(1)
1249 }
1250 }
1251
1252 // Stops all profiles.
1253 func (cmd *BenchCommand) stopProfiling() {
1254 if cpuprofile != nil {
1255 pprof.StopCPUProfile()
1256 cpuprofile.Close()
1257 cpuprofile = nil
1258 }
1259
1260 if memprofile != nil {
1261 pprof.Lookup("heap").WriteTo(memprofile, 0)
1262 memprofile.Close()
1263 memprofile = nil
1264 }
1265
1266 if blockprofile != nil {
1267 pprof.Lookup("block").WriteTo(blockprofile, 0)
1268 blockprofile.Close()
1269 blockprofile = nil
1270 runtime.SetBlockProfileRate(0)
1271 }
1272 }
1273
1274 // BenchOptions represents the set of options that can be passed to "bolt bench".
1275 type BenchOptions struct {
1276 ProfileMode string
1277 WriteMode string
1278 ReadMode string
1279 Iterations int
1280 BatchSize int
1281 KeySize int
1282 ValueSize int
1283 CPUProfile string
1284 MemProfile string
1285 BlockProfile string
1286 StatsInterval time.Duration
1287 FillPercent float64
1288 NoSync bool
1289 Work bool
1290 Path string
1291 }
1292
1293 // BenchResults represents the performance results of the benchmark.
1294 type BenchResults struct {
1295 WriteOps int
1296 WriteDuration time.Duration
1297 ReadOps int
1298 ReadDuration time.Duration
1299 }
1300
1301 // Returns the duration for a single write operation.
1302 func (r *BenchResults) WriteOpDuration() time.Duration {
1303 if r.WriteOps == 0 {
1304 return 0
1305 }
1306 return r.WriteDuration / time.Duration(r.WriteOps)
1307 }
1308
1309 // Returns average number of write operations that can be performed per second.
1310 func (r *BenchResults) WriteOpsPerSecond() int {
1311 var op = r.WriteOpDuration()
1312 if op == 0 {
1313 return 0
1314 }
1315 return int(time.Second) / int(op)
1316 }
1317
1318 // Returns the duration for a single read operation.
1319 func (r *BenchResults) ReadOpDuration() time.Duration {
1320 if r.ReadOps == 0 {
1321 return 0
1322 }
1323 return r.ReadDuration / time.Duration(r.ReadOps)
1324 }
1325
1326 // Returns average number of read operations that can be performed per second.
1327 func (r *BenchResults) ReadOpsPerSecond() int {
1328 var op = r.ReadOpDuration()
1329 if op == 0 {
1330 return 0
1331 }
1332 return int(time.Second) / int(op)
1333 }
1334
1335 type PageError struct {
1336 ID int
1337 Err error
1338 }
1339
1340 func (e *PageError) Error() string {
1341 return fmt.Sprintf("page error: id=%d, err=%s", e.ID, e.Err)
1342 }
1343
1344 // isPrintable returns true if the string is valid unicode and contains only printable runes.
1345 func isPrintable(s string) bool {
1346 if !utf8.ValidString(s) {
1347 return false
1348 }
1349 for _, ch := range s {
1350 if !unicode.IsPrint(ch) {
1351 return false
1352 }
1353 }
1354 return true
1355 }
1356
1357 // ReadPage reads page info & full page data from a path.
1358 // This is not transactionally safe.
1359 func ReadPage(path string, pageID int) (*page, []byte, error) {
1360 // Find page size.
1361 pageSize, err := ReadPageSize(path)
1362 if err != nil {
1363 return nil, nil, fmt.Errorf("read page size: %s", err)
1364 }
1365
1366 // Open database file.
1367 f, err := os.Open(path)
1368 if err != nil {
1369 return nil, nil, err
1370 }
1371 defer f.Close()
1372
1373 // Read one block into buffer.
1374 buf := make([]byte, pageSize)
1375 if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil {
1376 return nil, nil, err
1377 } else if n != len(buf) {
1378 return nil, nil, io.ErrUnexpectedEOF
1379 }
1380
1381 // Determine total number of blocks.
1382 p := (*page)(unsafe.Pointer(&buf[0]))
1383 overflowN := p.overflow
1384
1385 // Re-read entire page (with overflow) into buffer.
1386 buf = make([]byte, (int(overflowN)+1)*pageSize)
1387 if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil {
1388 return nil, nil, err
1389 } else if n != len(buf) {
1390 return nil, nil, io.ErrUnexpectedEOF
1391 }
1392 p = (*page)(unsafe.Pointer(&buf[0]))
1393
1394 return p, buf, nil
1395 }
1396
1397 // ReadPageSize reads page size a path.
1398 // This is not transactionally safe.
1399 func ReadPageSize(path string) (int, error) {
1400 // Open database file.
1401 f, err := os.Open(path)
1402 if err != nil {
1403 return 0, err
1404 }
1405 defer f.Close()
1406
1407 // Read 4KB chunk.
1408 buf := make([]byte, 4096)
1409 if _, err := io.ReadFull(f, buf); err != nil {
1410 return 0, err
1411 }
1412
1413 // Read page size from metadata.
1414 m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize]))
1415 return int(m.pageSize), nil
1416 }
1417
1418 // atois parses a slice of strings into integers.
1419 func atois(strs []string) ([]int, error) {
1420 var a []int
1421 for _, str := range strs {
1422 i, err := strconv.Atoi(str)
1423 if err != nil {
1424 return nil, err
1425 }
1426 a = append(a, i)
1427 }
1428 return a, nil
1429 }
1430
1431 // DO NOT EDIT. Copied from the "bolt" package.
1432 const maxAllocSize = 0xFFFFFFF
1433
1434 // DO NOT EDIT. Copied from the "bolt" package.
1435 const (
1436 branchPageFlag = 0x01
1437 leafPageFlag = 0x02
1438 metaPageFlag = 0x04
1439 freelistPageFlag = 0x10
1440 )
1441
1442 // DO NOT EDIT. Copied from the "bolt" package.
1443 const bucketLeafFlag = 0x01
1444
1445 // DO NOT EDIT. Copied from the "bolt" package.
1446 type pgid uint64
1447
1448 // DO NOT EDIT. Copied from the "bolt" package.
1449 type txid uint64
1450
1451 // DO NOT EDIT. Copied from the "bolt" package.
1452 type meta struct {
1453 magic uint32
1454 version uint32
1455 pageSize uint32
1456 flags uint32
1457 root bucket
1458 freelist pgid
1459 pgid pgid
1460 txid txid
1461 checksum uint64
1462 }
1463
1464 // DO NOT EDIT. Copied from the "bolt" package.
1465 type bucket struct {
1466 root pgid
1467 sequence uint64
1468 }
1469
1470 // DO NOT EDIT. Copied from the "bolt" package.
1471 type page struct {
1472 id pgid
1473 flags uint16
1474 count uint16
1475 overflow uint32
1476 ptr uintptr
1477 }
1478
1479 // DO NOT EDIT. Copied from the "bolt" package.
1480 func (p *page) Type() string {
1481 if (p.flags & branchPageFlag) != 0 {
1482 return "branch"
1483 } else if (p.flags & leafPageFlag) != 0 {
1484 return "leaf"
1485 } else if (p.flags & metaPageFlag) != 0 {
1486 return "meta"
1487 } else if (p.flags & freelistPageFlag) != 0 {
1488 return "freelist"
1489 }
1490 return fmt.Sprintf("unknown<%02x>", p.flags)
1491 }
1492
1493 // DO NOT EDIT. Copied from the "bolt" package.
1494 func (p *page) leafPageElement(index uint16) *leafPageElement {
1495 n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index]
1496 return n
1497 }
1498
1499 // DO NOT EDIT. Copied from the "bolt" package.
1500 func (p *page) branchPageElement(index uint16) *branchPageElement {
1501 return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index]
1502 }
1503
1504 // DO NOT EDIT. Copied from the "bolt" package.
1505 type branchPageElement struct {
1506 pos uint32
1507 ksize uint32
1508 pgid pgid
1509 }
1510
1511 // DO NOT EDIT. Copied from the "bolt" package.
1512 func (n *branchPageElement) key() []byte {
1513 buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
1514 return buf[n.pos : n.pos+n.ksize]
1515 }
1516
1517 // DO NOT EDIT. Copied from the "bolt" package.
1518 type leafPageElement struct {
1519 flags uint32
1520 pos uint32
1521 ksize uint32
1522 vsize uint32
1523 }
1524
1525 // DO NOT EDIT. Copied from the "bolt" package.
1526 func (n *leafPageElement) key() []byte {
1527 buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
1528 return buf[n.pos : n.pos+n.ksize]
1529 }
1530
1531 // DO NOT EDIT. Copied from the "bolt" package.
1532 func (n *leafPageElement) value() []byte {
1533 buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
1534 return buf[n.pos+n.ksize : n.pos+n.ksize+n.vsize]
1535 }
1536
1537 // CompactCommand represents the "compact" command execution.
1538 type CompactCommand struct {
1539 Stdin io.Reader
1540 Stdout io.Writer
1541 Stderr io.Writer
1542
1543 SrcPath string
1544 DstPath string
1545 TxMaxSize int64
1546 }
1547
1548 // newCompactCommand returns a CompactCommand.
1549 func newCompactCommand(m *Main) *CompactCommand {
1550 return &CompactCommand{
1551 Stdin: m.Stdin,
1552 Stdout: m.Stdout,
1553 Stderr: m.Stderr,
1554 }
1555 }
1556
1557 // Run executes the command.
1558 func (cmd *CompactCommand) Run(args ...string) (err error) {
1559 // Parse flags.
1560 fs := flag.NewFlagSet("", flag.ContinueOnError)
1561 fs.SetOutput(ioutil.Discard)
1562 fs.StringVar(&cmd.DstPath, "o", "", "")
1563 fs.Int64Var(&cmd.TxMaxSize, "tx-max-size", 65536, "")
1564 if err := fs.Parse(args); err == flag.ErrHelp {
1565 fmt.Fprintln(cmd.Stderr, cmd.Usage())
1566 return ErrUsage
1567 } else if err != nil {
1568 return err
1569 } else if cmd.DstPath == "" {
1570 return fmt.Errorf("output file required")
1571 }
1572
1573 // Require database paths.
1574 cmd.SrcPath = fs.Arg(0)
1575 if cmd.SrcPath == "" {
1576 return ErrPathRequired
1577 }
1578
1579 // Ensure source file exists.
1580 fi, err := os.Stat(cmd.SrcPath)
1581 if os.IsNotExist(err) {
1582 return ErrFileNotFound
1583 } else if err != nil {
1584 return err
1585 }
1586 initialSize := fi.Size()
1587
1588 // Open source database.
1589 src, err := bolt.Open(cmd.SrcPath, 0444, nil)
1590 if err != nil {
1591 return err
1592 }
1593 defer src.Close()
1594
1595 // Open destination database.
1596 dst, err := bolt.Open(cmd.DstPath, fi.Mode(), nil)
1597 if err != nil {
1598 return err
1599 }
1600 defer dst.Close()
1601
1602 // Run compaction.
1603 if err := cmd.compact(dst, src); err != nil {
1604 return err
1605 }
1606
1607 // Report stats on new size.
1608 fi, err = os.Stat(cmd.DstPath)
1609 if err != nil {
1610 return err
1611 } else if fi.Size() == 0 {
1612 return fmt.Errorf("zero db size")
1613 }
1614 fmt.Fprintf(cmd.Stdout, "%d -> %d bytes (gain=%.2fx)\n", initialSize, fi.Size(), float64(initialSize)/float64(fi.Size()))
1615
1616 return nil
1617 }
1618
1619 func (cmd *CompactCommand) compact(dst, src *bolt.DB) error {
1620 // commit regularly, or we'll run out of memory for large datasets if using one transaction.
1621 var size int64
1622 tx, err := dst.Begin(true)
1623 if err != nil {
1624 return err
1625 }
1626 defer tx.Rollback()
1627
1628 if err := cmd.walk(src, func(keys [][]byte, k, v []byte, seq uint64) error {
1629 // On each key/value, check if we have exceeded tx size.
1630 sz := int64(len(k) + len(v))
1631 if size+sz > cmd.TxMaxSize && cmd.TxMaxSize != 0 {
1632 // Commit previous transaction.
1633 if err := tx.Commit(); err != nil {
1634 return err
1635 }
1636
1637 // Start new transaction.
1638 tx, err = dst.Begin(true)
1639 if err != nil {
1640 return err
1641 }
1642 size = 0
1643 }
1644 size += sz
1645
1646 // Create bucket on the root transaction if this is the first level.
1647 nk := len(keys)
1648 if nk == 0 {
1649 bkt, err := tx.CreateBucket(k)
1650 if err != nil {
1651 return err
1652 }
1653 if err := bkt.SetSequence(seq); err != nil {
1654 return err
1655 }
1656 return nil
1657 }
1658
1659 // Create buckets on subsequent levels, if necessary.
1660 b := tx.Bucket(keys[0])
1661 if nk > 1 {
1662 for _, k := range keys[1:] {
1663 b = b.Bucket(k)
1664 }
1665 }
1666
1667 // If there is no value then this is a bucket call.
1668 if v == nil {
1669 bkt, err := b.CreateBucket(k)
1670 if err != nil {
1671 return err
1672 }
1673 if err := bkt.SetSequence(seq); err != nil {
1674 return err
1675 }
1676 return nil
1677 }
1678
1679 // Otherwise treat it as a key/value pair.
1680 return b.Put(k, v)
1681 }); err != nil {
1682 return err
1683 }
1684
1685 return tx.Commit()
1686 }
1687
1688 // walkFunc is the type of the function called for keys (buckets and "normal"
1689 // values) discovered by Walk. keys is the list of keys to descend to the bucket
1690 // owning the discovered key/value pair k/v.
1691 type walkFunc func(keys [][]byte, k, v []byte, seq uint64) error
1692
1693 // walk walks recursively the bolt database db, calling walkFn for each key it finds.
1694 func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error {
1695 return db.View(func(tx *bolt.Tx) error {
1696 return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
1697 return cmd.walkBucket(b, nil, name, nil, b.Sequence(), walkFn)
1698 })
1699 })
1700 }
1701
1702 func (cmd *CompactCommand) walkBucket(b *bolt.Bucket, keypath [][]byte, k, v []byte, seq uint64, fn walkFunc) error {
1703 // Execute callback.
1704 if err := fn(keypath, k, v, seq); err != nil {
1705 return err
1706 }
1707
1708 // If this is not a bucket then stop.
1709 if v != nil {
1710 return nil
1711 }
1712
1713 // Iterate over each child key/value.
1714 keypath = append(keypath, k)
1715 return b.ForEach(func(k, v []byte) error {
1716 if v == nil {
1717 bkt := b.Bucket(k)
1718 return cmd.walkBucket(bkt, keypath, k, nil, bkt.Sequence(), fn)
1719 }
1720 return cmd.walkBucket(b, keypath, k, v, b.Sequence(), fn)
1721 })
1722 }
1723
1724 // Usage returns the help message.
1725 func (cmd *CompactCommand) Usage() string {
1726 return strings.TrimLeft(`
1727 usage: bolt compact [options] -o DST SRC
1728
1729 Compact opens a database at SRC path and walks it recursively, copying keys
1730 as they are found from all buckets, to a newly created database at DST path.
1731
1732 The original database is left untouched.
1733
1734 Additional options include:
1735
1736 -tx-max-size NUM
1737 Specifies the maximum size of individual transactions.
1738 Defaults to 64KB.
1739 `, "\n")
1740 }