store_replicate.go 6.3 KB

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