store_replicate.go 7.0 KB

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