Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: refactor conf of manager api #693

Merged
merged 22 commits into from
Nov 5, 2020
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions .github/workflows/e2e-test-backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@ jobs:
steps:
- uses: actions/checkout@v2

- name: install runtime
run: |
sudo apt-get update
sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt update
export GO111MOUDULE=on
sudo apt install golang-1.14-go
- name: setup go
uses: actions/setup-go@v1
with:
go-version: '1.13'

- name: run docker compose
working-directory: ./api/test/docker
Expand Down
25 changes: 13 additions & 12 deletions .github/workflows/test-api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,19 @@ jobs:
- name: get lua lib
run: |
wget https://github.com/api7/dag-to-lua/archive/v1.1.tar.gz
sudo mkdir -p /go/manager-api/dag-to-lua/
sudo mkdir -p ./api/dag-to-lua
tar -zxvf v1.1.tar.gz
sudo mv ./dag-to-lua-1.1/lib/* /go/manager-api/dag-to-lua/
sudo mv ./dag-to-lua-1.1/lib/* ./api/dag-to-lua/

- name: install runtime
run: |
sudo apt-get update
sudo apt-get install lua5.1
sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt update
export GO111MOUDULE=on
sudo apt install golang-1.14-go
- name: setup go
uses: actions/setup-go@v1
with:
go-version: '1.13'

- name: setup lua
uses: leafo/gh-actions-lua@v7
with:
luaVersion: "5.1.5"

- name: run test
run: |
Expand All @@ -55,12 +56,12 @@ jobs:
run: |
export GO111MOUDULE=on
export APISIX_CONF_PATH=$PWD/conf
sed -i 's/8080/8088/' conf/conf.json
sed -i 's/8080/8088/' conf/conf.yaml
go build -o ./manager-api
./manager-api > ./api.log 2>&1 &
sleep 2
cat ./api.log
cat conf/conf.json
cat conf/conf.yaml

- name: run with custom port
working-directory: ./api
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,5 @@ golang-lint: ## Run the golangci-lint application (install if not found)
### api-test: Run the tests of manager-api
.PHONY: api-test
api-test:
cd api/ && go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./...
cd api/ && APISIX_API_WORKDIR=$$PWD go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./...
membphis marked this conversation as resolved.
Show resolved Hide resolved

6 changes: 3 additions & 3 deletions api/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ FROM golang:1.13.8 AS build-env

WORKDIR /go/src/github.com/apisix/manager-api
COPY . .
RUN mkdir -p /go/manager-api \
RUN mkdir -p /go/manager-api/conf \
&& mkdir -p /go/manager-api/build-tools \
&& go env -w GOPROXY=https://goproxy.io,direct \
&& export GOPROXY=https://goproxy.io \
&& go build -o /go/manager-api/manager-api \
&& mv /go/src/github.com/apisix/manager-api/entry.sh /go/manager-api/ \
&& mv /go/src/github.com/apisix/manager-api/build-tools/* /go/manager-api/build-tools/ \
&& mv /go/src/github.com/apisix/manager-api/conf/conf_preview.json /go/manager-api/conf.json \
&& mv /go/src/github.com/apisix/manager-api/conf/schema.json /go/manager-api/schema.json \
&& mv /go/src/github.com/apisix/manager-api/conf/conf.yaml /go/manager-api/conf/conf.yaml \
&& mv /go/src/github.com/apisix/manager-api/conf/schema.json /go/manager-api/conf/schema.json \
&& rm -rf /go/src/github.com/apisix/manager-api \
&& rm -rf /etc/localtime \
&& ln -s /usr/share/zoneinfo/Hongkong /etc/localtime \
Expand Down
6 changes: 3 additions & 3 deletions api/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,19 @@ set -ex
export ENV=local
pwd=`pwd`

rm -rf output && mkdir -p output/conf && mkdir -p output/dag-to-lua-1.1
rm -rf output && mkdir -p output/conf && mkdir -p output/dag-to-lua

# get dag-to-lua lib
if [[ ! -f "dag-to-lua-1.1/lib/dag-to-lua.lua" ]]; then
wget https://github.com/api7/dag-to-lua/archive/v1.1.tar.gz -P /tmp
tar -zxvf /tmp/v1.1.tar.gz -C /tmp
cp -r /tmp/dag-to-lua-1.1/lib ./output/dag-to-lua-1.1
cp -r /tmp/dag-to-lua-1.1/lib/* ./output/dag-to-lua
fi

# build
cd ./api && go build -o ../output/manager-api . && cd ..

cp ./api/conf/schema.json ./output/conf/schema.json
cp ./api/conf/conf.json ./output/conf/conf.json
cp ./api/conf/conf.yaml ./output/conf/conf.yaml

echo "Build the Manager API successfully"
162 changes: 71 additions & 91 deletions api/conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,147 +17,127 @@
package conf

import (
"flag"
"fmt"
"github.com/tidwall/gjson"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"

"github.com/tidwall/gjson"

"github.com/apisix/manager-api/internal/utils"
)

const (
WebDir = "./output/html"

EnvPROD = "prod"
EnvBETA = "beta"
EnvDEV = "dev"
EnvLOCAL = "local"

confJsonPath = "/go/manager-api/conf.json"
schemaPath = "/go/manager-api/schema.json"
WebDir = "./html"
)

var (
ENV string
basePath string
Schema gjson.Result
DagLibPath = "/go/manager-api/dag-to-lua/"
WorkDir = "."
ServerHost = "127.0.0.1"
ServerPort = 80
ETCDEndpoints = "127.0.0.1:2379"
ETCDEndpoints = []string{"127.0.0.1:2379"}
UserList = make(map[string]User, 2)
AuthConf Authentication
)

type Etcd struct {
Endpoints []string
}

type Listen struct {
Host string
Port int
}

type Conf struct {
Etcd Etcd
Listen Listen
}

type User struct {
Username string
Password string
}

type Authentication struct {
Secret string
ExpireTime int
Users []User
}

type Config struct {
Conf Conf
Authentication Authentication
}

func init() {
//go test
if workDir := os.Getenv("APISIX_API_WORKDIR"); workDir != "" {
WorkDir = workDir
} else {
flag.StringVar(&WorkDir, "p", ".", "current work dir")
flag.Parse()
}

setConf()
setEnvironment()
initAuthentication()
initSchema()
setConf()
}

func setConf() {
filePath := configurationPath()
filePath := WorkDir + "/conf/conf.yaml"
if configurationContent, err := ioutil.ReadFile(filePath); err != nil {
panic(fmt.Sprintf("fail to read configuration: %s", filePath))
} else {
configuration := gjson.ParseBytes(configurationContent)
//configuration := gjson.ParseBytes(configurationContent)
config := Config{}
err := yaml.Unmarshal(configurationContent, &config)
if err != nil {
log.Printf("conf: %s, error: %v", configurationContent, err)
}

//listen
serverPort := int(configuration.Get("conf.listen.port").Int())
if serverPort != 0 {
ServerPort = serverPort
if config.Conf.Listen.Port != 0 {
ServerPort = config.Conf.Listen.Port
}
serverHost := configuration.Get("conf.listen.host").String()
if serverHost != "" {
ServerHost = serverHost
if config.Conf.Listen.Host != "" {
ServerHost = config.Conf.Listen.Host
}

//dag lib path
dagLibPath := configuration.Get("conf.dag-lib-path").String()
if dagLibPath != "" {
DagLibPath = dagLibPath
}
//etcd
eTCDEndpoints := configuration.Get("conf.etcd.endpoints").String()
if eTCDEndpoints != "" {
ETCDEndpoints = eTCDEndpoints
if len(config.Conf.Etcd.Endpoints) > 0 {
ETCDEndpoints = config.Conf.Etcd.Endpoints
}

//auth
initAuthentication(config.Authentication)
}
}

func setEnvironment() {
if env := os.Getenv("ENV"); env == "" {
ENV = EnvLOCAL
} else {
ENV = EnvPROD
if env := os.Getenv("ENV"); env != "" {
ENV = env
}

_, basePath, _, _ = runtime.Caller(1)
}

func configurationPath() string {
if confPath := os.Getenv("APISIX_CONF_PATH"); confPath != "" {
return filepath.Join(confPath, "/conf.json")
} else if ENV == EnvLOCAL {
return filepath.Join(filepath.Dir(basePath), "conf.json")
} else {
return confJsonPath
}
}

func getSchemaPath() string {
if confPath := os.Getenv("APISIX_CONF_PATH"); confPath != "" {
return filepath.Join(confPath, "/schema.json")
} else if ENV == EnvLOCAL {
return filepath.Join(filepath.Dir(basePath), "schema.json")
} else {
return schemaPath
}
}

type user struct {
Username string
Password string
}

type authenticationConfig struct {
Session struct {
Secret string
ExpireTime uint64
}
}

var UserList = make(map[string]user, 1)

var AuthenticationConfig authenticationConfig

func initAuthentication() {
filePath := configurationPath()
configurationContent, err := ioutil.ReadFile(filePath)
if err != nil {
panic(fmt.Sprintf("fail to read configuration: %s", filePath))
}

configuration := gjson.ParseBytes(configurationContent)
userList := configuration.Get("authentication.user").Array()
func initAuthentication(conf Authentication) {
AuthConf = conf
userList := conf.Users
// create user list
for _, item := range userList {
username := item.Map()["username"].String()
password := item.Map()["password"].String()
UserList[item.Map()["username"].String()] = user{Username: username, Password: password}
}
AuthenticationConfig.Session.Secret = configuration.Get("authentication.session.secret").String()
if "secret" == AuthenticationConfig.Session.Secret {
AuthenticationConfig.Session.Secret = utils.GetFlakeUidStr()
UserList[item.Username] = item
}

AuthenticationConfig.Session.ExpireTime = configuration.Get("authentication.session.expireTime").Uint()
}

func initSchema() {
filePath := getSchemaPath()
filePath := WorkDir + "/conf/schema.json"
if schemaContent, err := ioutil.ReadFile(filePath); err != nil {
panic(fmt.Sprintf("fail to read configuration: %s", filePath))
} else {
Expand Down
23 changes: 15 additions & 8 deletions api/docker-compose.yml → api/conf/conf.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
version: '3'

services:
manager:
image: golang:1.13.8
volumes:
- .:/go/src/github.com/apisix/manager-api
working_dir: /go/src/github.com/apisix/manager-api
command: go test -v github.com/apisix/manager-api/service
conf:
listen:
host: 127.0.0.1
membphis marked this conversation as resolved.
Show resolved Hide resolved
port: 8080
etcd:
endpoints:
- 127.0.0.1:2379
authentication:
secret: secret
nic-chen marked this conversation as resolved.
Show resolved Hide resolved
expireTime: 3600
users:
- username: admin
password: admin
- username: user
password: user
2 changes: 1 addition & 1 deletion api/filter/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func Authentication() gin.HandlerFunc {

// verify token
token, err := jwt.ParseWithClaims(tokenStr, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(conf.AuthenticationConfig.Session.Secret), nil
return []byte(conf.AuthConf.Secret), nil
})

errResp := gin.H{
Expand Down
1 change: 1 addition & 0 deletions api/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ require (
github.com/xeipuuv/gojsonschema v1.2.0
go.etcd.io/etcd v3.3.25+incompatible
go.uber.org/zap v1.16.0
gopkg.in/yaml.v2 v2.3.0
)
4 changes: 2 additions & 2 deletions api/internal/handler/authentication/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ func (h *Handler) userLogin(c droplet.Context) (interface{}, error) {
claims := jwt.StandardClaims{
Subject: username,
IssuedAt: time.Now().Unix(),
ExpiresAt: time.Now().Add(time.Second * time.Duration(conf.AuthenticationConfig.Session.ExpireTime)).Unix(),
ExpiresAt: time.Now().Add(time.Second * time.Duration(conf.AuthConf.ExpireTime)).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, _ := token.SignedString([]byte(conf.AuthenticationConfig.Session.Secret))
signedToken, _ := token.SignedString([]byte(conf.AuthConf.Secret))

// output token
return &UserSession{
Expand Down
2 changes: 1 addition & 1 deletion api/internal/handler/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func generateLuaCode(script map[string]interface{}) (string, error) {
}

cmd := exec.Command("sh", "-c",
"cd "+conf.DagLibPath+" && lua cli.lua "+
"cd "+conf.WorkDir+"/dag-to-lua && lua cli.lua "+
nic-chen marked this conversation as resolved.
Show resolved Hide resolved
"'"+string(scriptString)+"'")

stdout, _ := cmd.StdoutPipe()
Expand Down
Loading