store_replicate.go 6.5 KB

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