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.

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