Skip to content

Commit

Permalink
Merge pull request #267 from subutai-io/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
Emil authored Feb 28, 2018
2 parents 16ba143 + 2b6173c commit a307a2e
Show file tree
Hide file tree
Showing 10 changed files with 357 additions and 97 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
gorjun
my.db
gorjun_*
gorjun_
10 changes: 5 additions & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ language: go

sudo: enabled
go:
- 1.9.4
- '1.10'
script:
- go get
- make
- sudo apt-get install systemd
- sudo cp -f /home/travis/gopath/src/github.com/subutai-io/gorjun/libgorjun/gorjun.service /etc/systemd/system/gorjun.service
- sudo cp -f /home/travis/gopath/src/github.com/subutai-io/cdn/libgorjun/gorjun.service /etc/systemd/system/gorjun.service
- sudo systemctl daemon-reload
- sudo systemctl start gorjun.service
- sudo systemctl status gorjun.service
- sudo apt install -y rng-tools
- sudo rngd -r /dev/urandom
- gpg --gen-key --batch /home/travis/gopath/src/github.com/subutai-io/gorjun/libgorjun/gpg.txt
- gpg --gen-key --batch /home/travis/gopath/src/github.com/subutai-io/cdn/libgorjun/gpg.txt
- sudo chmod +x /home/travis/gopath/src/github.com/subutai-io/gorjun/libgorjun/register.sh
- cd /home/travis/gopath/src/github.com/subutai-io/gorjun/libgorjun/; ./register.sh
- cd /home/travis/gopath/src/github.com/subutai-io/gorjun/libgorjun; go get github.com/stretchr/testify/assert;
- cd /home/travis/gopath/src/github.com/subutai-io/cdn/libgorjun/; ./register.sh
- cd /home/travis/gopath/src/github.com/subutai-io/cdn/libgorjun; go get github.com/stretchr/testify/assert;
- go test -v
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
[![Build Status](https://travis-ci.org/subutai-io/gorjun.svg?branch=master)](https://travis-ci.org/subutai-io/gorjun)
# Gorjun
Gorjun is a golang replacement for Kurjun project. Kurjun is Subutai's CDN software.

## Vagrant

Use vagrant to create a multi-machine development and testing environment in an internal network. The master vm builds, configures and runs Gorjun. The cdn\[1-n] nodes are NGINX CDN cache nodes.

> vagrant up
Expand Down
143 changes: 60 additions & 83 deletions apt/apt.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package apt

import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"io"
Expand All @@ -18,6 +17,7 @@ import (

"github.com/mkrautz/goar"
"github.com/subutai-io/agent/log"
"os/exec"
)

func readDeb(hash string) (control bytes.Buffer, err error) {
Expand Down Expand Up @@ -77,28 +77,6 @@ func getSize(file string) (size string) {
return size
}

func writePackage(meta map[string]string) {
var f *os.File
if _, err := os.Stat(config.Storage.Path + "Packages"); os.IsNotExist(err) {
f, err = os.Create(config.Storage.Path + "Packages")
log.Check(log.WarnLevel, "Creating packages file", err)
defer f.Close()
} else if err == nil {
f, err = os.OpenFile(config.Storage.Path+"Packages", os.O_APPEND|os.O_WRONLY, 0600)
log.Check(log.WarnLevel, "Opening packages file", err)
defer f.Close()
} else {
log.Warn(err.Error())
}

for k, v := range meta {
_, err := f.WriteString(string(k) + ": " + string(v) + "\n")
log.Check(log.WarnLevel, "Appending package data", err)
}
_, err := f.Write([]byte("\n"))
log.Check(log.WarnLevel, "Appending endline", err)
}

func Upload(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
_, header, _ := r.FormFile("file")
Expand All @@ -124,10 +102,11 @@ func Upload(w http.ResponseWriter, r *http.Request) {
meta["SHA1"] = upload.Hash(config.Storage.Path+md5, "sha1")
meta["MD5sum"] = md5
meta["type"] = "apt"
writePackage(meta)
db.Write(owner, md5, header.Filename, meta)
w.Write([]byte(md5))
log.Info(meta["Filename"] + " saved to apt repo by " + owner)
os.Rename(config.Storage.Path+md5, config.Storage.Path+header.Filename)
renameOldDebFiles()
}
}

Expand All @@ -136,10 +115,10 @@ func Download(w http.ResponseWriter, r *http.Request) {
if len(file) == 0 {
file = strings.TrimPrefix(r.RequestURI, "/kurjun/rest/apt/")
}
if file != "Packages" && file != "InRelease" && file != "Release" {
file = db.LastHash(file, "apt")
size := getSize(config.Storage.Path + "Packages")
if file == "Packages" && (size == "" || size == "0"){
GenerateReleaseFile()
}

if f, err := os.Open(config.Storage.Path + file); err == nil && file != "" {
defer f.Close()
io.Copy(w, f)
Expand All @@ -148,65 +127,9 @@ func Download(w http.ResponseWriter, r *http.Request) {
}
}

func readPackages() []string {
file, err := os.Open(config.Storage.Path + "Packages")
log.Check(log.WarnLevel, "Opening packages file", err)
defer file.Close()

var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
log.Check(log.WarnLevel, "Scanning packages list", scanner.Err())
return lines
}

func deleteInfo(hash string) {
list := readPackages()
if len(list) == 0 {
log.Warn("Empty packages list")
return
}

var newlist, block string
changed, skip := false, false
for _, line := range list {
if len(line) != 0 && skip {
continue
} else if len(line) == 0 {
skip = false
if len(block) != 0 {
newlist = newlist + block + "\n"
block = ""
}
} else if len(line) != 0 && !skip {
if strings.HasSuffix(line, hash) {
block = ""
skip = true
changed = true
} else {
block = block + line + "\n"
}
}
}
if changed {
log.Info("Updating packages list")
file, err := os.Create(config.Storage.Path + "Packages.new")
log.Check(log.WarnLevel, "Opening packages file", err)
defer file.Close()

_, err = file.WriteString(newlist)
log.Check(log.WarnLevel, "Writing new list", err)
log.Check(log.WarnLevel, "Replacing old list",
os.Rename(config.Storage.Path+"Packages.new", config.Storage.Path+"Packages"))
}
}

func Delete(w http.ResponseWriter, r *http.Request) {
if r.Method == "DELETE" {
if hash := upload.Delete(w, r); len(hash) != 0 {
deleteInfo(hash)
w.Write([]byte("Removed"))
return
}
Expand All @@ -222,4 +145,58 @@ func Info(w http.ResponseWriter, r *http.Request) {
return
}
w.Write([]byte("Not found"))
}

func renameOldDebFiles() {
list := db.Search("")
for _, k := range list {
if db.CheckRepo("", "apt", k) == 0 {
continue
}
item := download.FormatItem(db.Info(k), "apt", "")
os.Rename(config.Storage.Path+item.Hash.Md5, config.Storage.Path+item.Name)
}
}

func GenerateReleaseFile() {
cmd := exec.Command("bash", "-c", "dpkg-scanpackages . /dev/null | tee Packages | gzip > Packages.gz")
cmd.Dir = config.Storage.Path
err := cmd.Run()
if err != nil {
log.Fatal(err)
log.Info("Can't run dpkg-scanpackages")
}

cmd = exec.Command("bash", "-c", "apt-ftparchive release . > Release")
cmd.Dir = config.Storage.Path
err = cmd.Run()
if err != nil {
log.Fatal(err)
log.Info("Can't run apt-ftparchive")
}
cmd = exec.Command("bash", "-c", "gpg --batch --yes --armor -u [email protected] -abs -o Release.gpg Release")
cmd.Dir = config.Storage.Path
err = cmd.Run()
if err != nil {
log.Fatal(err)
log.Info("Can't sign Realease file")
}
}

func Generate(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
owner := strings.ToLower(db.CheckToken(token))
if len(token) == 0 || len(owner) == 0 {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Not authorized"))
log.Warn(r.RemoteAddr + " - rejecting generate request")
return
}
if owner != "subutai" && owner != "jenkins" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Only allowed users can generate release file"))
log.Warn(r.RemoteAddr + " - rejecting generate request")
return
}
GenerateReleaseFile()
}
26 changes: 22 additions & 4 deletions download/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/subutai-io/gorjun/config"
"github.com/subutai-io/gorjun/db"
"github.com/blang/semver"
"net/url"
)

// ListItem describes Gorjun entity. It can be APT package, Subutai template or Raw file.
Expand Down Expand Up @@ -146,7 +147,9 @@ func Info(repo string, r *http.Request) []byte {
log.Check(log.DebugLevel, "Looking for artifacts with tag "+tag, err)
list = intersect(list, listByTag)
}

if onlyOneParameterProvided("name",r) {
verified = "true"
}
if len(id) > 0 {
list = append(list[:0], id)
} else if verified == "true" {
Expand Down Expand Up @@ -217,18 +220,23 @@ func in(str string, list []string) bool {
}

func getVerified(list []string, name, repo string) ListItem {
latestVersion, _ := semver.Make("0.0.0")
var itemLatestVersion ListItem
for _, k := range list {
if info := db.Info(k); db.CheckRepo("", repo, k) > 0 {
if info["name"] == name || (strings.HasPrefix(info["name"], name+"-subutai-template") && repo == "template") {
for _, owner := range db.FileField(info["id"], "owner") {
if in(owner, []string{"subutai", "jenkins", "docker"}) {
return FormatItem(info, repo, name)
itemVersion, _:= semver.Make(info["version"])
if in(owner, []string{"subutai", "jenkins", "docker"}) &&
itemVersion.Compare(latestVersion) == 1 {
latestVersion = itemVersion
itemLatestVersion = FormatItem(db.Info(k), repo, name)
}
}
}
}
}
return ListItem{}
return itemLatestVersion
}

func FormatItem(info map[string]string, repo, name string) ListItem {
Expand Down Expand Up @@ -279,3 +287,13 @@ func intersect(listA, listB []string) (list []string) {
return list
}

func onlyOneParameterProvided(parameter string,r *http.Request) bool {
u, _ := url.Parse(r.RequestURI)
parameters, _ := url.ParseQuery(u.RawQuery)
for key, _ := range parameters {
if key != parameter {
return false
}
}
return len(parameters) > 0
}
2 changes: 1 addition & 1 deletion libgorjun/gorjun.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (g *GorjunServer) ListUserFiles() ([]GorjunFile, error) {

// GetFileByName will return information about a file with specified name
func (g *GorjunServer) GetFileByName(filename string,artifactType string) ([]GorjunFile, error) {
resp, err := http.Get(fmt.Sprintf("http://%s/kurjun/rest/%s/info?name=%s", g.Hostname,artifactType,filename))
resp, err := http.Get(fmt.Sprintf("http://%s/kurjun/rest/%s/info?name=%s&owner=%s", g.Hostname,artifactType,filename,g.Username))
if err != nil {
return nil, fmt.Errorf("Failed to retrieve file information from %s: %v", g.Hostname, err)
}
Expand Down
2 changes: 1 addition & 1 deletion libgorjun/gorjun.service
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Description=Subutai Kurjun Server
After=network.target auditd.service
[Service]
ExecStart=
ExecStart=/home/travis/gopath/src/github.com/subutai-io/gorjun/gorjun
ExecStart=/home/travis/gopath/src/github.com/subutai-io/cdn/gorjun
Restart=on-failure
Type=simple
[Install]
Expand Down
Loading

0 comments on commit a307a2e

Please sign in to comment.