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.

192 lines
6.2 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
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",
  94. *tailTarget, time.Now().Add(-*tailStart).UnixNano(), 0,
  95. func(resp *filer_pb.SubscribeMetadataResponse) error {
  96. if !shouldPrint(resp) {
  97. return nil
  98. }
  99. if err := eachEntryFunc(resp); err != nil {
  100. return err
  101. }
  102. return nil
  103. }, false)
  104. if tailErr != nil {
  105. fmt.Printf("tail %s: %v\n", *tailFiler, tailErr)
  106. }
  107. return true
  108. }
  109. type EsDocument struct {
  110. Dir string `json:"dir,omitempty"`
  111. Name string `json:"name,omitempty"`
  112. IsDirectory bool `json:"isDir,omitempty"`
  113. Size uint64 `json:"size,omitempty"`
  114. Uid uint32 `json:"uid,omitempty"`
  115. Gid uint32 `json:"gid,omitempty"`
  116. UserName string `json:"userName,omitempty"`
  117. Collection string `json:"collection,omitempty"`
  118. Crtime int64 `json:"crtime,omitempty"`
  119. Mtime int64 `json:"mtime,omitempty"`
  120. Mime string `json:"mime,omitempty"`
  121. }
  122. func toEsEntry(event *filer_pb.EventNotification) (*EsDocument, string) {
  123. entry := event.NewEntry
  124. dir, name := event.NewParentPath, entry.Name
  125. id := util.Md5String([]byte(util.NewFullPath(dir, name)))
  126. esEntry := &EsDocument{
  127. Dir: dir,
  128. Name: name,
  129. IsDirectory: entry.IsDirectory,
  130. Size: entry.Attributes.FileSize,
  131. Uid: entry.Attributes.Uid,
  132. Gid: entry.Attributes.Gid,
  133. UserName: entry.Attributes.UserName,
  134. Collection: entry.Attributes.Collection,
  135. Crtime: entry.Attributes.Crtime,
  136. Mtime: entry.Attributes.Mtime,
  137. Mime: entry.Attributes.Mime,
  138. }
  139. return esEntry, id
  140. }
  141. func sendToElasticSearchFunc(servers string, esIndex string) (func(resp *filer_pb.SubscribeMetadataResponse) error, error) {
  142. options := []elastic.ClientOptionFunc{}
  143. options = append(options, elastic.SetURL(strings.Split(servers, ",")...))
  144. options = append(options, elastic.SetSniff(false))
  145. options = append(options, elastic.SetHealthcheck(false))
  146. client, err := elastic.NewClient(options...)
  147. if err != nil {
  148. return nil, err
  149. }
  150. return func(resp *filer_pb.SubscribeMetadataResponse) error {
  151. event := resp.EventNotification
  152. if event.OldEntry != nil &&
  153. (event.NewEntry == nil || resp.Directory != event.NewParentPath || event.OldEntry.Name != event.NewEntry.Name) {
  154. // delete or not update the same file
  155. dir, name := resp.Directory, event.OldEntry.Name
  156. id := util.Md5String([]byte(util.NewFullPath(dir, name)))
  157. println("delete", id)
  158. _, err := client.Delete().Index(esIndex).Id(id).Do(context.Background())
  159. return err
  160. }
  161. if event.NewEntry != nil {
  162. // add a new file or update the same file
  163. esEntry, id := toEsEntry(event)
  164. value, err := jsoniter.Marshal(esEntry)
  165. if err != nil {
  166. return err
  167. }
  168. println(string(value))
  169. _, err = client.Index().Index(esIndex).Id(id).BodyJson(string(value)).Do(context.Background())
  170. return err
  171. }
  172. return nil
  173. }, nil
  174. }