hardlinks.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright The containerd Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package continuity
  14. import (
  15. "fmt"
  16. "os"
  17. )
  18. var (
  19. errNotAHardLink = fmt.Errorf("invalid hardlink")
  20. )
  21. type hardlinkManager struct {
  22. hardlinks map[hardlinkKey][]Resource
  23. }
  24. func newHardlinkManager() *hardlinkManager {
  25. return &hardlinkManager{
  26. hardlinks: map[hardlinkKey][]Resource{},
  27. }
  28. }
  29. // Add attempts to add the resource to the hardlink manager. If the resource
  30. // cannot be considered as a hardlink candidate, errNotAHardLink is returned.
  31. func (hlm *hardlinkManager) Add(fi os.FileInfo, resource Resource) error {
  32. if _, ok := resource.(Hardlinkable); !ok {
  33. return errNotAHardLink
  34. }
  35. key, err := newHardlinkKey(fi)
  36. if err != nil {
  37. return err
  38. }
  39. hlm.hardlinks[key] = append(hlm.hardlinks[key], resource)
  40. return nil
  41. }
  42. // Merge processes the current state of the hardlink manager and merges any
  43. // shared nodes into hardlinked resources.
  44. func (hlm *hardlinkManager) Merge() ([]Resource, error) {
  45. var resources []Resource
  46. for key, linked := range hlm.hardlinks {
  47. if len(linked) < 1 {
  48. return nil, fmt.Errorf("no hardlink entrys for dev, inode pair: %#v", key)
  49. }
  50. merged, err := Merge(linked...)
  51. if err != nil {
  52. return nil, fmt.Errorf("error merging hardlink: %v", err)
  53. }
  54. resources = append(resources, merged)
  55. }
  56. return resources, nil
  57. }