cache.go 837 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package network
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "io/ioutil"
  6. "os"
  7. "github.com/rancher/os/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. }