2016-05-25 16:40:28 +00:00
|
|
|
package network
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/md5"
|
|
|
|
"encoding/hex"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2017-03-03 04:02:44 +00:00
|
|
|
"path/filepath"
|
2016-05-25 16:40:28 +00:00
|
|
|
|
2017-03-03 04:02:44 +00:00
|
|
|
"github.com/rancher/os/config"
|
2016-11-23 10:49:35 +00:00
|
|
|
"github.com/rancher/os/log"
|
2016-05-25 16:40:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func locationHash(location string) string {
|
|
|
|
sum := md5.Sum([]byte(location))
|
|
|
|
return hex.EncodeToString(sum[:])
|
|
|
|
}
|
|
|
|
|
2017-03-03 04:02:44 +00:00
|
|
|
func CacheLookup(location string) ([]byte, error) {
|
|
|
|
cacheFile := filepath.Join(config.CacheDirectory, location)
|
2016-05-25 16:40:28 +00:00
|
|
|
bytes, err := ioutil.ReadFile(cacheFile)
|
|
|
|
if err == nil {
|
|
|
|
log.Debugf("Using cached file: %s", cacheFile)
|
2017-03-03 04:02:44 +00:00
|
|
|
return bytes, nil
|
2016-05-25 16:40:28 +00:00
|
|
|
}
|
2017-03-03 04:02:44 +00:00
|
|
|
log.Debugf("Cached file not found: %s", cacheFile)
|
|
|
|
return nil, err
|
2016-05-25 16:40:28 +00:00
|
|
|
}
|
|
|
|
|
2017-03-03 04:02:44 +00:00
|
|
|
func cacheAdd(location string, data []byte) error {
|
|
|
|
os.MkdirAll(config.CacheDirectory, 0755)
|
|
|
|
tempFile, err := ioutil.TempFile(config.CacheDirectory, "")
|
2016-05-25 16:40:28 +00:00
|
|
|
if err != nil {
|
2017-03-03 04:02:44 +00:00
|
|
|
return err
|
2016-05-25 16:40:28 +00:00
|
|
|
}
|
|
|
|
defer os.Remove(tempFile.Name())
|
|
|
|
|
|
|
|
_, err = tempFile.Write(data)
|
|
|
|
if err != nil {
|
2017-03-03 04:02:44 +00:00
|
|
|
return err
|
2016-05-25 16:40:28 +00:00
|
|
|
}
|
|
|
|
|
2017-03-03 04:02:44 +00:00
|
|
|
cacheFile := filepath.Join(config.CacheDirectory, location)
|
|
|
|
cacheDir := filepath.Dir(cacheFile)
|
|
|
|
log.Debugf("writing %s to %s", cacheFile, cacheDir)
|
|
|
|
os.MkdirAll(cacheDir, 0755)
|
2016-05-25 16:40:28 +00:00
|
|
|
os.Rename(tempFile.Name(), cacheFile)
|
2017-03-03 04:02:44 +00:00
|
|
|
return nil
|
2016-05-25 16:40:28 +00:00
|
|
|
}
|