export.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package command
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "text/template"
  13. "time"
  14. "github.com/chrislusf/seaweedfs/weed/glog"
  15. "github.com/chrislusf/seaweedfs/weed/storage"
  16. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  17. "github.com/chrislusf/seaweedfs/weed/storage/needle_map"
  18. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  19. "github.com/chrislusf/seaweedfs/weed/storage/types"
  20. )
  21. const (
  22. defaultFnFormat = `{{.Mime}}/{{.Id}}:{{.Name}}`
  23. timeFormat = "2006-01-02T15:04:05"
  24. )
  25. var (
  26. export ExportOptions
  27. )
  28. type ExportOptions struct {
  29. dir *string
  30. collection *string
  31. volumeId *int
  32. }
  33. var cmdExport = &Command{
  34. UsageLine: "export -dir=/tmp -volumeId=234 -o=/dir/name.tar -fileNameFormat={{.Name}} -newer='" + timeFormat + "'",
  35. Short: "list or export files from one volume data file",
  36. Long: `List all files in a volume, or Export all files in a volume to a tar file if the output is specified.
  37. The format of file name in the tar file can be customized. Default is {{.Mime}}/{{.Id}}:{{.Name}}. Also available is {{.Key}}.
  38. `,
  39. }
  40. func init() {
  41. cmdExport.Run = runExport // break init cycle
  42. export.dir = cmdExport.Flag.String("dir", ".", "input data directory to store volume data files")
  43. export.collection = cmdExport.Flag.String("collection", "", "the volume collection name")
  44. export.volumeId = cmdExport.Flag.Int("volumeId", -1, "a volume id. The volume .dat and .idx files should already exist in the dir.")
  45. }
  46. var (
  47. output = cmdExport.Flag.String("o", "", "output tar file name, must ends with .tar, or just a \"-\" for stdout")
  48. format = cmdExport.Flag.String("fileNameFormat", defaultFnFormat, "filename formatted with {{.Mime}} {{.Id}} {{.Name}} {{.Ext}}")
  49. newer = cmdExport.Flag.String("newer", "", "export only files newer than this time, default is all files. Must be specified in RFC3339 without timezone, e.g. 2006-01-02T15:04:05")
  50. showDeleted = cmdExport.Flag.Bool("deleted", false, "export deleted files. only applies if -o is not specified")
  51. limit = cmdExport.Flag.Int("limit", 0, "only show first n entries if specified")
  52. tarOutputFile *tar.Writer
  53. tarHeader tar.Header
  54. fileNameTemplate *template.Template
  55. fileNameTemplateBuffer = bytes.NewBuffer(nil)
  56. newerThan time.Time
  57. newerThanUnix int64 = -1
  58. localLocation, _ = time.LoadLocation("Local")
  59. )
  60. func printNeedle(vid needle.VolumeId, n *needle.Needle, version needle.Version, deleted bool) {
  61. key := needle.NewFileIdFromNeedle(vid, n).String()
  62. size := n.DataSize
  63. if version == needle.Version1 {
  64. size = n.Size
  65. }
  66. fmt.Printf("%s\t%s\t%d\t%t\t%s\t%s\t%s\t%t\n",
  67. key,
  68. n.Name,
  69. size,
  70. n.IsGzipped(),
  71. n.Mime,
  72. n.LastModifiedString(),
  73. n.Ttl.String(),
  74. deleted,
  75. )
  76. }
  77. type VolumeFileScanner4Export struct {
  78. version needle.Version
  79. counter int
  80. needleMap *needle_map.MemDb
  81. vid needle.VolumeId
  82. }
  83. func (scanner *VolumeFileScanner4Export) VisitSuperBlock(superBlock super_block.SuperBlock) error {
  84. scanner.version = superBlock.Version
  85. return nil
  86. }
  87. func (scanner *VolumeFileScanner4Export) ReadNeedleBody() bool {
  88. return true
  89. }
  90. func (scanner *VolumeFileScanner4Export) VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error {
  91. needleMap := scanner.needleMap
  92. vid := scanner.vid
  93. nv, ok := needleMap.Get(n.Id)
  94. glog.V(3).Infof("key %d offset %d size %d disk_size %d gzip %v ok %v nv %+v",
  95. n.Id, offset, n.Size, n.DiskSize(scanner.version), n.IsGzipped(), ok, nv)
  96. if ok && nv.Size > 0 && nv.Size != types.TombstoneFileSize && nv.Offset.ToAcutalOffset() == offset {
  97. if newerThanUnix >= 0 && n.HasLastModifiedDate() && n.LastModified < uint64(newerThanUnix) {
  98. glog.V(3).Infof("Skipping this file, as it's old enough: LastModified %d vs %d",
  99. n.LastModified, newerThanUnix)
  100. return nil
  101. }
  102. scanner.counter++
  103. if *limit > 0 && scanner.counter > *limit {
  104. return io.EOF
  105. }
  106. if tarOutputFile != nil {
  107. return writeFile(vid, n)
  108. } else {
  109. printNeedle(vid, n, scanner.version, false)
  110. return nil
  111. }
  112. }
  113. if !ok {
  114. if *showDeleted && tarOutputFile == nil {
  115. if n.DataSize > 0 {
  116. printNeedle(vid, n, scanner.version, true)
  117. } else {
  118. n.Name = []byte("*tombstone")
  119. printNeedle(vid, n, scanner.version, true)
  120. }
  121. }
  122. glog.V(2).Infof("This seems deleted %d size %d", n.Id, n.Size)
  123. } else {
  124. glog.V(2).Infof("Skipping later-updated Id %d size %d", n.Id, n.Size)
  125. }
  126. return nil
  127. }
  128. func runExport(cmd *Command, args []string) bool {
  129. var err error
  130. if *newer != "" {
  131. if newerThan, err = time.ParseInLocation(timeFormat, *newer, localLocation); err != nil {
  132. fmt.Println("cannot parse 'newer' argument: " + err.Error())
  133. return false
  134. }
  135. newerThanUnix = newerThan.Unix()
  136. }
  137. if *export.volumeId == -1 {
  138. return false
  139. }
  140. if *output != "" {
  141. if *output != "-" && !strings.HasSuffix(*output, ".tar") {
  142. fmt.Println("the output file", *output, "should be '-' or end with .tar")
  143. return false
  144. }
  145. if fileNameTemplate, err = template.New("name").Parse(*format); err != nil {
  146. fmt.Println("cannot parse format " + *format + ": " + err.Error())
  147. return false
  148. }
  149. var outputFile *os.File
  150. if *output == "-" {
  151. outputFile = os.Stdout
  152. } else {
  153. if outputFile, err = os.Create(*output); err != nil {
  154. glog.Fatalf("cannot open output tar %s: %s", *output, err)
  155. }
  156. }
  157. defer outputFile.Close()
  158. tarOutputFile = tar.NewWriter(outputFile)
  159. defer tarOutputFile.Close()
  160. t := time.Now()
  161. tarHeader = tar.Header{Mode: 0644,
  162. ModTime: t, Uid: os.Getuid(), Gid: os.Getgid(),
  163. Typeflag: tar.TypeReg,
  164. AccessTime: t, ChangeTime: t}
  165. }
  166. fileName := strconv.Itoa(*export.volumeId)
  167. if *export.collection != "" {
  168. fileName = *export.collection + "_" + fileName
  169. }
  170. vid := needle.VolumeId(*export.volumeId)
  171. needleMap := needle_map.NewMemDb()
  172. if err := needleMap.LoadFromIdx(path.Join(*export.dir, fileName+".idx")); err != nil {
  173. glog.Fatalf("cannot load needle map from %s.idx: %s", fileName, err)
  174. }
  175. volumeFileScanner := &VolumeFileScanner4Export{
  176. needleMap: needleMap,
  177. vid: vid,
  178. }
  179. if tarOutputFile == nil {
  180. fmt.Printf("key\tname\tsize\tgzip\tmime\tmodified\tttl\tdeleted\n")
  181. }
  182. err = storage.ScanVolumeFile(*export.dir, *export.collection, vid, storage.NeedleMapInMemory, volumeFileScanner)
  183. if err != nil && err != io.EOF {
  184. glog.Fatalf("Export Volume File [ERROR] %s\n", err)
  185. }
  186. return true
  187. }
  188. type nameParams struct {
  189. Name string
  190. Id types.NeedleId
  191. Mime string
  192. Key string
  193. Ext string
  194. }
  195. func writeFile(vid needle.VolumeId, n *needle.Needle) (err error) {
  196. key := needle.NewFileIdFromNeedle(vid, n).String()
  197. fileNameTemplateBuffer.Reset()
  198. if err = fileNameTemplate.Execute(fileNameTemplateBuffer,
  199. nameParams{
  200. Name: string(n.Name),
  201. Id: n.Id,
  202. Mime: string(n.Mime),
  203. Key: key,
  204. Ext: filepath.Ext(string(n.Name)),
  205. },
  206. ); err != nil {
  207. return err
  208. }
  209. fileName := fileNameTemplateBuffer.String()
  210. if n.IsGzipped() && path.Ext(fileName) != ".gz" {
  211. fileName = fileName + ".gz"
  212. }
  213. tarHeader.Name, tarHeader.Size = fileName, int64(len(n.Data))
  214. if n.HasLastModifiedDate() {
  215. tarHeader.ModTime = time.Unix(int64(n.LastModified), 0)
  216. } else {
  217. tarHeader.ModTime = time.Unix(0, 0)
  218. }
  219. tarHeader.ChangeTime = tarHeader.ModTime
  220. if err = tarOutputFile.WriteHeader(&tarHeader); err != nil {
  221. return err
  222. }
  223. _, err = tarOutputFile.Write(n.Data)
  224. return
  225. }