filer_meta_tail.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package command
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/golang/protobuf/jsonpb"
  6. jsoniter "github.com/json-iterator/go"
  7. "github.com/olivere/elastic/v7"
  8. "io"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "github.com/chrislusf/seaweedfs/weed/pb"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "github.com/chrislusf/seaweedfs/weed/security"
  16. "github.com/chrislusf/seaweedfs/weed/util"
  17. )
  18. func init() {
  19. cmdFilerMetaTail.Run = runFilerMetaTail // break init cycle
  20. }
  21. var cmdFilerMetaTail = &Command{
  22. UsageLine: "filer.meta.tail [-filer=localhost:8888] [-pathPrefix=/]",
  23. Short: "see continuous changes on a filer",
  24. Long: `See continuous changes on a filer.
  25. weed filer.meta.tail -timeAgo=30h | grep truncate
  26. weed filer.meta.tail -timeAgo=30h | jq .
  27. weed filer.meta.tail -timeAgo=30h | jq .eventNotification.newEntry.name
  28. `,
  29. }
  30. var (
  31. tailFiler = cmdFilerMetaTail.Flag.String("filer", "localhost:8888", "filer hostname:port")
  32. tailTarget = cmdFilerMetaTail.Flag.String("pathPrefix", "/", "path to a folder or common prefix for the folders or files on filer")
  33. 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\"")
  34. tailPattern = cmdFilerMetaTail.Flag.String("pattern", "", "full path or just filename pattern, ex: \"/home/?opher\", \"*.pdf\", see https://golang.org/pkg/path/filepath/#Match ")
  35. esServers = cmdFilerMetaTail.Flag.String("es", "", "comma-separated elastic servers http://<host:port>")
  36. esIndex = cmdFilerMetaTail.Flag.String("es.index", "seaweedfs", "ES index name")
  37. )
  38. func runFilerMetaTail(cmd *Command, args []string) bool {
  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.WithFilerClient(*tailFiler, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  94. ctx, cancel := context.WithCancel(context.Background())
  95. defer cancel()
  96. stream, err := client.SubscribeMetadata(ctx, &filer_pb.SubscribeMetadataRequest{
  97. ClientName: "tail",
  98. PathPrefix: *tailTarget,
  99. SinceNs: time.Now().Add(-*tailStart).UnixNano(),
  100. })
  101. if err != nil {
  102. return fmt.Errorf("listen: %v", err)
  103. }
  104. for {
  105. resp, listenErr := stream.Recv()
  106. if listenErr == io.EOF {
  107. return nil
  108. }
  109. if listenErr != nil {
  110. return listenErr
  111. }
  112. if !shouldPrint(resp) {
  113. continue
  114. }
  115. if err = eachEntryFunc(resp); err != nil {
  116. return err
  117. }
  118. }
  119. })
  120. if tailErr != nil {
  121. fmt.Printf("tail %s: %v\n", *tailFiler, tailErr)
  122. }
  123. return true
  124. }
  125. type EsDocument struct {
  126. Dir string `json:"dir,omitempty"`
  127. Name string `json:"name,omitempty"`
  128. IsDirectory bool `json:"isDir,omitempty"`
  129. Size uint64 `json:"size,omitempty"`
  130. Uid uint32 `json:"uid,omitempty"`
  131. Gid uint32 `json:"gid,omitempty"`
  132. UserName string `json:"userName,omitempty"`
  133. Collection string `json:"collection,omitempty"`
  134. Crtime int64 `json:"crtime,omitempty"`
  135. Mtime int64 `json:"mtime,omitempty"`
  136. Mime string `json:"mime,omitempty"`
  137. }
  138. func toEsEntry(event *filer_pb.EventNotification) (*EsDocument, string) {
  139. entry := event.NewEntry
  140. dir, name := event.NewParentPath, entry.Name
  141. id := util.Md5String([]byte(util.NewFullPath(dir, name)))
  142. esEntry := &EsDocument{
  143. Dir: dir,
  144. Name: name,
  145. IsDirectory: entry.IsDirectory,
  146. Size: entry.Attributes.FileSize,
  147. Uid: entry.Attributes.Uid,
  148. Gid: entry.Attributes.Gid,
  149. UserName: entry.Attributes.UserName,
  150. Collection: entry.Attributes.Collection,
  151. Crtime: entry.Attributes.Crtime,
  152. Mtime: entry.Attributes.Mtime,
  153. Mime: entry.Attributes.Mime,
  154. }
  155. return esEntry, id
  156. }
  157. func sendToElasticSearchFunc(servers string, esIndex string) (func(resp *filer_pb.SubscribeMetadataResponse) error, error) {
  158. options := []elastic.ClientOptionFunc{}
  159. options = append(options, elastic.SetURL(strings.Split(servers, ",")...))
  160. options = append(options, elastic.SetSniff(false))
  161. options = append(options, elastic.SetHealthcheck(false))
  162. client, err := elastic.NewClient(options...)
  163. if err != nil {
  164. return nil, err
  165. }
  166. return func(resp *filer_pb.SubscribeMetadataResponse) error {
  167. event := resp.EventNotification
  168. if event.OldEntry != nil &&
  169. (event.NewEntry == nil || resp.Directory != event.NewParentPath || event.OldEntry.Name != event.NewEntry.Name) {
  170. // delete or not update the same file
  171. dir, name := resp.Directory, event.OldEntry.Name
  172. id := util.Md5String([]byte(util.NewFullPath(dir, name)))
  173. println("delete", id)
  174. _, err := client.Delete().Index(esIndex).Id(id).Do(context.Background())
  175. return err
  176. }
  177. if event.NewEntry != nil {
  178. // add a new file or update the same file
  179. esEntry, id := toEsEntry(event)
  180. value, err := jsoniter.Marshal(esEntry)
  181. if err != nil {
  182. return err
  183. }
  184. println(string(value))
  185. _, err = client.Index().Index(esIndex).Id(id).BodyJson(string(value)).Do(context.Background())
  186. return err
  187. }
  188. return nil
  189. }, nil
  190. }