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.

393 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. remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewEntry, dest)
  179. if writeErr != nil {
  180. return writeErr
  181. }
  182. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  183. }
  184. if message.OldEntry != nil && message.NewEntry == nil {
  185. if resp.Directory == option.bucketsDir {
  186. return handleDeleteBucket(message.OldEntry)
  187. }
  188. bucket, remoteStorageMountLocation, remoteStorage, ok := option.detectBucketInfo(resp.Directory)
  189. if !ok {
  190. return nil
  191. }
  192. client, err := remote_storage.GetRemoteStorage(remoteStorage)
  193. if err != nil {
  194. return err
  195. }
  196. glog.V(2).Infof("delete: %+v", resp)
  197. dest := toRemoteStorageLocation(bucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), remoteStorageMountLocation)
  198. if message.OldEntry.IsDirectory {
  199. glog.V(0).Infof("rmdir %s", remote_storage.FormatLocation(dest))
  200. return client.RemoveDirectory(dest)
  201. }
  202. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(dest))
  203. return client.DeleteFile(dest)
  204. }
  205. if message.OldEntry != nil && message.NewEntry != nil {
  206. if resp.Directory == option.bucketsDir {
  207. if message.NewParentPath == option.bucketsDir {
  208. if message.OldEntry.Name == message.NewEntry.Name {
  209. return nil
  210. }
  211. if err := handleCreateBucket(message.NewEntry); err != nil {
  212. return err
  213. }
  214. if err := handleDeleteBucket(message.OldEntry); err != nil {
  215. return err
  216. }
  217. }
  218. }
  219. oldBucket, oldRemoteStorageMountLocation, oldRemoteStorage, oldOk := option.detectBucketInfo(resp.Directory)
  220. newBucket, newRemoteStorageMountLocation, newRemoteStorage, newOk := option.detectBucketInfo(message.NewParentPath)
  221. if oldOk && newOk {
  222. if !shouldSendToRemote(message.NewEntry) {
  223. glog.V(2).Infof("skipping updating: %+v", resp)
  224. return nil
  225. }
  226. client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
  227. if err != nil {
  228. return err
  229. }
  230. if resp.Directory == message.NewParentPath && message.OldEntry.Name == message.NewEntry.Name {
  231. // update the same entry
  232. if message.NewEntry.IsDirectory {
  233. // update directory property
  234. return nil
  235. }
  236. if filer.IsSameData(message.OldEntry, message.NewEntry) {
  237. glog.V(2).Infof("update meta: %+v", resp)
  238. oldDest := toRemoteStorageLocation(oldBucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), oldRemoteStorageMountLocation)
  239. return client.UpdateFileMetadata(oldDest, message.OldEntry, message.NewEntry)
  240. } else {
  241. newDest := toRemoteStorageLocation(newBucket, util.NewFullPath(message.NewParentPath, message.NewEntry.Name), newRemoteStorageMountLocation)
  242. remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewEntry, newDest)
  243. if writeErr != nil {
  244. return writeErr
  245. }
  246. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  247. }
  248. }
  249. }
  250. // the following is entry rename
  251. if oldOk {
  252. client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
  253. if err != nil {
  254. return err
  255. }
  256. oldDest := toRemoteStorageLocation(oldBucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), oldRemoteStorageMountLocation)
  257. if message.OldEntry.IsDirectory {
  258. return client.RemoveDirectory(oldDest)
  259. }
  260. glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
  261. if err := client.DeleteFile(oldDest); err != nil {
  262. return err
  263. }
  264. }
  265. if newOk {
  266. if !shouldSendToRemote(message.NewEntry) {
  267. glog.V(2).Infof("skipping updating: %+v", resp)
  268. return nil
  269. }
  270. client, err := remote_storage.GetRemoteStorage(newRemoteStorage)
  271. if err != nil {
  272. return err
  273. }
  274. newDest := toRemoteStorageLocation(newBucket, util.NewFullPath(message.NewParentPath, message.NewEntry.Name), newRemoteStorageMountLocation)
  275. if message.NewEntry.IsDirectory {
  276. return client.WriteDirectory(newDest, message.NewEntry)
  277. }
  278. remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewEntry, newDest)
  279. if writeErr != nil {
  280. return writeErr
  281. }
  282. return updateLocalEntry(&remoteSyncOptions, message.NewParentPath, message.NewEntry, remoteEntry)
  283. }
  284. }
  285. return nil
  286. }
  287. return eachEntryFunc, nil
  288. }
  289. func (option *RemoteGatewayOptions) findRemoteStorageClient(bucketName string) (client remote_storage.RemoteStorageClient, remoteStorageMountLocation *remote_pb.RemoteStorageLocation, err error) {
  290. bucket := util.FullPath(option.bucketsDir).Child(bucketName)
  291. var isMounted bool
  292. remoteStorageMountLocation, isMounted = option.mappings.Mappings[string(bucket)]
  293. if !isMounted {
  294. return nil, remoteStorageMountLocation, fmt.Errorf("%s is not mounted", bucket)
  295. }
  296. remoteConf, hasClient := option.remoteConfs[remoteStorageMountLocation.Name]
  297. if !hasClient {
  298. return nil, remoteStorageMountLocation, fmt.Errorf("%s mounted to un-configured %+v", bucket, remoteStorageMountLocation)
  299. }
  300. client, err = remote_storage.GetRemoteStorage(remoteConf)
  301. if err != nil {
  302. return nil, remoteStorageMountLocation, err
  303. }
  304. return client, remoteStorageMountLocation, nil
  305. }
  306. func (option *RemoteGatewayOptions) detectBucketInfo(actualDir string) (bucket util.FullPath, remoteStorageMountLocation *remote_pb.RemoteStorageLocation, remoteConf *remote_pb.RemoteConf, ok bool) {
  307. bucket, ok = extractBucketPath(option.bucketsDir, actualDir)
  308. if !ok {
  309. return "", nil, nil, false
  310. }
  311. var isMounted bool
  312. remoteStorageMountLocation, isMounted = option.mappings.Mappings[string(bucket)]
  313. if !isMounted {
  314. glog.Warningf("%s is not mounted", bucket)
  315. return "", nil, nil, false
  316. }
  317. var hasClient bool
  318. remoteConf, hasClient = option.remoteConfs[remoteStorageMountLocation.Name]
  319. if !hasClient {
  320. glog.Warningf("%s mounted to un-configured %+v", bucket, remoteStorageMountLocation)
  321. return "", nil, nil, false
  322. }
  323. return bucket, remoteStorageMountLocation, remoteConf, true
  324. }
  325. func extractBucketPath(bucketsDir, dir string) (util.FullPath, bool) {
  326. if !strings.HasPrefix(dir, bucketsDir+"/") {
  327. return "", false
  328. }
  329. parts := strings.SplitN(dir[len(bucketsDir)+1:], "/", 2)
  330. return util.FullPath(bucketsDir).Child(parts[0]), true
  331. }
  332. func (option *RemoteGatewayOptions) collectRemoteStorageConf() (err error) {
  333. if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress)); err != nil {
  334. return err
  335. } else {
  336. option.mappings = mappings
  337. }
  338. option.remoteConfs = make(map[string]*remote_pb.RemoteConf)
  339. var lastConfName string
  340. err = filer_pb.List(option, filer.DirectoryEtcRemote, "", func(entry *filer_pb.Entry, isLast bool) error {
  341. if !strings.HasSuffix(entry.Name, filer.REMOTE_STORAGE_CONF_SUFFIX) {
  342. return nil
  343. }
  344. conf := &remote_pb.RemoteConf{}
  345. if err := proto.Unmarshal(entry.Content, conf); err != nil {
  346. return fmt.Errorf("unmarshal %s/%s: %v", filer.DirectoryEtcRemote, entry.Name, err)
  347. }
  348. option.remoteConfs[conf.Name] = conf
  349. lastConfName = conf.Name
  350. return nil
  351. }, "", false, math.MaxUint32)
  352. if option.mappings.PrimaryBucketStorageName == "" && len(option.remoteConfs) == 1 {
  353. glog.V(0).Infof("%s is set to the default remote storage", lastConfName)
  354. option.mappings.PrimaryBucketStorageName = lastConfName
  355. }
  356. return
  357. }