store_replicate.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package topology
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "google.golang.org/grpc"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/seaweedfs/seaweedfs/weed/glog"
  13. "github.com/seaweedfs/seaweedfs/weed/operation"
  14. "github.com/seaweedfs/seaweedfs/weed/security"
  15. "github.com/seaweedfs/seaweedfs/weed/stats"
  16. "github.com/seaweedfs/seaweedfs/weed/storage"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  18. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  19. "github.com/seaweedfs/seaweedfs/weed/util"
  20. "github.com/seaweedfs/seaweedfs/weed/util/buffer_pool"
  21. util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
  22. )
  23. func ReplicatedWrite(masterFn operation.GetMasterFn, grpcDialOption grpc.DialOption, s *storage.Store, volumeId needle.VolumeId, n *needle.Needle, r *http.Request, contentMd5 string) (isUnchanged bool, err error) {
  24. //check JWT
  25. jwt := security.GetJwt(r)
  26. // check whether this is a replicated write request
  27. var remoteLocations []operation.Location
  28. if r.FormValue("type") != "replicate" {
  29. // this is the initial request
  30. remoteLocations, err = GetWritableRemoteReplications(s, grpcDialOption, volumeId, masterFn)
  31. if err != nil {
  32. glog.V(0).Infoln(err)
  33. return
  34. }
  35. }
  36. // read fsync value
  37. fsync := false
  38. if r.FormValue("fsync") == "true" {
  39. fsync = true
  40. }
  41. if s.GetVolume(volumeId) != nil {
  42. start := time.Now()
  43. isUnchanged, err = s.WriteVolumeNeedle(volumeId, n, true, fsync)
  44. stats.VolumeServerRequestHistogram.WithLabelValues(stats.WriteToLocalDisk).Observe(time.Since(start).Seconds())
  45. if err != nil {
  46. stats.VolumeServerHandlerCounter.WithLabelValues(stats.ErrorWriteToLocalDisk).Inc()
  47. err = fmt.Errorf("failed to write to local disk: %v", err)
  48. glog.V(0).Infoln(err)
  49. return
  50. }
  51. }
  52. if len(remoteLocations) > 0 { //send to other replica locations
  53. start := time.Now()
  54. err = DistributedOperation(remoteLocations, func(location operation.Location) error {
  55. u := url.URL{
  56. Scheme: "http",
  57. Host: location.Url,
  58. Path: r.URL.Path,
  59. }
  60. q := url.Values{
  61. "type": {"replicate"},
  62. "ttl": {n.Ttl.String()},
  63. }
  64. if n.LastModified > 0 {
  65. q.Set("ts", strconv.FormatUint(n.LastModified, 10))
  66. }
  67. if n.IsChunkedManifest() {
  68. q.Set("cm", "true")
  69. }
  70. u.RawQuery = q.Encode()
  71. pairMap := make(map[string]string)
  72. if n.HasPairs() {
  73. tmpMap := make(map[string]string)
  74. err := json.Unmarshal(n.Pairs, &tmpMap)
  75. if err != nil {
  76. stats.VolumeServerHandlerCounter.WithLabelValues(stats.ErrorUnmarshalPairs).Inc()
  77. glog.V(0).Infoln("Unmarshal pairs error:", err)
  78. }
  79. for k, v := range tmpMap {
  80. pairMap[needle.PairNamePrefix+k] = v
  81. }
  82. }
  83. bytesBuffer := buffer_pool.SyncPoolGetBuffer()
  84. defer buffer_pool.SyncPoolPutBuffer(bytesBuffer)
  85. // volume server do not know about encryption
  86. // TODO optimize here to compress data only once
  87. uploadOption := &operation.UploadOption{
  88. UploadUrl: u.String(),
  89. Filename: string(n.Name),
  90. Cipher: false,
  91. IsInputCompressed: n.IsCompressed(),
  92. MimeType: string(n.Mime),
  93. PairMap: pairMap,
  94. Jwt: jwt,
  95. Md5: contentMd5,
  96. BytesBuffer: bytesBuffer,
  97. }
  98. uploader, err := operation.NewUploader()
  99. if err != nil {
  100. glog.Errorf("replication-UploadData, err:%v, url:%s", err, u.String())
  101. return err
  102. }
  103. _, err = uploader.UploadData(n.Data, uploadOption)
  104. if err != nil {
  105. glog.Errorf("replication-UploadData, err:%v, url:%s", err, u.String())
  106. }
  107. return err
  108. })
  109. stats.VolumeServerRequestHistogram.WithLabelValues(stats.WriteToReplicas).Observe(time.Since(start).Seconds())
  110. if err != nil {
  111. stats.VolumeServerHandlerCounter.WithLabelValues(stats.ErrorWriteToReplicas).Inc()
  112. err = fmt.Errorf("failed to write to replicas for volume %d: %v", volumeId, err)
  113. glog.V(0).Infoln(err)
  114. return false, err
  115. }
  116. }
  117. return
  118. }
  119. func ReplicatedDelete(masterFn operation.GetMasterFn, grpcDialOption grpc.DialOption, store *storage.Store, volumeId needle.VolumeId, n *needle.Needle, r *http.Request) (size types.Size, err error) {
  120. //check JWT
  121. jwt := security.GetJwt(r)
  122. var remoteLocations []operation.Location
  123. if r.FormValue("type") != "replicate" {
  124. remoteLocations, err = GetWritableRemoteReplications(store, grpcDialOption, volumeId, masterFn)
  125. if err != nil {
  126. glog.V(0).Infoln(err)
  127. return
  128. }
  129. }
  130. size, err = store.DeleteVolumeNeedle(volumeId, n)
  131. if err != nil {
  132. glog.V(0).Infoln("delete error:", err)
  133. return
  134. }
  135. if len(remoteLocations) > 0 { //send to other replica locations
  136. if err = DistributedOperation(remoteLocations, func(location operation.Location) error {
  137. return util_http.Delete("http://"+location.Url+r.URL.Path+"?type=replicate", string(jwt))
  138. }); err != nil {
  139. size = 0
  140. }
  141. }
  142. return
  143. }
  144. type DistributedOperationResult map[string]error
  145. func (dr DistributedOperationResult) Error() error {
  146. var errs []string
  147. for k, v := range dr {
  148. if v != nil {
  149. errs = append(errs, fmt.Sprintf("[%s]: %v", k, v))
  150. }
  151. }
  152. if len(errs) == 0 {
  153. return nil
  154. }
  155. return errors.New(strings.Join(errs, "\n"))
  156. }
  157. type RemoteResult struct {
  158. Host string
  159. Error error
  160. }
  161. func DistributedOperation(locations []operation.Location, op func(location operation.Location) error) error {
  162. length := len(locations)
  163. results := make(chan RemoteResult)
  164. for _, location := range locations {
  165. go func(location operation.Location, results chan RemoteResult) {
  166. results <- RemoteResult{location.Url, op(location)}
  167. }(location, results)
  168. }
  169. ret := DistributedOperationResult(make(map[string]error))
  170. for i := 0; i < length; i++ {
  171. result := <-results
  172. ret[result.Host] = result.Error
  173. }
  174. return ret.Error()
  175. }
  176. func GetWritableRemoteReplications(s *storage.Store, grpcDialOption grpc.DialOption, volumeId needle.VolumeId, masterFn operation.GetMasterFn) (remoteLocations []operation.Location, err error) {
  177. v := s.GetVolume(volumeId)
  178. if v != nil && v.ReplicaPlacement.GetCopyCount() == 1 {
  179. return
  180. }
  181. // not on local store, or has replications
  182. lookupResult, lookupErr := operation.LookupVolumeId(masterFn, grpcDialOption, volumeId.String())
  183. if lookupErr == nil {
  184. selfUrl := util.JoinHostPort(s.Ip, s.Port)
  185. for _, location := range lookupResult.Locations {
  186. if location.Url != selfUrl {
  187. remoteLocations = append(remoteLocations, location)
  188. }
  189. }
  190. } else {
  191. err = fmt.Errorf("replicating lookup failed for %d: %v", volumeId, lookupErr)
  192. return
  193. }
  194. if v != nil {
  195. // has one local and has remote replications
  196. copyCount := v.ReplicaPlacement.GetCopyCount()
  197. if len(lookupResult.Locations) < copyCount {
  198. err = fmt.Errorf("replicating operations [%d] is less than volume %d replication copy count [%d]",
  199. len(lookupResult.Locations), volumeId, copyCount)
  200. }
  201. }
  202. return
  203. }