Skip to content

Commit

Permalink
Feature/sdk (#114)
Browse files Browse the repository at this point in the history
* update

* clean

* remove tablewriter

* add cluster functions to sdk

* add namespaces crud functions & update docs

* Add job crud

* update
  • Loading branch information
Clivern authored Jun 16, 2020
1 parent 063737d commit 2db820a
Show file tree
Hide file tree
Showing 17 changed files with 898 additions and 42 deletions.
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ require (
github.com/gin-gonic/gin v1.6.3
github.com/imdario/mergo v0.3.9 // indirect
github.com/jinzhu/gorm v1.9.13
github.com/olekukonko/tablewriter v0.0.4
github.com/prometheus/client_golang v1.6.0
github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.6.0
Expand Down
8 changes: 0 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,6 @@ github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD87
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
Expand Down Expand Up @@ -180,8 +178,6 @@ github.com/imdario/mergo v0.3.9 h1:UauaLniWCFHWd+Jp9oCEkTBj8VO/9DKg3PV3VCNMDIg=
github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jinzhu/gorm v1.9.12 h1:Drgk1clyWT9t9ERbzHza6Mj/8FY/CqMyVzOiHviMo6Q=
github.com/jinzhu/gorm v1.9.12/go.mod h1:vhTjlKSJUTWNtcbQtrMBFCxy7eXTzeCAzfL5fBZT/Qs=
github.com/jinzhu/gorm v1.9.13 h1:fcdacwmUcoyon8XHkQrdPJZ7pnHAYclHZ6iLYER5nX4=
github.com/jinzhu/gorm v1.9.13/go.mod h1:C0zfmO9z9J61PGrs46nfRkfsq0/8ErGTKBxyudR2KvI=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
Expand Down Expand Up @@ -221,8 +217,6 @@ github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaO
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v2.0.1+incompatible h1:xQ15muvnzGBHpIpdrNi1DA5x0+TcBZzsIDwmw9uTHzw=
github.com/mattn/go-sqlite3 v2.0.1+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
Expand All @@ -247,8 +241,6 @@ github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8m
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/olekukonko/tablewriter v0.0.4 h1:vHD/YYe1Wolo78koG299f7V/VAS08c6IpCLn+Ejf/w8=
github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA=
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.11.0 h1:JAKSXpt1YjtLA7YpPiqO9ss6sNXEsPfSGdwN0UHqzrw=
Expand Down
4 changes: 3 additions & 1 deletion internal/app/controller/jobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,7 @@ func Jobs(c *gin.Context) {

defer db.Close()

c.JSON(http.StatusOK, db.GetJobs())
c.JSON(http.StatusOK, gin.H{
"jobs": db.GetJobs(),
})
}
3 changes: 2 additions & 1 deletion internal/app/controller/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package controller
import (
"context"
"fmt"
"strings"
"time"

"github.com/clivern/beetle/internal/app/kubernetes"
Expand Down Expand Up @@ -101,7 +102,7 @@ func Worker(workerID int, messages <-chan string) {
}).Info(`Worker accepted deployment request`)

// Notify if there is a webhook
if viper.GetString("app.webhook.url") != "" {
if strings.TrimSpace(viper.GetString("app.webhook.url")) != "" {
uuid = util.GenerateUUID4()

for db.JobExistByUUID(uuid) {
Expand Down
23 changes: 23 additions & 0 deletions internal/app/model/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ type Cluster struct {
Health bool `json:"health"`
}

// Clusters struct
type Clusters struct {
Clusters []Cluster `json:"clusters"`
}

// LoadFromJSON update object from json
func (c *Cluster) LoadFromJSON(data []byte) (bool, error) {
err := json.Unmarshal(data, &c)
Expand All @@ -31,3 +36,21 @@ func (c *Cluster) ConvertToJSON() (string, error) {
}
return string(data), nil
}

// LoadFromJSON update object from json
func (c *Clusters) LoadFromJSON(data []byte) (bool, error) {
err := json.Unmarshal(data, &c)
if err != nil {
return false, err
}
return true, nil
}

// ConvertToJSON convert object to json
func (c *Clusters) ConvertToJSON() (string, error) {
data, err := json.Marshal(&c)
if err != nil {
return "", err
}
return string(data), nil
}
23 changes: 23 additions & 0 deletions internal/app/model/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ type Job struct {
UpdatedAt time.Time `json:"updated_at"`
}

// Jobs struct
type Jobs struct {
Jobs []Job `json:"jobs"`
}

// LoadFromJSON update object from json
func (j *Job) LoadFromJSON(data []byte) (bool, error) {
err := json.Unmarshal(data, &j)
Expand All @@ -61,3 +66,21 @@ func (j *Job) ConvertToJSON() (string, error) {
}
return string(data), nil
}

// LoadFromJSON update object from json
func (j *Jobs) LoadFromJSON(data []byte) (bool, error) {
err := json.Unmarshal(data, &j)
if err != nil {
return false, err
}
return true, nil
}

// ConvertToJSON convert object to json
func (j *Jobs) ConvertToJSON() (string, error) {
data, err := json.Marshal(&j)
if err != nil {
return "", err
}
return string(data), nil
}
23 changes: 23 additions & 0 deletions internal/app/model/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ type Namespace struct {
Status string `json:"status"`
}

// Namespaces struct
type Namespaces struct {
Namespaces []Namespace `json:"namespaces"`
}

// LoadFromJSON update object from json
func (d *Namespace) LoadFromJSON(data []byte) (bool, error) {
err := json.Unmarshal(data, &d)
Expand All @@ -32,3 +37,21 @@ func (d *Namespace) ConvertToJSON() (string, error) {
}
return string(data), nil
}

// LoadFromJSON update object from json
func (d *Namespaces) LoadFromJSON(data []byte) (bool, error) {
err := json.Unmarshal(data, &d)
if err != nil {
return false, err
}
return true, nil
}

// ConvertToJSON convert object to json
func (d *Namespaces) ConvertToJSON() (string, error) {
data, err := json.Marshal(&d)
if err != nil {
return "", err
}
return string(data), nil
}
30 changes: 0 additions & 30 deletions internal/app/module/tablewriter.go

This file was deleted.

3 changes: 2 additions & 1 deletion pkg/server_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import (
)

// ServerMock mocks http server
func ServerMock(uri, response string) *httptest.Server {
func ServerMock(uri, response string, statusCode int) *httptest.Server {
handler := http.NewServeMux()
handler.HandleFunc(uri, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(statusCode)
w.Write([]byte(response))
})

Expand Down
File renamed without changes.
89 changes: 89 additions & 0 deletions sdk/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,92 @@
// license that can be found in the LICENSE file.

package sdk

import (
"context"
"fmt"
"net/http"

"github.com/clivern/beetle/internal/app/model"
"github.com/clivern/beetle/internal/app/module"
)

// GetClusters Get Clusters List
func GetClusters(ctx context.Context, httpClient *module.HTTPClient, serverURL, token string) (model.Clusters, error) {
var result model.Clusters

response, err := httpClient.Get(
ctx,
fmt.Sprintf("%s/api/v1/cluster", serverURL),
map[string]string{},
map[string]string{"X-AUTH-TOKEN": token},
)

if err != nil {
return result, err
}

statusCode := httpClient.GetStatusCode(response)

if statusCode != http.StatusOK {
return result, fmt.Errorf(fmt.Sprintf("Invalid status code %d", statusCode))
}

body, err := httpClient.ToString(response)

if err != nil {
return result, fmt.Errorf(fmt.Sprintf("Invalid response: %s", err.Error()))
}

ok, err := result.LoadFromJSON([]byte(body))

if err != nil {
return result, fmt.Errorf(fmt.Sprintf("Invalid response: %s", err.Error()))
}

if !ok {
return result, fmt.Errorf("Invalid response")
}

return result, nil
}

// GetCluster Get Cluster
func GetCluster(ctx context.Context, httpClient *module.HTTPClient, serverURL, cluster, token string) (model.Cluster, error) {
var result model.Cluster

response, err := httpClient.Get(
ctx,
fmt.Sprintf("%s/api/v1/cluster/%s", serverURL, cluster),
map[string]string{},
map[string]string{"X-AUTH-TOKEN": token},
)

if err != nil {
return result, err
}

statusCode := httpClient.GetStatusCode(response)

if statusCode != http.StatusOK {
return result, fmt.Errorf(fmt.Sprintf("Invalid status code %d", statusCode))
}

body, err := httpClient.ToString(response)

if err != nil {
return result, fmt.Errorf(fmt.Sprintf("Invalid response: %s", err.Error()))
}

ok, err := result.LoadFromJSON([]byte(body))

if err != nil {
return result, fmt.Errorf(fmt.Sprintf("Invalid response: %s", err.Error()))
}

if !ok {
return result, fmt.Errorf("Invalid response")
}

return result, nil
}
89 changes: 89 additions & 0 deletions sdk/cluster_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright 2020 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package sdk

import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"testing"

"github.com/clivern/beetle/internal/app/model"
"github.com/clivern/beetle/internal/app/module"
"github.com/clivern/beetle/pkg"

"github.com/drone/envsubst"
"github.com/spf13/viper"
)

// TestClusterCRUD test cases
func TestClusterCRUD(t *testing.T) {
testingConfig := "config.testing.yml"
httpClient := module.NewHTTPClient()

// LoadConfigFile
t.Run("LoadConfigFile", func(t *testing.T) {
fs := module.FileSystem{}

dir, _ := os.Getwd()
configFile := fmt.Sprintf("%s/%s", dir, testingConfig)

for {
if fs.FileExists(configFile) {
break
}
dir = filepath.Dir(dir)
configFile = fmt.Sprintf("%s/%s", dir, testingConfig)
}

t.Logf("Load Config File %s", configFile)

configUnparsed, _ := ioutil.ReadFile(configFile)
configParsed, _ := envsubst.EvalEnv(string(configUnparsed))
viper.SetConfigType("yaml")
viper.ReadConfig(bytes.NewBuffer([]byte(configParsed)))
})

// TestGetClusters
t.Run("TestGetClusters", func(t *testing.T) {
srv := pkg.ServerMock(
"/api/v1/cluster",
`{"clusters": [{"name": "staging", "health": false},{"name": "production", "health": true}]}`,
http.StatusOK,
)

defer srv.Close()

result, err := GetClusters(context.TODO(), httpClient, srv.URL, "")

pkg.Expect(t, nil, err)
pkg.Expect(t, result, model.Clusters{
Clusters: []model.Cluster{
model.Cluster{Name: "staging", Health: false},
model.Cluster{Name: "production", Health: true},
},
})
})

// TestGetCluster
t.Run("TestGetCluster", func(t *testing.T) {
srv := pkg.ServerMock(
"/api/v1/cluster/staging",
`{"name": "staging", "health": false}`,
http.StatusOK,
)

defer srv.Close()

result, err := GetCluster(context.TODO(), httpClient, srv.URL, "staging", "")

pkg.Expect(t, nil, err)
pkg.Expect(t, result, model.Cluster{Name: "staging", Health: false})
})
}
Loading

0 comments on commit 2db820a

Please sign in to comment.