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.

261 lines
7.3 KiB

6 years ago
12 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
12 years ago
6 years ago
  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. defer needleMap.Close()
  173. if err := needleMap.LoadFromIdx(path.Join(*export.dir, fileName+".idx")); err != nil {
  174. glog.Fatalf("cannot load needle map from %s.idx: %s", fileName, err)
  175. }
  176. volumeFileScanner := &VolumeFileScanner4Export{
  177. needleMap: needleMap,
  178. vid: vid,
  179. }
  180. if tarOutputFile == nil {
  181. fmt.Printf("key\tname\tsize\tgzip\tmime\tmodified\tttl\tdeleted\n")
  182. }
  183. err = storage.ScanVolumeFile(*export.dir, *export.collection, vid, storage.NeedleMapInMemory, volumeFileScanner)
  184. if err != nil && err != io.EOF {
  185. glog.Fatalf("Export Volume File [ERROR] %s\n", err)
  186. }
  187. return true
  188. }
  189. type nameParams struct {
  190. Name string
  191. Id types.NeedleId
  192. Mime string
  193. Key string
  194. Ext string
  195. }
  196. func writeFile(vid needle.VolumeId, n *needle.Needle) (err error) {
  197. key := needle.NewFileIdFromNeedle(vid, n).String()
  198. fileNameTemplateBuffer.Reset()
  199. if err = fileNameTemplate.Execute(fileNameTemplateBuffer,
  200. nameParams{
  201. Name: string(n.Name),
  202. Id: n.Id,
  203. Mime: string(n.Mime),
  204. Key: key,
  205. Ext: filepath.Ext(string(n.Name)),
  206. },
  207. ); err != nil {
  208. return err
  209. }
  210. fileName := fileNameTemplateBuffer.String()
  211. if n.IsGzipped() && path.Ext(fileName) != ".gz" {
  212. fileName = fileName + ".gz"
  213. }
  214. tarHeader.Name, tarHeader.Size = fileName, int64(len(n.Data))
  215. if n.HasLastModifiedDate() {
  216. tarHeader.ModTime = time.Unix(int64(n.LastModified), 0)
  217. } else {
  218. tarHeader.ModTime = time.Unix(0, 0)
  219. }
  220. tarHeader.ChangeTime = tarHeader.ModTime
  221. if err = tarOutputFile.WriteHeader(&tarHeader); err != nil {
  222. return err
  223. }
  224. _, err = tarOutputFile.Write(n.Data)
  225. return
  226. }