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.

398 lines
14 KiB

  1. package command
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/seaweedfs/weed/filer"
  5. "github.com/chrislusf/seaweedfs/weed/glog"
  6. "github.com/chrislusf/seaweedfs/weed/pb"
  7. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  8. "github.com/chrislusf/seaweedfs/weed/pb/remote_pb"
  9. "github.com/chrislusf/seaweedfs/weed/remote_storage"
  10. "github.com/chrislusf/seaweedfs/weed/replication/source"
  11. "github.com/chrislusf/seaweedfs/weed/util"
  12. "github.com/golang/protobuf/proto"
  13. "math"
  14. "math/rand"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. )
  19. func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSource *source.FilerSource) error {
  20. // read filer remote storage mount mappings
  21. if detectErr := option.collectRemoteStorageConf(); detectErr != nil {
  22. return fmt.Errorf("read mount info: %v", detectErr)
  23. }
  24. eachEntryFunc, err := option.makeBucketedEventProcessor(filerSource)
  25. if err != nil {
  26. return err
  27. }
  28. processEventFnWithOffset := pb.AddOffsetFunc(eachEntryFunc, 3*time.Second, func(counter int64, lastTsNs int64) error {
  29. lastTime := time.Unix(0, lastTsNs)
  30. glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, lastTime, float64(counter)/float64(3))
  31. return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, lastTsNs)
  32. })
  33. lastOffsetTs := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, *option.timeAgo)
  34. return pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, "filer.remote.sync",
  35. option.bucketsDir, []string{filer.DirectoryEtcRemote}, lastOffsetTs.UnixNano(), 0, processEventFnWithOffset, false)
  36. }
  37. func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *source.FilerSource) (pb.ProcessMetadataFunc, error) {
  38. handleCreateBucket := func(entry *filer_pb.Entry) error {
  39. if !entry.IsDirectory {
  40. return nil
  41. }
  42. if entry.RemoteEntry != nil {
  43. // this directory is imported from "remote.mount.buckets" or "remote.mount"
  44. return nil
  45. }
  46. if option.mappings.PrimaryBucketStorageName != "" && *option.createBucketAt == "" {
  47. *option.createBucketAt = option.mappings.PrimaryBucketStorageName
  48. glog.V(0).Infof("%s is set as the primary remote storage", *option.createBucketAt)
  49. }
  50. if len(option.mappings.Mappings) == 1 && *option.createBucketAt == "" {
  51. for k := range option.mappings.Mappings {
  52. *option.createBucketAt = k
  53. glog.V(0).Infof("%s is set as the only remote storage", *option.createBucketAt)
  54. }
  55. }
  56. if *option.createBucketAt == "" {
  57. return nil
  58. }
  59. remoteConf, found := option.remoteConfs[*option.createBucketAt]
  60. if !found {
  61. return fmt.Errorf("un-configured remote storage %s", *option.createBucketAt)
  62. }
  63. client, err := remote_storage.GetRemoteStorage(remoteConf)
  64. if err != nil {
  65. return err
  66. }
  67. bucketName := strings.ToLower(entry.Name)
  68. if *option.include != "" {
  69. if ok, _ := filepath.Match(*option.include, entry.Name); !ok {
  70. return nil
  71. }
  72. }
  73. if *option.exclude != "" {
  74. if ok, _ := filepath.Match(*option.exclude, entry.Name); ok {
  75. return nil
  76. }
  77. }
  78. if *option.createBucketRandomSuffix {
  79. // https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html
  80. if len(bucketName)+5 > 63 {
  81. bucketName = bucketName[:58]
  82. }
  83. bucketName = fmt.Sprintf("%s-%4d", bucketName, rand.Uint32()%10000)
  84. }
  85. glog.V(0).Infof("create bucket %s", bucketName)
  86. if err := client.CreateBucket(bucketName); err != nil {
  87. return fmt.Errorf("create bucket %s in %s: %v", bucketName, remoteConf.Name, err)
  88. }
  89. bucketPath := util.FullPath(option.bucketsDir).Child(entry.Name)
  90. remoteLocation := &remote_pb.RemoteStorageLocation{
  91. Name: *option.createBucketAt,
  92. Bucket: bucketName,
  93. Path: "/",
  94. }
  95. // need to add new mapping here before getting upates from metadata tailing
  96. option.mappings.Mappings[string(bucketPath)] = remoteLocation
  97. return filer.InsertMountMapping(option, string(bucketPath), remoteLocation)
  98. }
  99. handleDeleteBucket := func(entry *filer_pb.Entry) error {
  100. if !entry.IsDirectory {
  101. return nil
  102. }
  103. client, remoteStorageMountLocation, err := option.findRemoteStorageClient(entry.Name)
  104. if err != nil {
  105. return fmt.Errorf("findRemoteStorageClient %s: %v", entry.Name, err)
  106. }
  107. glog.V(0).Infof("delete remote bucket %s", remoteStorageMountLocation.Bucket)
  108. if err := client.DeleteBucket(remoteStorageMountLocation.Bucket); err != nil {
  109. return fmt.Errorf("delete remote bucket %s: %v", remoteStorageMountLocation.Bucket, err)
  110. }
  111. bucketPath := util.FullPath(option.bucketsDir).Child(entry.Name)
  112. return filer.DeleteMountMapping(option, string(bucketPath))
  113. }
  114. handleEtcRemoteChanges := func(resp *filer_pb.SubscribeMetadataResponse) error {
  115. message := resp.EventNotification
  116. if message.NewEntry != nil {
  117. // update
  118. if message.NewEntry.Name == filer.REMOTE_STORAGE_MOUNT_FILE {
  119. newMappings, readErr := filer.UnmarshalRemoteStorageMappings(message.NewEntry.Content)
  120. if readErr != nil {
  121. return fmt.Errorf("unmarshal mappings: %v", readErr)
  122. }
  123. option.mappings = newMappings
  124. }
  125. if strings.HasSuffix(message.NewEntry.Name, filer.REMOTE_STORAGE_CONF_SUFFIX) {
  126. conf := &remote_pb.RemoteConf{}
  127. if err := proto.Unmarshal(message.NewEntry.Content, conf); err != nil {
  128. return fmt.Errorf("unmarshal %s/%s: %v", filer.DirectoryEtcRemote, message.NewEntry.Name, err)
  129. }
  130. option.remoteConfs[conf.Name] = conf
  131. }
  132. } else if message.OldEntry != nil {
  133. // deletion
  134. if strings.HasSuffix(message.OldEntry.Name, filer.REMOTE_STORAGE_CONF_SUFFIX) {
  135. conf := &remote_pb.RemoteConf{}
  136. if err := proto.Unmarshal(message.OldEntry.Content, conf); err != nil {
  137. return fmt.Errorf("unmarshal %s/%s: %v", filer.DirectoryEtcRemote, message.OldEntry.Name, err)
  138. }
  139. delete(option.remoteConfs, conf.Name)
  140. }
  141. }
  142. return nil
  143. }
  144. eachEntryFunc := func(resp *filer_pb.SubscribeMetadataResponse) error {
  145. message := resp.EventNotification
  146. if strings.HasPrefix(resp.Directory, filer.DirectoryEtcRemote) {
  147. return handleEtcRemoteChanges(resp)
  148. }
  149. if message.OldEntry == nil && message.NewEntry == nil {
  150. return nil
  151. }
  152. if message.OldEntry == nil && message.NewEntry != nil {
  153. if message.NewParentPath == option.bucketsDir {
  154. return handleCreateBucket(message.NewEntry)
  155. }
  156. if !filer.HasData(message.NewEntry) {
  157. return nil
  158. }
  159. bucket, remoteStorageMountLocation, remoteStorage, ok := option.detectBucketInfo(message.NewParentPath)
  160. if !ok {
  161. return nil
  162. }
  163. client, err := remote_storage.GetRemoteStorage(remoteStorage)
  164. if err != nil {
  165. return err
  166. }
  167. glog.V(2).Infof("create: %+v", resp)
  168. if !shouldSendToRemote(message.NewEntry) {
  169. glog.V(2).Infof("skipping creating: %+v", resp)
  170. return nil
  171. }
  172. dest := toRemoteStorageLocation(bucket, util.NewFullPath(message.NewParentPath, message.NewEntry.Name), remoteStorageMountLocation)
  173. if message.NewEntry.IsDirectory {
  174. glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
  175. return client.WriteDirectory(dest, message.NewEntry)
  176. }
  177. glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
  178. reader := filer.NewFileReader(filerSource, message.NewEntry)
  179. remoteEntry, writeErr := client.WriteFile(dest, message.NewEntry, reader)
  180. if writeErr != nil {
  181. return writeErr
  182. }
  183. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  184. }
  185. if message.OldEntry != nil && message.NewEntry == nil {
  186. if resp.Directory == option.bucketsDir {
  187. return handleDeleteBucket(message.OldEntry)
  188. }
  189. bucket, remoteStorageMountLocation, remoteStorage, ok := option.detectBucketInfo(resp.Directory)
  190. if !ok {
  191. return nil
  192. }
  193. client, err := remote_storage.GetRemoteStorage(remoteStorage)
  194. if err != nil {
  195. return err
  196. }
  197. glog.V(2).Infof("delete: %+v", resp)
  198. dest := toRemoteStorageLocation(bucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  199. if message.OldEntry.IsDirectory {
  200. glog.V(0).Infof("rmdir %s", remote_storage.FormatLocation(dest))
  201. return client.RemoveDirectory(dest)
  202. }
  203. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
  204. return client.DeleteFile(dest)
  205. }
  206. if message.OldEntry != nil && message.NewEntry != nil {
  207. if resp.Directory == option.bucketsDir {
  208. if message.NewParentPath == option.bucketsDir {
  209. if message.OldEntry.Name == message.NewEntry.Name {
  210. return nil
  211. }
  212. if err := handleCreateBucket(message.NewEntry); err != nil {
  213. return err
  214. }
  215. if err := handleDeleteBucket(message.OldEntry); err != nil {
  216. return err
  217. }
  218. }
  219. }
  220. oldBucket, oldRemoteStorageMountLocation, oldRemoteStorage, oldOk := option.detectBucketInfo(resp.Directory)
  221. newBucket, newRemoteStorageMountLocation, newRemoteStorage, newOk := option.detectBucketInfo(message.NewParentPath)
  222. if oldOk && newOk {
  223. if !shouldSendToRemote(message.NewEntry) {
  224. glog.V(2).Infof("skipping updating: %+v", resp)
  225. return nil
  226. }
  227. client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
  228. if err != nil {
  229. return err
  230. }
  231. if resp.Directory == message.NewParentPath && message.OldEntry.Name == message.NewEntry.Name {
  232. // update the same entry
  233. if message.NewEntry.IsDirectory {
  234. // update directory property
  235. return nil
  236. }
  237. if filer.IsSameData(message.OldEntry, message.NewEntry) {
  238. glog.V(2).Infof("update meta: %+v", resp)
  239. oldDest := toRemoteStorageLocation(oldBucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), oldRemoteStorageMountLocation)
  240. return client.UpdateFileMetadata(oldDest, message.OldEntry, message.NewEntry)
  241. } else {
  242. newDest := toRemoteStorageLocation(newBucket, util.NewFullPath(message.NewParentPath, message.NewEntry.Name), newRemoteStorageMountLocation)
  243. reader := filer.NewFileReader(filerSource, message.NewEntry)
  244. glog.V(0).Infof("create %s", remote_storage.FormatLocation(newDest))
  245. remoteEntry, writeErr := client.WriteFile(newDest, message.NewEntry, reader)
  246. if writeErr != nil {
  247. return writeErr
  248. }
  249. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  250. }
  251. }
  252. }
  253. // the following is entry rename
  254. if oldOk {
  255. client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
  256. if err != nil {
  257. return err
  258. }
  259. oldDest := toRemoteStorageLocation(oldBucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), oldRemoteStorageMountLocation)
  260. if message.OldEntry.IsDirectory {
  261. return client.RemoveDirectory(oldDest)
  262. }
  263. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
  264. if err := client.DeleteFile(oldDest); err != nil {
  265. return err
  266. }
  267. }
  268. if newOk {
  269. if !shouldSendToRemote(message.NewEntry) {
  270. glog.V(2).Infof("skipping updating: %+v", resp)
  271. return nil
  272. }
  273. client, err := remote_storage.GetRemoteStorage(newRemoteStorage)
  274. if err != nil {
  275. return err
  276. }
  277. newDest := toRemoteStorageLocation(newBucket, util.NewFullPath(message.NewParentPath, message.NewEntry.Name), newRemoteStorageMountLocation)
  278. if message.NewEntry.IsDirectory {
  279. return client.WriteDirectory(newDest, message.NewEntry)
  280. }
  281. reader := filer.NewFileReader(filerSource, message.NewEntry)
  282. glog.V(0).Infof("create %s", remote_storage.FormatLocation(newDest))
  283. remoteEntry, writeErr := client.WriteFile(newDest, message.NewEntry, reader)
  284. if writeErr != nil {
  285. return writeErr
  286. }
  287. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  288. }
  289. }
  290. return nil
  291. }
  292. return eachEntryFunc, nil
  293. }
  294. func (option *RemoteGatewayOptions) findRemoteStorageClient(bucketName string) (client remote_storage.RemoteStorageClient, remoteStorageMountLocation *remote_pb.RemoteStorageLocation, err error) {
  295. bucket := util.FullPath(option.bucketsDir).Child(bucketName)
  296. var isMounted bool
  297. remoteStorageMountLocation, isMounted = option.mappings.Mappings[string(bucket)]
  298. if !isMounted {
  299. return nil, remoteStorageMountLocation, fmt.Errorf("%s is not mounted", bucket)
  300. }
  301. remoteConf, hasClient := option.remoteConfs[remoteStorageMountLocation.Name]
  302. if !hasClient {
  303. return nil, remoteStorageMountLocation, fmt.Errorf("%s mounted to un-configured %+v", bucket, remoteStorageMountLocation)
  304. }
  305. client, err = remote_storage.GetRemoteStorage(remoteConf)
  306. if err != nil {
  307. return nil, remoteStorageMountLocation, err
  308. }
  309. return client, remoteStorageMountLocation, nil
  310. }
  311. func (option *RemoteGatewayOptions) detectBucketInfo(actualDir string) (bucket util.FullPath, remoteStorageMountLocation *remote_pb.RemoteStorageLocation, remoteConf *remote_pb.RemoteConf, ok bool) {
  312. bucket, ok = extractBucketPath(option.bucketsDir, actualDir)
  313. if !ok {
  314. return "", nil, nil, false
  315. }
  316. var isMounted bool
  317. remoteStorageMountLocation, isMounted = option.mappings.Mappings[string(bucket)]
  318. if !isMounted {
  319. glog.Warningf("%s is not mounted", bucket)
  320. return "", nil, nil, false
  321. }
  322. var hasClient bool
  323. remoteConf, hasClient = option.remoteConfs[remoteStorageMountLocation.Name]
  324. if !hasClient {
  325. glog.Warningf("%s mounted to un-configured %+v", bucket, remoteStorageMountLocation)
  326. return "", nil, nil, false
  327. }
  328. return bucket, remoteStorageMountLocation, remoteConf, true
  329. }
  330. func extractBucketPath(bucketsDir, dir string) (util.FullPath, bool) {
  331. if !strings.HasPrefix(dir, bucketsDir+"/") {
  332. return "", false
  333. }
  334. parts := strings.SplitN(dir[len(bucketsDir)+1:], "/", 2)
  335. return util.FullPath(bucketsDir).Child(parts[0]), true
  336. }
  337. func (option *RemoteGatewayOptions) collectRemoteStorageConf() (err error) {
  338. if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress)); err != nil {
  339. return err
  340. } else {
  341. option.mappings = mappings
  342. }
  343. option.remoteConfs = make(map[string]*remote_pb.RemoteConf)
  344. var lastConfName string
  345. err = filer_pb.List(option, filer.DirectoryEtcRemote, "", func(entry *filer_pb.Entry, isLast bool) error {
  346. if !strings.HasSuffix(entry.Name, filer.REMOTE_STORAGE_CONF_SUFFIX) {
  347. return nil
  348. }
  349. conf := &remote_pb.RemoteConf{}
  350. if err := proto.Unmarshal(entry.Content, conf); err != nil {
  351. return fmt.Errorf("unmarshal %s/%s: %v", filer.DirectoryEtcRemote, entry.Name, err)
  352. }
  353. option.remoteConfs[conf.Name] = conf
  354. lastConfName = conf.Name
  355. return nil
  356. }, "", false, math.MaxUint32)
  357. if option.mappings.PrimaryBucketStorageName == "" && len(option.remoteConfs) == 1 {
  358. glog.V(0).Infof("%s is set to the default remote storage", lastConfName)
  359. option.mappings.PrimaryBucketStorageName = lastConfName
  360. }
  361. return
  362. }