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

630 lines
19 KiB

4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
5 years ago
5 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
  1. package shell
  2. import (
  3. "bufio"
  4. "context"
  5. "flag"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "math"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. "sync"
  16. "github.com/chrislusf/seaweedfs/weed/filer"
  17. "github.com/chrislusf/seaweedfs/weed/operation"
  18. "github.com/chrislusf/seaweedfs/weed/pb"
  19. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  20. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  21. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  22. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  23. "github.com/chrislusf/seaweedfs/weed/storage/needle_map"
  24. "github.com/chrislusf/seaweedfs/weed/storage/types"
  25. "github.com/chrislusf/seaweedfs/weed/util"
  26. )
  27. func init() {
  28. Commands = append(Commands, &commandVolumeFsck{})
  29. }
  30. type commandVolumeFsck struct {
  31. env *CommandEnv
  32. }
  33. func (c *commandVolumeFsck) Name() string {
  34. return "volume.fsck"
  35. }
  36. func (c *commandVolumeFsck) Help() string {
  37. return `check all volumes to find entries not used by the filer
  38. Important assumption!!!
  39. the system is all used by one filer.
  40. This command works this way:
  41. 1. collect all file ids from all volumes, as set A
  42. 2. collect all file ids from the filer, as set B
  43. 3. find out the set A subtract B
  44. If -findMissingChunksInFiler is enabled, this works
  45. in a reverse way:
  46. 1. collect all file ids from all volumes, as set A
  47. 2. collect all file ids from the filer, as set B
  48. 3. find out the set B subtract A
  49. `
  50. }
  51. func (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  52. fsckCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  53. verbose := fsckCommand.Bool("v", false, "verbose mode")
  54. findMissingChunksInFiler := fsckCommand.Bool("findMissingChunksInFiler", false, "see \"help volume.fsck\"")
  55. findMissingChunksInFilerPath := fsckCommand.String("findMissingChunksInFilerPath", "/", "used together with findMissingChunksInFiler")
  56. applyPurging := fsckCommand.Bool("reallyDeleteFromVolume", false, "<expert only!> after detection, delete missing data from volumes / delete missing file entries from filer")
  57. purgeAbsent := fsckCommand.Bool("reallyDeleteFilerEntries", false, "<expert only!> delete missing file entries from filer if the corresponding volume is missing for any reason, please ensure all still existing/expected volumes are connected! used together with findMissingChunksInFiler")
  58. if err = fsckCommand.Parse(args); err != nil {
  59. return nil
  60. }
  61. if err = commandEnv.confirmIsLocked(args); err != nil {
  62. return
  63. }
  64. c.env = commandEnv
  65. // create a temp folder
  66. tempFolder, err := os.MkdirTemp("", "sw_fsck")
  67. if err != nil {
  68. return fmt.Errorf("failed to create temp folder: %v", err)
  69. }
  70. if *verbose {
  71. fmt.Fprintf(writer, "working directory: %s\n", tempFolder)
  72. }
  73. defer os.RemoveAll(tempFolder)
  74. // collect all volume id locations
  75. volumeIdToVInfo, err := c.collectVolumeIds(commandEnv, *verbose, writer)
  76. if err != nil {
  77. return fmt.Errorf("failed to collect all volume locations: %v", err)
  78. }
  79. isBucketsPath := false
  80. var fillerBucketsPath string
  81. if *findMissingChunksInFiler && *findMissingChunksInFilerPath != "" {
  82. fillerBucketsPath, err = readFilerBucketsPath(commandEnv)
  83. if err != nil {
  84. return fmt.Errorf("read filer buckets path: %v", err)
  85. }
  86. if strings.HasPrefix(*findMissingChunksInFilerPath, fillerBucketsPath) {
  87. isBucketsPath = true
  88. }
  89. }
  90. if err != nil {
  91. return fmt.Errorf("read filer buckets path: %v", err)
  92. }
  93. // collect each volume file ids
  94. for volumeId, vinfo := range volumeIdToVInfo {
  95. if isBucketsPath && !strings.HasPrefix(*findMissingChunksInFilerPath, fillerBucketsPath+"/"+vinfo.collection) {
  96. delete(volumeIdToVInfo, volumeId)
  97. continue
  98. }
  99. err = c.collectOneVolumeFileIds(tempFolder, volumeId, vinfo, *verbose, writer)
  100. if err != nil {
  101. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, err)
  102. }
  103. }
  104. if *findMissingChunksInFiler {
  105. // collect all filer file ids and paths
  106. if err = c.collectFilerFileIdAndPaths(volumeIdToVInfo, tempFolder, writer, *findMissingChunksInFilerPath, *verbose, *purgeAbsent); err != nil {
  107. return fmt.Errorf("collectFilerFileIdAndPaths: %v", err)
  108. }
  109. // for each volume, check filer file ids
  110. if err = c.findFilerChunksMissingInVolumeServers(volumeIdToVInfo, tempFolder, writer, *verbose, *applyPurging); err != nil {
  111. return fmt.Errorf("findFilerChunksMissingInVolumeServers: %v", err)
  112. }
  113. } else {
  114. // collect all filer file ids
  115. if err = c.collectFilerFileIds(volumeIdToVInfo, tempFolder, writer, *verbose); err != nil {
  116. return fmt.Errorf("failed to collect file ids from filer: %v", err)
  117. }
  118. // volume file ids subtract filer file ids
  119. if err = c.findExtraChunksInVolumeServers(volumeIdToVInfo, tempFolder, writer, *verbose, *applyPurging); err != nil {
  120. return fmt.Errorf("findExtraChunksInVolumeServers: %v", err)
  121. }
  122. }
  123. return nil
  124. }
  125. func (c *commandVolumeFsck) collectFilerFileIdAndPaths(volumeIdToServer map[uint32]VInfo, tempFolder string, writer io.Writer, filerPath string, verbose bool, purgeAbsent bool) error {
  126. if verbose {
  127. fmt.Fprintf(writer, "checking each file from filer ...\n")
  128. }
  129. files := make(map[uint32]*os.File)
  130. for vid := range volumeIdToServer {
  131. dst, openErr := os.OpenFile(getFilerFileIdFile(tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  132. if openErr != nil {
  133. return fmt.Errorf("failed to create file %s: %v", getFilerFileIdFile(tempFolder, vid), openErr)
  134. }
  135. files[vid] = dst
  136. }
  137. defer func() {
  138. for _, f := range files {
  139. f.Close()
  140. }
  141. }()
  142. type Item struct {
  143. vid uint32
  144. fileKey uint64
  145. cookie uint32
  146. path util.FullPath
  147. }
  148. return doTraverseBfsAndSaving(c.env, nil, filerPath, false, func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  149. if verbose && entry.Entry.IsDirectory {
  150. fmt.Fprintf(writer, "checking directory %s\n", util.NewFullPath(entry.Dir, entry.Entry.Name))
  151. }
  152. dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.Chunks, 0, math.MaxInt64)
  153. if resolveErr != nil {
  154. return nil
  155. }
  156. dataChunks = append(dataChunks, manifestChunks...)
  157. for _, chunk := range dataChunks {
  158. outputChan <- &Item{
  159. vid: chunk.Fid.VolumeId,
  160. fileKey: chunk.Fid.FileKey,
  161. cookie: chunk.Fid.Cookie,
  162. path: util.NewFullPath(entry.Dir, entry.Entry.Name),
  163. }
  164. }
  165. return nil
  166. }, func(outputChan chan interface{}) {
  167. buffer := make([]byte, 16)
  168. for item := range outputChan {
  169. i := item.(*Item)
  170. if f, ok := files[i.vid]; ok {
  171. util.Uint64toBytes(buffer, i.fileKey)
  172. util.Uint32toBytes(buffer[8:], i.cookie)
  173. util.Uint32toBytes(buffer[12:], uint32(len(i.path)))
  174. f.Write(buffer)
  175. f.Write([]byte(i.path))
  176. // fmt.Fprintf(writer, "%d,%x%08x %d %s\n", i.vid, i.fileKey, i.cookie, len(i.path), i.path)
  177. } else {
  178. fmt.Fprintf(writer, "%d,%x%08x %s volume not found\n", i.vid, i.fileKey, i.cookie, i.path)
  179. if purgeAbsent {
  180. fmt.Printf("deleting path %s after volume not found", i.path)
  181. c.httpDelete(i.path, verbose)
  182. }
  183. }
  184. }
  185. })
  186. }
  187. func (c *commandVolumeFsck) findFilerChunksMissingInVolumeServers(volumeIdToVInfo map[uint32]VInfo, tempFolder string, writer io.Writer, verbose bool, applyPurging bool) error {
  188. for volumeId, vinfo := range volumeIdToVInfo {
  189. checkErr := c.oneVolumeFileIdsCheckOneVolume(tempFolder, volumeId, writer, verbose, applyPurging)
  190. if checkErr != nil {
  191. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  192. }
  193. }
  194. return nil
  195. }
  196. func (c *commandVolumeFsck) findExtraChunksInVolumeServers(volumeIdToVInfo map[uint32]VInfo, tempFolder string, writer io.Writer, verbose bool, applyPurging bool) error {
  197. var totalInUseCount, totalOrphanChunkCount, totalOrphanDataSize uint64
  198. for volumeId, vinfo := range volumeIdToVInfo {
  199. inUseCount, orphanFileIds, orphanDataSize, checkErr := c.oneVolumeFileIdsSubtractFilerFileIds(tempFolder, volumeId, writer, verbose)
  200. if checkErr != nil {
  201. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  202. }
  203. totalInUseCount += inUseCount
  204. totalOrphanChunkCount += uint64(len(orphanFileIds))
  205. totalOrphanDataSize += orphanDataSize
  206. if verbose {
  207. for _, fid := range orphanFileIds {
  208. fmt.Fprintf(writer, "%s\n", fid)
  209. }
  210. }
  211. if applyPurging && len(orphanFileIds) > 0 {
  212. if verbose {
  213. fmt.Fprintf(writer, "purging process for volume %d", volumeId)
  214. }
  215. if vinfo.isEcVolume {
  216. fmt.Fprintf(writer, "skip purging for Erasure Coded volume %d.\n", volumeId)
  217. continue
  218. }
  219. needleVID := needle.VolumeId(volumeId)
  220. if vinfo.isReadOnly {
  221. err := markVolumeWritable(c.env.option.GrpcDialOption, needleVID, vinfo.server, true)
  222. if err != nil {
  223. return fmt.Errorf("mark volume %d read/write: %v", volumeId, err)
  224. }
  225. fmt.Fprintf(writer, "temporarily marked %d on server %v writable for forced purge\n", volumeId, vinfo.server)
  226. defer markVolumeWritable(c.env.option.GrpcDialOption, needleVID, vinfo.server, false)
  227. }
  228. fmt.Fprintf(writer, "marked %d on server %v writable for forced purge\n", volumeId, vinfo.server)
  229. if verbose {
  230. fmt.Fprintf(writer, "purging files from volume %d\n", volumeId)
  231. }
  232. if err := c.purgeFileIdsForOneVolume(volumeId, orphanFileIds, writer); err != nil {
  233. return fmt.Errorf("purging volume %d: %v", volumeId, err)
  234. }
  235. }
  236. }
  237. if !applyPurging {
  238. pct := float64(totalOrphanChunkCount*100) / (float64(totalOrphanChunkCount + totalInUseCount))
  239. fmt.Fprintf(writer, "\nTotal\t\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  240. totalOrphanChunkCount+totalInUseCount, totalOrphanChunkCount, pct, totalOrphanDataSize)
  241. fmt.Fprintf(writer, "This could be normal if multiple filers or no filers are used.\n")
  242. }
  243. if totalOrphanChunkCount == 0 {
  244. fmt.Fprintf(writer, "no orphan data\n")
  245. //return nil
  246. }
  247. return nil
  248. }
  249. func (c *commandVolumeFsck) collectOneVolumeFileIds(tempFolder string, volumeId uint32, vinfo VInfo, verbose bool, writer io.Writer) error {
  250. if verbose {
  251. fmt.Fprintf(writer, "collecting volume %d file ids from %s ...\n", volumeId, vinfo.server)
  252. }
  253. return operation.WithVolumeServerClient(false, vinfo.server, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  254. ext := ".idx"
  255. if vinfo.isEcVolume {
  256. ext = ".ecx"
  257. }
  258. copyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  259. VolumeId: volumeId,
  260. Ext: ext,
  261. CompactionRevision: math.MaxUint32,
  262. StopOffset: math.MaxInt64,
  263. Collection: vinfo.collection,
  264. IsEcVolume: vinfo.isEcVolume,
  265. IgnoreSourceFileNotFound: false,
  266. })
  267. if err != nil {
  268. return fmt.Errorf("failed to start copying volume %d%s: %v", volumeId, ext, err)
  269. }
  270. err = writeToFile(copyFileClient, getVolumeFileIdFile(tempFolder, volumeId))
  271. if err != nil {
  272. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, vinfo.server, err)
  273. }
  274. return nil
  275. })
  276. }
  277. func (c *commandVolumeFsck) collectFilerFileIds(volumeIdToServer map[uint32]VInfo, tempFolder string, writer io.Writer, verbose bool) error {
  278. if verbose {
  279. fmt.Fprintf(writer, "collecting file ids from filer ...\n")
  280. }
  281. files := make(map[uint32]*os.File)
  282. for vid := range volumeIdToServer {
  283. dst, openErr := os.OpenFile(getFilerFileIdFile(tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  284. if openErr != nil {
  285. return fmt.Errorf("failed to create file %s: %v", getFilerFileIdFile(tempFolder, vid), openErr)
  286. }
  287. files[vid] = dst
  288. }
  289. defer func() {
  290. for _, f := range files {
  291. f.Close()
  292. }
  293. }()
  294. type Item struct {
  295. vid uint32
  296. fileKey uint64
  297. }
  298. return doTraverseBfsAndSaving(c.env, nil, "/", false, func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  299. dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.Chunks, 0, math.MaxInt64)
  300. if resolveErr != nil {
  301. if verbose {
  302. fmt.Fprintf(writer, "resolving manifest chunks in %s: %v\n", util.NewFullPath(entry.Dir, entry.Entry.Name), resolveErr)
  303. }
  304. return nil
  305. }
  306. dataChunks = append(dataChunks, manifestChunks...)
  307. for _, chunk := range dataChunks {
  308. outputChan <- &Item{
  309. vid: chunk.Fid.VolumeId,
  310. fileKey: chunk.Fid.FileKey,
  311. }
  312. }
  313. return nil
  314. }, func(outputChan chan interface{}) {
  315. buffer := make([]byte, 8)
  316. for item := range outputChan {
  317. i := item.(*Item)
  318. util.Uint64toBytes(buffer, i.fileKey)
  319. files[i.vid].Write(buffer)
  320. }
  321. })
  322. }
  323. func (c *commandVolumeFsck) oneVolumeFileIdsCheckOneVolume(tempFolder string, volumeId uint32, writer io.Writer, verbose bool, applyPurging bool) (err error) {
  324. if verbose {
  325. fmt.Fprintf(writer, "find missing file chunks in volume %d ...\n", volumeId)
  326. }
  327. db := needle_map.NewMemDb()
  328. defer db.Close()
  329. if err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, volumeId)); err != nil {
  330. return
  331. }
  332. file := getFilerFileIdFile(tempFolder, volumeId)
  333. fp, err := os.Open(file)
  334. if err != nil {
  335. return
  336. }
  337. defer fp.Close()
  338. type Item struct {
  339. fileKey uint64
  340. cookie uint32
  341. path util.FullPath
  342. }
  343. br := bufio.NewReader(fp)
  344. buffer := make([]byte, 16)
  345. item := &Item{}
  346. var readSize int
  347. for {
  348. readSize, err = io.ReadFull(br, buffer)
  349. if err != nil || readSize != 16 {
  350. break
  351. }
  352. item.fileKey = util.BytesToUint64(buffer[:8])
  353. item.cookie = util.BytesToUint32(buffer[8:12])
  354. pathSize := util.BytesToUint32(buffer[12:16])
  355. pathBytes := make([]byte, int(pathSize))
  356. n, err := io.ReadFull(br, pathBytes)
  357. if err != nil {
  358. fmt.Fprintf(writer, "%d,%x%08x in unexpected error: %v\n", volumeId, item.fileKey, item.cookie, err)
  359. }
  360. if n != int(pathSize) {
  361. fmt.Fprintf(writer, "%d,%x%08x %d unexpected file name size %d\n", volumeId, item.fileKey, item.cookie, pathSize, n)
  362. }
  363. item.path = util.FullPath(string(pathBytes))
  364. needleId := types.NeedleId(item.fileKey)
  365. if _, found := db.Get(needleId); !found {
  366. fmt.Fprintf(writer, "%s\n", item.path)
  367. if applyPurging {
  368. // defining the URL this way automatically escapes complex path names
  369. c.httpDelete(item.path, verbose)
  370. }
  371. }
  372. }
  373. return nil
  374. }
  375. func (c *commandVolumeFsck) httpDelete(path util.FullPath, verbose bool) {
  376. req, err := http.NewRequest(http.MethodDelete, "", nil)
  377. req.URL = &url.URL{
  378. Scheme: "http",
  379. Host: c.env.option.FilerAddress.ToHttpAddress(),
  380. Path: string(path),
  381. }
  382. if verbose {
  383. fmt.Printf("full HTTP delete request to be sent: %v\n", req)
  384. }
  385. if err != nil {
  386. fmt.Errorf("HTTP delete request error: %v\n", err)
  387. }
  388. client := &http.Client{}
  389. resp, err := client.Do(req)
  390. if err != nil {
  391. fmt.Errorf("DELETE fetch error: %v\n", err)
  392. }
  393. defer resp.Body.Close()
  394. _, err = ioutil.ReadAll(resp.Body)
  395. if err != nil {
  396. fmt.Errorf("DELETE response error: %v\n", err)
  397. }
  398. if verbose {
  399. fmt.Println("delete response Status : ", resp.Status)
  400. fmt.Println("delete response Headers : ", resp.Header)
  401. }
  402. }
  403. func (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(tempFolder string, volumeId uint32, writer io.Writer, verbose bool) (inUseCount uint64, orphanFileIds []string, orphanDataSize uint64, err error) {
  404. db := needle_map.NewMemDb()
  405. defer db.Close()
  406. if err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, volumeId)); err != nil {
  407. return
  408. }
  409. filerFileIdsData, err := os.ReadFile(getFilerFileIdFile(tempFolder, volumeId))
  410. if err != nil {
  411. return
  412. }
  413. dataLen := len(filerFileIdsData)
  414. if dataLen%8 != 0 {
  415. return 0, nil, 0, fmt.Errorf("filer data is corrupted")
  416. }
  417. for i := 0; i < len(filerFileIdsData); i += 8 {
  418. fileKey := util.BytesToUint64(filerFileIdsData[i : i+8])
  419. db.Delete(types.NeedleId(fileKey))
  420. inUseCount++
  421. }
  422. var orphanFileCount uint64
  423. db.AscendingVisit(func(n needle_map.NeedleValue) error {
  424. // fmt.Printf("%d,%x\n", volumeId, n.Key)
  425. orphanFileIds = append(orphanFileIds, fmt.Sprintf("%d,%s00000000", volumeId, n.Key.String()))
  426. orphanFileCount++
  427. orphanDataSize += uint64(n.Size)
  428. return nil
  429. })
  430. if orphanFileCount > 0 {
  431. pct := float64(orphanFileCount*100) / (float64(orphanFileCount + inUseCount))
  432. fmt.Fprintf(writer, "volume:%d\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  433. volumeId, orphanFileCount+inUseCount, orphanFileCount, pct, orphanDataSize)
  434. }
  435. return
  436. }
  437. type VInfo struct {
  438. server pb.ServerAddress
  439. collection string
  440. isEcVolume bool
  441. isReadOnly bool
  442. }
  443. func (c *commandVolumeFsck) collectVolumeIds(commandEnv *CommandEnv, verbose bool, writer io.Writer) (volumeIdToServer map[uint32]VInfo, err error) {
  444. if verbose {
  445. fmt.Fprintf(writer, "collecting volume id and locations from master ...\n")
  446. }
  447. volumeIdToServer = make(map[uint32]VInfo)
  448. // collect topology information
  449. topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
  450. if err != nil {
  451. return
  452. }
  453. eachDataNode(topologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {
  454. for _, diskInfo := range t.DiskInfos {
  455. for _, vi := range diskInfo.VolumeInfos {
  456. volumeIdToServer[vi.Id] = VInfo{
  457. server: pb.NewServerAddressFromDataNode(t),
  458. collection: vi.Collection,
  459. isEcVolume: false,
  460. isReadOnly: vi.ReadOnly,
  461. }
  462. }
  463. for _, ecShardInfo := range diskInfo.EcShardInfos {
  464. volumeIdToServer[ecShardInfo.Id] = VInfo{
  465. server: pb.NewServerAddressFromDataNode(t),
  466. collection: ecShardInfo.Collection,
  467. isEcVolume: true,
  468. isReadOnly: true,
  469. }
  470. }
  471. }
  472. })
  473. if verbose {
  474. fmt.Fprintf(writer, "collected %d volumes and locations.\n", len(volumeIdToServer))
  475. }
  476. return
  477. }
  478. func (c *commandVolumeFsck) purgeFileIdsForOneVolume(volumeId uint32, fileIds []string, writer io.Writer) (err error) {
  479. fmt.Fprintf(writer, "purging orphan data for volume %d...\n", volumeId)
  480. locations, found := c.env.MasterClient.GetLocations(volumeId)
  481. if !found {
  482. return fmt.Errorf("failed to find volume %d locations", volumeId)
  483. }
  484. resultChan := make(chan []*volume_server_pb.DeleteResult, len(locations))
  485. var wg sync.WaitGroup
  486. for _, location := range locations {
  487. wg.Add(1)
  488. go func(server pb.ServerAddress, fidList []string) {
  489. defer wg.Done()
  490. if deleteResults, deleteErr := operation.DeleteFilesAtOneVolumeServer(server, c.env.option.GrpcDialOption, fidList, false); deleteErr != nil {
  491. err = deleteErr
  492. } else if deleteResults != nil {
  493. resultChan <- deleteResults
  494. }
  495. }(location.ServerAddress(), fileIds)
  496. }
  497. wg.Wait()
  498. close(resultChan)
  499. for results := range resultChan {
  500. for _, result := range results {
  501. if result.Error != "" {
  502. fmt.Fprintf(writer, "purge error: %s\n", result.Error)
  503. }
  504. }
  505. }
  506. return
  507. }
  508. func getVolumeFileIdFile(tempFolder string, vid uint32) string {
  509. return filepath.Join(tempFolder, fmt.Sprintf("%d.idx", vid))
  510. }
  511. func getFilerFileIdFile(tempFolder string, vid uint32) string {
  512. return filepath.Join(tempFolder, fmt.Sprintf("%d.fid", vid))
  513. }
  514. func writeToFile(client volume_server_pb.VolumeServer_CopyFileClient, fileName string) error {
  515. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  516. dst, err := os.OpenFile(fileName, flags, 0644)
  517. if err != nil {
  518. return nil
  519. }
  520. defer dst.Close()
  521. for {
  522. resp, receiveErr := client.Recv()
  523. if receiveErr == io.EOF {
  524. break
  525. }
  526. if receiveErr != nil {
  527. return fmt.Errorf("receiving %s: %v", fileName, receiveErr)
  528. }
  529. dst.Write(resp.FileContent)
  530. }
  531. return nil
  532. }