cache.go 969 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package network
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "io/ioutil"
  6. "os"
  7. "github.com/rancher/os/pkg/log"
  8. )
  9. const (
  10. cacheDirectory = "/var/lib/rancher/cache/"
  11. )
  12. func locationHash(location string) string {
  13. sum := md5.Sum([]byte(location))
  14. return hex.EncodeToString(sum[:])
  15. }
  16. func cacheLookup(location string) []byte {
  17. cacheFile := cacheDirectory + locationHash(location)
  18. bytes, err := ioutil.ReadFile(cacheFile)
  19. if err == nil {
  20. log.Debugf("Using cached file: %s", cacheFile)
  21. return bytes
  22. }
  23. return nil
  24. }
  25. func cacheAdd(location string, data []byte) {
  26. tempFile, err := ioutil.TempFile(cacheDirectory, "")
  27. if err != nil {
  28. return
  29. }
  30. defer os.Remove(tempFile.Name())
  31. _, err = tempFile.Write(data)
  32. if err != nil {
  33. return
  34. }
  35. cacheFile := cacheDirectory + locationHash(location)
  36. os.Rename(tempFile.Name(), cacheFile)
  37. }
  38. func cacheRemove(location string) error {
  39. cacheFile := cacheDirectory + locationHash(location)
  40. return os.Remove(cacheFile)
  41. }