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.

190 lines
6.1 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package command
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/pb"
  6. "github.com/golang/protobuf/jsonpb"
  7. jsoniter "github.com/json-iterator/go"
  8. "github.com/olivere/elastic/v7"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. "github.com/chrislusf/seaweedfs/weed/security"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. )
  17. func init() {
  18. cmdFilerMetaTail.Run = runFilerMetaTail // break init cycle
  19. }
  20. var cmdFilerMetaTail = &Command{
  21. UsageLine: "filer.meta.tail [-filer=localhost:8888] [-pathPrefix=/]",
  22. Short: "see continuous changes on a filer",
  23. Long: `See continuous changes on a filer.
  24. weed filer.meta.tail -timeAgo=30h | grep truncate
  25. weed filer.meta.tail -timeAgo=30h | jq .
  26. weed filer.meta.tail -timeAgo=30h | jq .eventNotification.newEntry.name
  27. `,
  28. }
  29. var (
  30. tailFiler = cmdFilerMetaTail.Flag.String("filer", "localhost:8888", "filer hostname:port")
  31. tailTarget = cmdFilerMetaTail.Flag.String("pathPrefix", "/", "path to a folder or common prefix for the folders or files on filer")
  32. tailStart = cmdFilerMetaTail.Flag.Duration("timeAgo", 0, "start time before now. \"300ms\", \"1.5h\" or \"2h45m\". Valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\"")
  33. tailPattern = cmdFilerMetaTail.Flag.String("pattern", "", "full path or just filename pattern, ex: \"/home/?opher\", \"*.pdf\", see https://golang.org/pkg/path/filepath/#Match ")
  34. esServers = cmdFilerMetaTail.Flag.String("es", "", "comma-separated elastic servers http://<host:port>")
  35. esIndex = cmdFilerMetaTail.Flag.String("es.index", "seaweedfs", "ES index name")
  36. )
  37. func runFilerMetaTail(cmd *Command, args []string) bool {
  38. util.LoadConfiguration("security", false)
  39. grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
  40. var filterFunc func(dir, fname string) bool
  41. if *tailPattern != "" {
  42. if strings.Contains(*tailPattern, "/") {
  43. println("watch path pattern", *tailPattern)
  44. filterFunc = func(dir, fname string) bool {
  45. matched, err := filepath.Match(*tailPattern, dir+"/"+fname)
  46. if err != nil {
  47. fmt.Printf("error: %v", err)
  48. }
  49. return matched
  50. }
  51. } else {
  52. println("watch file pattern", *tailPattern)
  53. filterFunc = func(dir, fname string) bool {
  54. matched, err := filepath.Match(*tailPattern, fname)
  55. if err != nil {
  56. fmt.Printf("error: %v", err)
  57. }
  58. return matched
  59. }
  60. }
  61. }
  62. shouldPrint := func(resp *filer_pb.SubscribeMetadataResponse) bool {
  63. if filterFunc == nil {
  64. return true
  65. }
  66. if resp.EventNotification.OldEntry == nil && resp.EventNotification.NewEntry == nil {
  67. return false
  68. }
  69. if resp.EventNotification.OldEntry != nil && filterFunc(resp.Directory, resp.EventNotification.OldEntry.Name) {
  70. return true
  71. }
  72. if resp.EventNotification.NewEntry != nil && filterFunc(resp.EventNotification.NewParentPath, resp.EventNotification.NewEntry.Name) {
  73. return true
  74. }
  75. return false
  76. }
  77. jsonpbMarshaler := jsonpb.Marshaler{
  78. EmitDefaults: false,
  79. }
  80. eachEntryFunc := func(resp *filer_pb.SubscribeMetadataResponse) error {
  81. jsonpbMarshaler.Marshal(os.Stdout, resp)
  82. fmt.Fprintln(os.Stdout)
  83. return nil
  84. }
  85. if *esServers != "" {
  86. var err error
  87. eachEntryFunc, err = sendToElasticSearchFunc(*esServers, *esIndex)
  88. if err != nil {
  89. fmt.Printf("create elastic search client to %s: %+v\n", *esServers, err)
  90. return false
  91. }
  92. }
  93. tailErr := pb.FollowMetadata(*tailFiler, grpcDialOption, "tail", *tailTarget, nil, time.Now().Add(-*tailStart).UnixNano(), 0, func(resp *filer_pb.SubscribeMetadataResponse) error {
  94. if !shouldPrint(resp) {
  95. return nil
  96. }
  97. if err := eachEntryFunc(resp); err != nil {
  98. return err
  99. }
  100. return nil
  101. }, false)
  102. if tailErr != nil {
  103. fmt.Printf("tail %s: %v\n", *tailFiler, tailErr)
  104. }
  105. return true
  106. }
  107. type EsDocument struct {
  108. Dir string `json:"dir,omitempty"`
  109. Name string `json:"name,omitempty"`
  110. IsDirectory bool `json:"isDir,omitempty"`
  111. Size uint64 `json:"size,omitempty"`
  112. Uid uint32 `json:"uid,omitempty"`
  113. Gid uint32 `json:"gid,omitempty"`
  114. UserName string `json:"userName,omitempty"`
  115. Collection string `json:"collection,omitempty"`
  116. Crtime int64 `json:"crtime,omitempty"`
  117. Mtime int64 `json:"mtime,omitempty"`
  118. Mime string `json:"mime,omitempty"`
  119. }
  120. func toEsEntry(event *filer_pb.EventNotification) (*EsDocument, string) {
  121. entry := event.NewEntry
  122. dir, name := event.NewParentPath, entry.Name
  123. id := util.Md5String([]byte(util.NewFullPath(dir, name)))
  124. esEntry := &EsDocument{
  125. Dir: dir,
  126. Name: name,
  127. IsDirectory: entry.IsDirectory,
  128. Size: entry.Attributes.FileSize,
  129. Uid: entry.Attributes.Uid,
  130. Gid: entry.Attributes.Gid,
  131. UserName: entry.Attributes.UserName,
  132. Collection: entry.Attributes.Collection,
  133. Crtime: entry.Attributes.Crtime,
  134. Mtime: entry.Attributes.Mtime,
  135. Mime: entry.Attributes.Mime,
  136. }
  137. return esEntry, id
  138. }
  139. func sendToElasticSearchFunc(servers string, esIndex string) (func(resp *filer_pb.SubscribeMetadataResponse) error, error) {
  140. options := []elastic.ClientOptionFunc{}
  141. options = append(options, elastic.SetURL(strings.Split(servers, ",")...))
  142. options = append(options, elastic.SetSniff(false))
  143. options = append(options, elastic.SetHealthcheck(false))
  144. client, err := elastic.NewClient(options...)
  145. if err != nil {
  146. return nil, err
  147. }
  148. return func(resp *filer_pb.SubscribeMetadataResponse) error {
  149. event := resp.EventNotification
  150. if event.OldEntry != nil &&
  151. (event.NewEntry == nil || resp.Directory != event.NewParentPath || event.OldEntry.Name != event.NewEntry.Name) {
  152. // delete or not update the same file
  153. dir, name := resp.Directory, event.OldEntry.Name
  154. id := util.Md5String([]byte(util.NewFullPath(dir, name)))
  155. println("delete", id)
  156. _, err := client.Delete().Index(esIndex).Id(id).Do(context.Background())
  157. return err
  158. }
  159. if event.NewEntry != nil {
  160. // add a new file or update the same file
  161. esEntry, id := toEsEntry(event)
  162. value, err := jsoniter.Marshal(esEntry)
  163. if err != nil {
  164. return err
  165. }
  166. println(string(value))
  167. _, err = client.Index().Index(esIndex).Id(id).BodyJson(string(value)).Do(context.Background())
  168. return err
  169. }
  170. return nil
  171. }, nil
  172. }