Skip to content

Commit

Permalink
enhance the iamge download logic to avoid stale images
Browse files Browse the repository at this point in the history
  • Loading branch information
mhewedy committed Apr 27, 2020
1 parent 3a09ac4 commit f5e0f18
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 8 deletions.
41 changes: 36 additions & 5 deletions images/images.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"github.com/mhewedy/vermin/cmd"
"github.com/mhewedy/vermin/db"
"io"
"io/ioutil"
"os"
"strings"
)
Expand Down Expand Up @@ -109,14 +111,21 @@ func download(r *rimage) error {
fmt.Printf("Image '%s' could not be found. Attempting to find and install...\n", r.Name)
fmt.Printf("Downloading: %s", r.URL)

sp := strings.Split(r.Name, "/")
vmBasePath := db.GetImagesDir() + "/" + sp[0]

if err := os.MkdirAll(vmBasePath, 0755); err != nil {
// download to a temp file
tmpFile, err := ioutil.TempFile("", strings.ReplaceAll(r.Name, "/", "_"))
if err != nil {
return err
}
defer os.Remove(tmpFile.Name())
if _, err := cmd.ExecuteP("wget", "-O", tmpFile.Name(), r.URL); err != nil {
return err
}

if _, err := cmd.ExecuteP("wget", "-O", vmBasePath+"/"+sp[1]+".ova", r.URL); err != nil {
// copy the downloaded file to images directory
if err := os.MkdirAll(db.GetImagesDir()+"/"+strings.Split(r.Name, "/")[0], 0755); err != nil {
return err
}
if err := copyFile(tmpFile.Name(), db.GetImagesDir()+"/"+r.Name+".ova"); err != nil {
return err
}
return nil
Expand All @@ -130,3 +139,25 @@ func contains(a []string, s string) bool {
}
return false
}

// Copy the src file to dst. Any existing file will be overwritten and will not
// copy file attributes.
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()

out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()

_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}
6 changes: 3 additions & 3 deletions images/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ func listRemoteImages() ([]rimage, error) {
if err != nil {
return nil, err
}
defer tmpFile.Close()
tmp = tmpFile.Name()
_, err = cmd.Execute("wget", "-O", tmp,
"https://raw.githubusercontent.com/mhewedy/vermin/master/images/images.csv")
if err != nil {
if _, err = cmd.Execute("wget", "-O", tmp,
"https://raw.githubusercontent.com/mhewedy/vermin/master/images/images.csv"); err != nil {
return nil, err
}
}
Expand Down

0 comments on commit f5e0f18

Please sign in to comment.