zeroclean.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package zeroclean
  15. import (
  16. "os"
  17. "path/filepath"
  18. "yunion.io/x/log"
  19. "yunion.io/x/pkg/errors"
  20. )
  21. func ZeroFile(filename string) error {
  22. log.Debugf("zerofile %s", filename)
  23. f, err := os.OpenFile(filename, os.O_RDWR, 0644)
  24. if err != nil {
  25. return errors.Wrap(err, "os.OpenFile")
  26. }
  27. defer func() {
  28. f.Sync()
  29. f.Close()
  30. }()
  31. info, err := f.Stat()
  32. if err != nil {
  33. return errors.Wrap(err, "f.Stat")
  34. }
  35. zeroBuf := make([]byte, 4096)
  36. offset := int64(0)
  37. for offset < info.Size() {
  38. if offset+int64(len(zeroBuf)) > info.Size() {
  39. zeroBuf = zeroBuf[:info.Size()-offset]
  40. }
  41. n, err := f.WriteAt(zeroBuf, offset)
  42. if err != nil {
  43. return errors.Wrapf(err, "zero at %d", offset)
  44. }
  45. offset += int64(n)
  46. }
  47. return nil
  48. }
  49. func ZeroDir(dirname string) error {
  50. err := filepath.Walk(dirname, func(path string, d os.FileInfo, err error) error {
  51. if err != nil {
  52. return errors.Wrapf(err, "WalkDIr %s", path)
  53. }
  54. if !d.IsDir() {
  55. err := ZeroFile(path)
  56. if err != nil {
  57. return errors.Wrapf(err, "Zerofiles %s", path)
  58. }
  59. }
  60. return nil
  61. })
  62. return errors.Wrap(err, "filepath.WalkDir")
  63. }