You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

hub_io.go 8.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package http
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/inhies/go-bytesize"
  12. "gitlink.org.cn/cloudream/common/consts/errorcode"
  13. "gitlink.org.cn/cloudream/common/pkgs/ioswitch/exec"
  14. "gitlink.org.cn/cloudream/common/pkgs/logger"
  15. "gitlink.org.cn/cloudream/common/sdks/storage/cdsapi"
  16. "gitlink.org.cn/cloudream/common/utils/serder"
  17. )
  18. type IOService struct {
  19. *Server
  20. }
  21. func (s *Server) IOSvc() *IOService {
  22. return &IOService{
  23. Server: s,
  24. }
  25. }
  26. func (s *IOService) GetStream(ctx *gin.Context) {
  27. var req cdsapi.GetStreamReq
  28. if err := ctx.ShouldBindJSON(&req); err != nil {
  29. logger.Warnf("binding body: %s", err.Error())
  30. ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
  31. return
  32. }
  33. logger.
  34. WithField("PlanID", req.PlanID).
  35. WithField("VarID", req.VarID).
  36. Debugf("stream output")
  37. // 设置超时
  38. c, cancel := context.WithTimeout(ctx.Request.Context(), time.Second*30)
  39. defer cancel()
  40. sw := s.svc.swWorker.FindByIDContexted(c, req.PlanID)
  41. if sw == nil {
  42. ctx.JSON(http.StatusNotFound, gin.H{"error": "plan not found"})
  43. return
  44. }
  45. signalBytes, err := serder.ObjectToJSON(req.Signal)
  46. if err != nil {
  47. logger.Warnf("serializing SignalVar: %s", err)
  48. ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "serializing SignalVar fail"))
  49. return
  50. }
  51. signal, err := serder.JSONToObjectEx[*exec.SignalVar](signalBytes)
  52. if err != nil {
  53. ctx.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("deserializing var: %v", err)})
  54. return
  55. }
  56. sw.PutVars(signal)
  57. strVar := &exec.StreamVar{
  58. ID: req.VarID,
  59. }
  60. err = sw.BindVars(ctx.Request.Context(), strVar)
  61. if err != nil {
  62. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("binding vars: %v", err)})
  63. return
  64. }
  65. reader := strVar.Stream
  66. defer reader.Close()
  67. ctx.Header("Content-Type", "application/octet-stream")
  68. ctx.Status(http.StatusOK)
  69. buf := make([]byte, 1024*64)
  70. readAllCnt := 0
  71. startTime := time.Now()
  72. for {
  73. readCnt, err := reader.Read(buf)
  74. if readCnt > 0 {
  75. readAllCnt += readCnt
  76. _, err := ctx.Writer.Write(buf[:readCnt])
  77. if err != nil {
  78. logger.
  79. WithField("PlanID", req.PlanID).
  80. WithField("VarID", req.VarID).
  81. Warnf("send stream data failed, err: %s", err.Error())
  82. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("send stream data failed, err: %v", err)})
  83. return
  84. }
  85. // 刷新缓冲区,确保数据立即发送
  86. ctx.Writer.Flush()
  87. }
  88. // 文件读取完毕
  89. if err == io.EOF {
  90. dt := time.Since(startTime)
  91. logger.
  92. WithField("PlanID", req.PlanID).
  93. WithField("VarID", req.VarID).
  94. Debugf("send data size %d in %v, speed %v/s", readAllCnt, dt, bytesize.New(float64(readAllCnt)/dt.Seconds()))
  95. return
  96. }
  97. // io.ErrUnexpectedEOF 没有读满整个 buf 就遇到了 EOF,此时正常发送剩余数据即可
  98. if err != nil && err != io.ErrUnexpectedEOF {
  99. logger.
  100. WithField("PlanID", req.PlanID).
  101. WithField("VarID", req.VarID).
  102. Warnf("reading stream data: %s", err.Error())
  103. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("reading stream data: %v", err)})
  104. return
  105. }
  106. }
  107. }
  108. func (s *IOService) SendStream(ctx *gin.Context) {
  109. //planID := ctx.PostForm("plan_id")
  110. //varID := ctx.PostForm("var_id")
  111. var req cdsapi.SendStreamReq
  112. if err := ctx.ShouldBindJSON(&req); err != nil {
  113. logger.Warnf("binding body: %s", err.Error())
  114. ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
  115. return
  116. }
  117. logger.
  118. WithField("PlanID", req.PlanID).
  119. WithField("VarID", req.VarID).
  120. Debugf("stream input")
  121. // 超时设置
  122. c, cancel := context.WithTimeout(ctx.Request.Context(), time.Second*30)
  123. defer cancel()
  124. sw := s.svc.swWorker.FindByIDContexted(c, req.PlanID)
  125. if sw == nil {
  126. ctx.JSON(http.StatusNotFound, gin.H{"error": "plan not found"})
  127. return
  128. }
  129. pr, pw := io.Pipe()
  130. defer pr.Close()
  131. streamVar := &exec.StreamVar{
  132. ID: req.VarID,
  133. Stream: pr,
  134. }
  135. sw.PutVars(streamVar)
  136. var recvSize int64
  137. go func() {
  138. defer pw.Close()
  139. _, err := io.Copy(pw, ctx.Request.Body)
  140. if err != nil {
  141. logger.Warnf("write data to file failed, err: %s", err.Error())
  142. pw.CloseWithError(fmt.Errorf("write data to file failed: %w", err))
  143. }
  144. }()
  145. for {
  146. buf := make([]byte, 1024*64)
  147. n, err := pr.Read(buf)
  148. if err != nil {
  149. if err == io.EOF {
  150. logger.WithField("ReceiveSize", recvSize).
  151. WithField("VarID", req.VarID).
  152. Debugf("file transmission completed")
  153. // 将结果返回给客户端
  154. ctx.JSON(http.StatusOK, gin.H{"message": "file transmission completed"})
  155. return
  156. }
  157. logger.Warnf("read stream failed, err: %s", err.Error())
  158. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("read stream failed: %v", err)})
  159. return
  160. }
  161. if n > 0 {
  162. recvSize += int64(n)
  163. // 处理接收到的数据,例如写入文件或进行其他操作
  164. }
  165. }
  166. }
  167. func (s *IOService) ExecuteIOPlan(ctx *gin.Context) {
  168. bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
  169. if err != nil {
  170. logger.Warnf("reading body: %s", err.Error())
  171. ctx.JSON(http.StatusInternalServerError, Failed("400", "internal error"))
  172. return
  173. }
  174. println("Received body: %s", string(bodyBytes))
  175. ctx.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) // Reset body for subsequent reads
  176. var req cdsapi.ExecuteIOPlanReq
  177. if err := ctx.ShouldBindJSON(&req); err != nil {
  178. logger.Warnf("binding body: %s", err.Error())
  179. ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
  180. return
  181. }
  182. planBytes, err := serder.ObjectToJSON(req.Plan)
  183. // 反序列化 Plan
  184. plan, err := serder.JSONToObjectEx[exec.Plan](planBytes)
  185. if err != nil {
  186. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("deserializing plan: %v", err)})
  187. return
  188. }
  189. logger.WithField("PlanID", plan.ID).Infof("begin execute io plan")
  190. defer logger.WithField("PlanID", plan.ID).Infof("plan finished")
  191. sw := exec.NewExecutor(plan)
  192. s.svc.swWorker.Add(sw)
  193. defer s.svc.swWorker.Remove(sw)
  194. // 设置上下文超时
  195. c, cancel := context.WithTimeout(ctx.Request.Context(), time.Second*30)
  196. defer cancel()
  197. _, err = sw.Run(c)
  198. if err != nil {
  199. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("running io plan: %v", err)})
  200. return
  201. }
  202. ctx.JSON(http.StatusOK, gin.H{"message": "plan executed successfully"})
  203. }
  204. func (s *IOService) SendVar(ctx *gin.Context) {
  205. var req cdsapi.SendVarReq
  206. if err := ctx.ShouldBindJSON(&req); err != nil {
  207. logger.Warnf("binding body: %s", err.Error())
  208. ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
  209. return
  210. }
  211. c, cancel := context.WithTimeout(ctx.Request.Context(), time.Second*30)
  212. defer cancel()
  213. sw := s.svc.swWorker.FindByIDContexted(c, req.PlanID)
  214. if sw == nil {
  215. ctx.JSON(http.StatusNotFound, gin.H{"error": "plan not found"})
  216. return
  217. }
  218. VarBytes, err := serder.ObjectToJSON(req.Var)
  219. v, err := serder.JSONToObjectEx[exec.Var](VarBytes)
  220. if err != nil {
  221. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("deserializing var: %v", err)})
  222. return
  223. }
  224. sw.PutVars(v)
  225. ctx.JSON(http.StatusOK, gin.H{"message": "var sent successfully"})
  226. }
  227. func (s *IOService) GetVar(ctx *gin.Context) {
  228. var req cdsapi.GetVarReq
  229. if err := ctx.ShouldBindJSON(&req); err != nil {
  230. logger.Warnf("binding body: %s", err.Error())
  231. ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
  232. return
  233. }
  234. c, cancel := context.WithTimeout(ctx.Request.Context(), time.Second*30)
  235. defer cancel()
  236. sw := s.svc.swWorker.FindByIDContexted(c, req.PlanID)
  237. if sw == nil {
  238. ctx.JSON(http.StatusNotFound, gin.H{"error": "plan not found"})
  239. return
  240. }
  241. VarBytes, err := serder.ObjectToJSON(req.Var)
  242. v, err := serder.JSONToObjectEx[exec.Var](VarBytes)
  243. if err != nil {
  244. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("deserializing var: %v", err)})
  245. return
  246. }
  247. SignalBytes, err := serder.ObjectToJSON(req.Signal)
  248. signal, err := serder.JSONToObjectEx[*exec.SignalVar](SignalBytes)
  249. if err != nil {
  250. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("deserializing signal: %v", err)})
  251. return
  252. }
  253. sw.PutVars(signal)
  254. err = sw.BindVars(c, v)
  255. if err != nil {
  256. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("binding vars: %v", err)})
  257. return
  258. }
  259. vd, err := serder.ObjectToJSONEx(v)
  260. if err != nil {
  261. ctx.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("serializing var: %v", err)})
  262. return
  263. }
  264. ctx.JSON(http.StatusOK, gin.H{"var": string(vd)})
  265. }

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。