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

fix: Support string type for the script field in Route #1289

Merged
merged 7 commits into from
Jan 15, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
32 changes: 18 additions & 14 deletions api/internal/handler/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ import (
"github.com/shiningrush/droplet"
"github.com/shiningrush/droplet/data"
"github.com/shiningrush/droplet/wrapper"
"github.com/yuin/gopher-lua"
wgin "github.com/shiningrush/droplet/wrapper/gin"
lua "github.com/yuin/gopher-lua"

"github.com/apisix/manager-api/internal/conf"
"github.com/apisix/manager-api/internal/core/entity"
"github.com/apisix/manager-api/internal/core/store"
Expand Down Expand Up @@ -327,12 +328,17 @@ func (h *Handler) Create(c droplet.Context) (interface{}, error) {
script := &entity.Script{}
script.ID = utils.InterfaceToString(input.ID)
script.Script = input.Script
//to lua

var err error
input.Script, err = generateLuaCode(input.Script.(map[string]interface{}))
if err != nil {
return nil, err
// Explicitly to lua if input script is of the map type, otherwise
// it will always represent a piece of lua code of the string type.
if scriptConf, ok := input.Script.(map[string]interface{}); ok {
input.Script, err = generateLuaCode(scriptConf)
if err != nil {
return nil, err
}
}

//save original conf
if err = h.scriptStore.Create(c.Context(), script); err != nil {
return nil, err
Expand Down Expand Up @@ -392,16 +398,14 @@ func (h *Handler) Update(c droplet.Context) (interface{}, error) {
script := &entity.Script{}
script.ID = input.ID
script.Script = input.Script
//to lua
// Explicitly to lua if input script is of the map type, otherwise
// it will always represent a piece of lua code of the string type.
var err error
scriptConf, ok := input.Script.(map[string]interface{})
if !ok {
return &data.SpecCodeResponse{StatusCode: http.StatusBadRequest},
fmt.Errorf("invalid `script`")
}
input.Route.Script, err = generateLuaCode(scriptConf)
if err != nil {
return &data.SpecCodeResponse{StatusCode: http.StatusInternalServerError}, err
if scriptConf, ok := input.Script.(map[string]interface{}); ok {
input.Route.Script, err = generateLuaCode(scriptConf)
if err != nil {
return &data.SpecCodeResponse{StatusCode: http.StatusInternalServerError}, err
}
juzhiyuan marked this conversation as resolved.
Show resolved Hide resolved
}
//save original conf
if err = h.scriptStore.Update(c.Context(), script, true); err != nil {
Expand Down
99 changes: 97 additions & 2 deletions api/internal/handler/route/route_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -938,7 +938,7 @@ func TestRoute(t *testing.T) {
dataPage = retPage.(*store.ListOutput)
assert.Equal(t, len(dataPage.Rows), 1)

//sleep
//sleep
time.Sleep(time.Duration(100) * time.Millisecond)

// list search and status not match
Expand Down Expand Up @@ -1197,7 +1197,7 @@ func TestRoute(t *testing.T) {
assert.Nil(t, err)
}

func Test_Route_With_Script(t *testing.T) {
func Test_Route_With_Script_Dag2lua(t *testing.T) {
// init
err := storage.InitETCDClient(conf.ETCDConfig)
assert.Nil(t, err)
Expand Down Expand Up @@ -1349,3 +1349,98 @@ func Test_Route_With_Script(t *testing.T) {
_, err = handler.BatchDelete(ctx)
assert.Nil(t, err)
}

func Test_Route_With_Script_Luacode(t *testing.T) {
// init
err := storage.InitETCDClient(conf.ETCDConfig)
assert.Nil(t, err)
err = store.InitStores()
assert.Nil(t, err)

handler := &Handler{
routeStore: store.GetStore(store.HubKeyRoute),
svcStore: store.GetStore(store.HubKeyService),
upstreamStore: store.GetStore(store.HubKeyUpstream),
scriptStore: store.GetStore(store.HubKeyScript),
}
assert.NotNil(t, handler)

ctx := droplet.NewContext()
route := &entity.Route{}
reqBody := `{
"id": "1",
"uri": "/index.html",
"upstream": {
"type": "roundrobin",
"nodes": [{
"host": "www.a.com",
"port": 80,
"weight": 1
}]
},
"script": "local _M = {} \n function _M.access(api_ctx) \n ngx.log(ngx.INFO,\"hit access phase\") \n end \nreturn _M"
}`
juzhiyuan marked this conversation as resolved.
Show resolved Hide resolved
err = json.Unmarshal([]byte(reqBody), route)
assert.Nil(t, err)
ctx.SetInput(route)
_, err = handler.Create(ctx)
assert.Nil(t, err)

//sleep
time.Sleep(time.Duration(20) * time.Millisecond)

//get
input := &GetInput{}
input.ID = "1"
ctx.SetInput(input)
ret, err := handler.Get(ctx)
stored := ret.(*entity.Route)
assert.Nil(t, err)
assert.Equal(t, stored.ID, route.ID)
assert.Equal(t, "local _M = {} \n function _M.access(api_ctx) \n ngx.log(ngx.INFO,\"hit access phase\") \n end \nreturn _M", stored.Script)

//update
route2 := &UpdateInput{}
route2.ID = "1"
reqBody = `{
"id": "1",
"uri": "/index.html",
"enable_websocket": true,
"upstream": {
"type": "roundrobin",
"nodes": [{
"host": "www.a.com",
"port": 80,
"weight": 1
}]
}
}`

err = json.Unmarshal([]byte(reqBody), route2)
assert.Nil(t, err)
ctx.SetInput(route2)
_, err = handler.Update(ctx)
assert.Nil(t, err)

//sleep
time.Sleep(time.Duration(100) * time.Millisecond)

//get, script should be nil
input = &GetInput{}
input.ID = "1"
ctx.SetInput(input)
ret, err = handler.Get(ctx)
stored = ret.(*entity.Route)
assert.Nil(t, err)
assert.Equal(t, stored.ID, route.ID)
assert.Nil(t, stored.Script)

//delete test data
inputDel := &BatchDelete{}
reqBody = `{"ids": "1"}`
err = json.Unmarshal([]byte(reqBody), inputDel)
assert.Nil(t, err)
ctx.SetInput(inputDel)
_, err = handler.BatchDelete(ctx)
assert.Nil(t, err)
}
70 changes: 70 additions & 0 deletions api/test/e2e/route_with_script_luacode_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package e2e

import (
"net/http"
"testing"
)

func TestRoute_with_script_lucacode(t *testing.T) {
tests := []HttpTestCase{
{
Desc: "create route with script of lua code",
Object: ManagerApiExpect(t),
Method: http.MethodPut,
Path: "/apisix/admin/routes/r1",
Body: `{
"uri": "/hello",
"upstream": {
"type": "roundrobin",
"nodes": [{
"host": "172.16.238.20",
"port": 1980,
"weight": 1
}]
},
"script": "local _M = {} \n function _M.access(api_ctx) \n ngx.log(ngx.INFO,\"hit access phase\") \n end \nreturn _M"
}`,
juzhiyuan marked this conversation as resolved.
Show resolved Hide resolved
Headers: map[string]string{"Authorization": token},
ExpectStatus: http.StatusOK,
},
{
Desc: "get the route",
Object: ManagerApiExpect(t),
Method: http.MethodGet,
Path: "/apisix/admin/routes/r1",
Headers: map[string]string{"Authorization": token},
ExpectStatus: http.StatusOK,
ExpectBody: "hit access phase",
Sleep: sleepTime,
},
nic-chen marked this conversation as resolved.
Show resolved Hide resolved
{
Desc: "delete the route (r1)",
Object: ManagerApiExpect(t),
Method: http.MethodDelete,
Path: "/apisix/admin/routes/r1",
Headers: map[string]string{"Authorization": token},
ExpectStatus: http.StatusOK,
Sleep: sleepTime,
},
}

for _, tc := range tests {
testCaseCheck(tc, t)
}
}