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

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