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

feat: support labels list #1072

Merged
merged 8 commits into from
Dec 21, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 3 additions & 1 deletion api/filter/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ import (

func Authentication() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.URL.Path != "/apisix/admin/user/login" && strings.HasPrefix(c.Request.URL.Path, "/apisix") {
if c.Request.URL.Path != "/apisix/admin/user/login" && (strings.HasPrefix(c.Request.URL.Path, "/apisix") ||
strings.HasPrefix(c.Request.URL.Path, "/api/")) {

tokenStr := c.GetHeader("Authorization")

// verify token
Expand Down
260 changes: 260 additions & 0 deletions api/internal/handler/label/label.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
/*
* 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 label

import (
"encoding/json"
"fmt"
"github.com/shiningrush/droplet/data"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put this package after the standard libs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh No. I think my goland plugin doesn't work.
Let me fix it.

"net/http"
"reflect"
"sort"
"strings"

"github.com/gin-gonic/gin"
"github.com/shiningrush/droplet"
"github.com/shiningrush/droplet/wrapper"
wgin "github.com/shiningrush/droplet/wrapper/gin"

"github.com/apisix/manager-api/internal/core/entity"
"github.com/apisix/manager-api/internal/core/store"
"github.com/apisix/manager-api/internal/handler"
"github.com/apisix/manager-api/internal/utils"
)

type Handler struct {
routeStore store.Interface
serviceStore store.Interface
upstreamStore store.Interface
sslStore store.Interface
consumerStore store.Interface
}

var _ json.Marshaler = Pair{}

type Pair struct {
Key string
Val string
}

func (p Pair) MarshalJSON() ([]byte, error) {
res := fmt.Sprintf("{\"%s\":\"%s\"}", p.Key, p.Val)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a good way, the JSON string will be broken if p.Key or p.Val has " in contents.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's ok because key and val come from req args. I will add some tests to ensure it.
And do you have some suggestions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's not a problem. If '"' in contents, Json.Marshal will return an error.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's a bug if you don't handle the special characters correctly in server side.

That's OK if you can make sure that no " in key and value.

Copy link
Contributor Author

@starsz starsz Dec 21, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed. And add some tests.

return []byte(res), nil
}

func NewHandler() (handler.RouteRegister, error) {
return &Handler{
routeStore: store.GetStore(store.HubKeyRoute),
serviceStore: store.GetStore(store.HubKeyService),
upstreamStore: store.GetStore(store.HubKeyUpstream),
sslStore: store.GetStore(store.HubKeySsl),
consumerStore: store.GetStore(store.HubKeyConsumer),
}, nil
}

func (h *Handler) ApplyRoute(r *gin.Engine) {
r.GET("/api/labels/:type", wgin.Wraps(h.List,
juzhiyuan marked this conversation as resolved.
Show resolved Hide resolved
wrapper.InputType(reflect.TypeOf(ListInput{}))))
}

type ListInput struct {
Type string `auto_read:"type,path" validate:"required"`
Label string `auto_read:"label,query"`
store.Pagination
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, we should put embed member at the top of struct definition.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK.

}

func getMatch(reqLabels, labels map[string]string) map[string]string {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can reference the label implementation of istio: https://github.com/istio/istio/blob/0c0cf2d6fb/pkg/config/labels/instance.go#L55.

Encapsulate the getMatch as SubsetOf will be more semantic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea.

if len(reqLabels) == 0 {
return labels
}

var res = make(map[string]string)
for k, v := range labels {
l, exist := reqLabels[k]
if exist && ((l == "") || v == l) {
res[k] = v
}
}

return res
}

// swagger:operation GET /api/labels getLabelsList
//
// Return the labels list among `route,ssl,consumer,upstream,service`
// according to the specified page number and page size, and can search labels by label.
//
// ---
// produces:
// - application/json
// parameters:
// - name: page
// in: query
// description: page number
// required: false
// type: integer
// - name: page_size
// in: query
// description: page size
// required: false
// type: integer
// - name: label
// in: query
// description: label filter of labels
// required: false
// type: string
// responses:
// '0':
// description: list response
// schema:
// type: array
// items:
// "$ref": "#/definitions/service"
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/ApiError"
func (h *Handler) List(c droplet.Context) (interface{}, error) {
input := c.Input().(*ListInput)

typ := input.Type
reqLabels, err := utils.GenLabelMap(input.Label)
if err != nil {
return &data.SpecCodeResponse{StatusCode: http.StatusBadRequest},
fmt.Errorf("%s: \"%s\"", err.Error(), input.Label)
}

var items []interface{}
switch typ {
juzhiyuan marked this conversation as resolved.
Show resolved Hide resolved
case "route":
items = append(items, h.routeStore)
case "service":
items = append(items, h.serviceStore)
case "consumer":
items = append(items, h.consumerStore)
case "ssl":
items = append(items, h.sslStore)
case "upstream":
items = append(items, h.upstreamStore)
case "all":
items = append(items, h.routeStore, h.serviceStore, h.upstreamStore,
h.sslStore, h.consumerStore)
}

predicate := func(obj interface{}) bool {
var ls map[string]string

switch obj := obj.(type) {
case *entity.Route:
ls = obj.Labels
case *entity.Consumer:
ls = obj.Labels
case *entity.SSL:
ls = obj.Labels
case *entity.Service:
ls = obj.Labels
case *entity.Upstream:
ls = obj.Labels
default:
return false
}

return utils.LabelContains(ls, reqLabels)
}

format := func(obj interface{}) interface{} {
val := reflect.ValueOf(obj).Elem()
l := val.FieldByName("Labels")
if l.IsNil() {
return nil
}

ls := l.Interface().(map[string]string)
return getMatch(reqLabels, ls)
}

var totalRet = new(store.ListOutput)
var existMap = make(map[string]struct{})
for _, item := range items {
ret, err := item.(store.Interface).List(
store.ListInput{
Predicate: predicate,
Format: format,
// Sort it later.
PageSize: 0,
PageNumber: 0,
Less: func(i, j interface{}) bool {
return true
},
},
)

if err != nil {
return nil, err
}

for _, r := range ret.Rows {
if r == nil {
continue
}

for k, v := range r.(map[string]string) {
key := fmt.Sprintf("%s:%s", k, v)
if _, exist := existMap[key]; exist {
continue
}

existMap[key] = struct{}{}
p := Pair{Key: k, Val: v}
totalRet.Rows = append(totalRet.Rows, p)
}
}
}
totalRet.TotalSize = len(totalRet.Rows)

sort.Slice(totalRet.Rows, func(i, j int) bool {
p1 := totalRet.Rows[i].(Pair)
p2 := totalRet.Rows[j].(Pair)

if strings.Compare(p1.Key, p2.Key) == 0 {
return strings.Compare(p1.Val, p2.Val) < 0
}

return strings.Compare(p1.Key, p2.Key) < 0
})

/* There are more than one store items,
So we need sort after getting all of labels.
*/
if input.PageSize > 0 && input.PageNumber > 0 {
skipCount := (input.PageNumber - 1) * input.PageSize
if skipCount > totalRet.TotalSize {
totalRet.Rows = []interface{}{}
return totalRet, nil
}

endIdx := skipCount + input.PageSize
if endIdx >= totalRet.TotalSize {
totalRet.Rows = totalRet.Rows[skipCount:]
return totalRet, nil
}

totalRet.Rows = totalRet.Rows[skipCount:endIdx]
}

return totalRet, nil
}
Loading