store_replicate.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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) (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. }
  92. _, err := operation.UploadData(n.Data, uploadOption)
  93. return err
  94. })
  95. stats.VolumeServerRequestHistogram.WithLabelValues(stats.WriteToReplicas).Observe(time.Since(start).Seconds())
  96. if err != nil {
  97. stats.VolumeServerRequestCounter.WithLabelValues(stats.ErrorWriteToReplicas).Inc()
  98. err = fmt.Errorf("failed to write to replicas for volume %d: %v", volumeId, err)
  99. glog.V(0).Infoln(err)
  100. return false, err
  101. }
  102. }
  103. return
  104. }
  105. 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) {
  106. //check JWT
  107. jwt := security.GetJwt(r)
  108. var remoteLocations []operation.Location
  109. if r.FormValue("type") != "replicate" {
  110. remoteLocations, err = GetWritableRemoteReplications(store, grpcDialOption, volumeId, masterFn)
  111. if err != nil {
  112. glog.V(0).Infoln(err)
  113. return
  114. }
  115. }
  116. size, err = store.DeleteVolumeNeedle(volumeId, n)
  117. if err != nil {
  118. glog.V(0).Infoln("delete error:", err)
  119. return
  120. }
  121. if len(remoteLocations) > 0 { //send to other replica locations
  122. if err = DistributedOperation(remoteLocations, func(location operation.Location) error {
  123. return util.Delete("http://"+location.Url+r.URL.Path+"?type=replicate", string(jwt))
  124. }); err != nil {
  125. size = 0
  126. }
  127. }
  128. return
  129. }
  130. type DistributedOperationResult map[string]error
  131. func (dr DistributedOperationResult) Error() error {
  132. var errs []string
  133. for k, v := range dr {
  134. if v != nil {
  135. errs = append(errs, fmt.Sprintf("[%s]: %v", k, v))
  136. }
  137. }
  138. if len(errs) == 0 {
  139. return nil
  140. }
  141. return errors.New(strings.Join(errs, "\n"))
  142. }
  143. type RemoteResult struct {
  144. Host string
  145. Error error
  146. }
  147. func DistributedOperation(locations []operation.Location, op func(location operation.Location) error) error {
  148. length := len(locations)
  149. results := make(chan RemoteResult)
  150. for _, location := range locations {
  151. go func(location operation.Location, results chan RemoteResult) {
  152. results <- RemoteResult{location.Url, op(location)}
  153. }(location, results)
  154. }
  155. ret := DistributedOperationResult(make(map[string]error))
  156. for i := 0; i < length; i++ {
  157. result := <-results
  158. ret[result.Host] = result.Error
  159. }
  160. return ret.Error()
  161. }
  162. func GetWritableRemoteReplications(s *storage.Store, grpcDialOption grpc.DialOption, volumeId needle.VolumeId, masterFn operation.GetMasterFn) (remoteLocations []operation.Location, err error) {
  163. v := s.GetVolume(volumeId)
  164. if v != nil && v.ReplicaPlacement.GetCopyCount() == 1 {
  165. return
  166. }
  167. // not on local store, or has replications
  168. lookupResult, lookupErr := operation.LookupVolumeId(masterFn, grpcDialOption, volumeId.String())
  169. if lookupErr == nil {
  170. selfUrl := util.JoinHostPort(s.Ip, s.Port)
  171. for _, location := range lookupResult.Locations {
  172. if location.Url != selfUrl {
  173. remoteLocations = append(remoteLocations, location)
  174. }
  175. }
  176. } else {
  177. err = fmt.Errorf("replicating lookup failed for %d: %v", volumeId, lookupErr)
  178. return
  179. }
  180. if v != nil {
  181. // has one local and has remote replications
  182. copyCount := v.ReplicaPlacement.GetCopyCount()
  183. if len(lookupResult.Locations) < copyCount {
  184. err = fmt.Errorf("replicating operations [%d] is less than volume %d replication copy count [%d]",
  185. len(lookupResult.Locations), volumeId, copyCount)
  186. }
  187. }
  188. return
  189. }