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.

265 lines
7.5 KiB

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