Skip to content

Commit

Permalink
Merge 4d981a9 into 4eda42b
Browse files Browse the repository at this point in the history
  • Loading branch information
little-cui committed Nov 17, 2017
2 parents 4eda42b + 4d981a9 commit 6e60711
Show file tree
Hide file tree
Showing 32 changed files with 947 additions and 942 deletions.
2 changes: 1 addition & 1 deletion integration/microservices_test.go
Expand Up @@ -207,7 +207,7 @@ var _ = Describe("MicroService Api Test", func() {
resp, _ := scclient.Do(req)
respbody, _ := ioutil.ReadAll(resp.Body)
Expect(resp.StatusCode).To(Equal(http.StatusOK))
Expect(string(respbody)).To(Equal("{}"))
Expect(strings.TrimSpace(string(respbody))).To(Equal("{}"))
})
})

Expand Down
10 changes: 7 additions & 3 deletions integration/rules_test.go
Expand Up @@ -183,13 +183,17 @@ var _ = Describe("MicroService Api Test", func() {
Expect(resp.StatusCode).To(Equal(http.StatusOK))

//Duplicate Request
bodyBuf = bytes.NewReader(body)
req, _ = http.NewRequest(POST, SCURL+url, bodyBuf)
req.Header.Set("X-Domain-Name", "default")
resp, err = scclient.Do(req)
Expect(err).To(BeNil())
defer resp.Body.Close()

Expect(resp.StatusCode).To(Equal(http.StatusBadRequest))
Expect(resp.StatusCode).To(Equal(http.StatusOK))

respbody, _ := ioutil.ReadAll(resp.Body)
Expect(strings.TrimSpace(string(respbody))).To(Equal("{}"))
})
})

Expand Down Expand Up @@ -243,7 +247,7 @@ var _ = Describe("MicroService Api Test", func() {
resp, _ := scclient.Do(req)
respbody, _ := ioutil.ReadAll(resp.Body)
Expect(resp.StatusCode).To(Equal(http.StatusOK))
Expect(string(respbody)).To(Equal("{}"))
Expect(strings.TrimSpace(string(respbody))).To(Equal("{}"))
})

It("Get Rules for Invalid MicroService", func() {
Expand Down Expand Up @@ -482,7 +486,7 @@ var _ = Describe("MicroService Api Test", func() {
resp, _ = scclient.Do(req)
respbody, _ = ioutil.ReadAll(resp.Body)
Expect(resp.StatusCode).To(Equal(http.StatusOK))
Expect(string(respbody)).To(Equal("{}"))
Expect(strings.TrimSpace(string(respbody))).To(Equal("{}"))
})

It("Delete MicroService rules with non-exsisting ruleID", func() {
Expand Down
4 changes: 3 additions & 1 deletion server/core/proto/services.go
Expand Up @@ -46,6 +46,8 @@ const (
EXISTENCE_SCHEMA string = "schema"

PROP_ALLOW_CROSS_APP = "allowCrossApp"

Response_SUCCESS int32 = 0
)

type SerivceInstanceCtrlServerEx interface {
Expand All @@ -68,7 +70,7 @@ type SystemConfig struct {
Version string `json:"version"`
}

func CreateResponse(code Response_Code, message string) *Response {
func CreateResponse(code int32, message string) *Response {
resp := &Response{
Code: code,
Message: message,
Expand Down
446 changes: 209 additions & 237 deletions server/core/proto/services.pb.go

Large diffs are not rendered by default.

7 changes: 1 addition & 6 deletions server/core/proto/services.proto
Expand Up @@ -174,12 +174,7 @@ message ServicePath {
}

message Response {
enum Code {
UNKNOWN = 0;
SUCCESS = 1;
FAIL = 2;
}
Code code = 1;
int32 code = 1;
string message = 2;
}

Expand Down
126 changes: 126 additions & 0 deletions server/error/error.go
@@ -0,0 +1,126 @@
//Copyright 2017 Huawei Technologies Co., Ltd
//
//Licensed 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 error

import (
"encoding/json"
"fmt"
"github.com/ServiceComb/service-center/pkg/util"
"net/http"
)

var errors = map[int32]string{
ErrInvalidParams: "Invalid parameter(s)",

ErrServiceAlreadyExists: "Micro-service already exists",
ErrServiceNotExists: "Micro-service does not exist",
ErrDeployedInstance: "Micro-service has deployed instance(s)",
ErrDependedOnConsumer: "Consumer(s) depends on this micro-service",

ErrUndefinedSchemaId: "Undefined schema id",
ErrModifySchemaNotAllow: "Not allowed to modify schema",
ErrSchemaNotExists: "Schema does not exist",

ErrInstanceNotExists: "Instance does not exist",
ErrPermissionDeny: "Access micro-service refused",

ErrTagNotExists: "Tag does not exist",

ErrRuleAlreadyExists: "Rule already exist",
ErrBlackAndWhiteRule: "Can not have both 'BLACK' and 'WHITE'",
ErrModifyRuleNotAllow: "Not allowed to modify the type of the rule",
ErrRuleNotExists: "Rule does not exist",

ErrNotEnoughQuota: "Not enough quota",

ErrUnauthorized: "Request unauthorized",

ErrInternal: "Internal server error",
ErrUnavailableBackend: "Registry service is unavailable",
ErrUnavailableQuota: "Quota service is unavailable",
}

const (
ErrInvalidParams int32 = 400001
ErrUnauthorized int32 = 401002
ErrInternal int32 = 500003

ErrServiceAlreadyExists int32 = 400010
ErrUnavailableBackend int32 = 500011

ErrServiceNotExists int32 = 400012

ErrDeployedInstance int32 = 400013

ErrUndefinedSchemaId int32 = 400014
ErrModifySchemaNotAllow int32 = 400015
ErrSchemaNotExists int32 = 400016

ErrInstanceNotExists int32 = 400017

ErrTagNotExists int32 = 400018

ErrRuleAlreadyExists int32 = 400019
ErrBlackAndWhiteRule int32 = 400020
ErrModifyRuleNotAllow int32 = 400021
ErrRuleNotExists int32 = 400022

ErrDependedOnConsumer int32 = 400023

ErrPermissionDeny int32 = 400024

ErrNotEnoughQuota int32 = 400100
ErrUnavailableQuota int32 = 500101
)

type Error struct {
Code int32 `json:"errorCode,string"`
Message string `json:"errorMessage"`
Detail string `json:"detail,omitempty"`
}

func (e Error) Error() string {
if len(e.Detail) == 0 {
return e.Message
}
return e.Message + "(" + e.Detail + ")"
}

func (e Error) toJson() string {
bs, _ := json.Marshal(e)
return util.BytesToStringWithNoCopy(bs)
}

func (e Error) StatusCode() int {
if e.Code >= 500000 {
return http.StatusInternalServerError
}
return http.StatusBadRequest
}

func (e Error) HttpWrite(w http.ResponseWriter) {
status := e.StatusCode()
w.Header().Add("X-Response-Status", fmt.Sprint(status))
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(status)
fmt.Fprintln(w, e.toJson())
}

func NewError(code int32, detail string) *Error {
return &Error{
Code: code,
Message: errors[code],
Detail: detail,
}
}
27 changes: 6 additions & 21 deletions server/handler/auth/handler.go
Expand Up @@ -17,34 +17,18 @@ import (
"github.com/ServiceComb/service-center/pkg/chain"
"github.com/ServiceComb/service-center/pkg/rest"
"github.com/ServiceComb/service-center/pkg/util"
"github.com/ServiceComb/service-center/server/infra/auth"
"github.com/astaxie/beego"
scerr "github.com/ServiceComb/service-center/server/error"
"github.com/ServiceComb/service-center/server/plugin/dynamic"
"github.com/ServiceComb/service-center/server/rest/controller"
"net/http"
)

var plugin auth.Auth

func init() {
name := beego.AppConfig.String("auth_plugin")
if pluginBuilder, ok := auth.AuthPlugins[name]; ok {
util.Logger().Warnf(nil, "service center is in '%s' mode", name)
plugin = pluginBuilder()
return
}
util.Logger().Warnf(nil, "service center is in 'noAuth' mode")
}

type AuthRequest struct {
}

func (h *AuthRequest) Handle(i *chain.Invocation) {
if plugin == nil {
i.Next()
return
}

r := i.Context().Value(rest.CTX_REQUEST).(*http.Request)
err := plugin.Identify(r)
err := dynamic.Identify(r)
if err == nil {
i.Next()
return
Expand All @@ -53,7 +37,8 @@ func (h *AuthRequest) Handle(i *chain.Invocation) {
util.Logger().Errorf(err, "authenticate request failed, %s %s", r.Method, r.RequestURI)

w := i.Context().Value(rest.CTX_RESPONSE).(http.ResponseWriter)
http.Error(w, "Request Unauthorized", http.StatusUnauthorized)
controller.WriteError(w, scerr.ErrUnauthorized, err.Error())

i.Fail(nil)
}

Expand Down
58 changes: 58 additions & 0 deletions server/plugin/dynamic/auth.go
@@ -0,0 +1,58 @@
//Copyright 2017 Huawei Technologies Co., Ltd
//
//Licensed 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 dynamic

import (
"github.com/ServiceComb/service-center/pkg/plugin"
"github.com/ServiceComb/service-center/pkg/util"
"github.com/ServiceComb/service-center/server/infra/auth"
"github.com/astaxie/beego"
"net/http"
)

var authLib auth.Auth

func init() {
name := beego.AppConfig.String("auth_plugin")
if pluginBuilder, ok := auth.AuthPlugins[name]; ok {
util.Logger().Warnf(nil, "static load plugin '%s' successfully.", name)
authLib = pluginBuilder()
return
}
}

func buildinAuthFunc(r *http.Request) error {
if authLib == nil {
return nil
}
return authLib.Identify(r)
}

func findAuthFunc(funcName string) func(*http.Request) error {
ff, err := plugin.FindFunc("auth", funcName)
if err != nil {
return buildinAuthFunc
}
f, ok := ff.(func(*http.Request) error)
if !ok {
util.Logger().Warnf(nil, "unexpected function '%s' format found in plugin 'auth'.", funcName)
return buildinAuthFunc
}
return f
}

func Identify(r *http.Request) error {
f := findAuthFunc("Identify")
return f(r)
}
63 changes: 22 additions & 41 deletions server/rest/controller/rest_util.go
Expand Up @@ -18,58 +18,39 @@ import (
"fmt"
"github.com/ServiceComb/service-center/pkg/util"
pb "github.com/ServiceComb/service-center/server/core/proto"
"github.com/ServiceComb/service-center/server/error"
"net/http"
"strconv"
)

func WriteJsonObject(status int, obj interface{}, w http.ResponseWriter) {
serviceJSON, err := json.Marshal(obj)
if err != nil {
util.Logger().Error("marshal response error", err)
WriteText(http.StatusInternalServerError, fmt.Sprintf("marshal response error, %s", err.Error()), w)
return
}
WriteJson(status, serviceJSON, w)
}

func WriteJson(status int, json []byte, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json;charset=utf-8")
w.Header().Add("x-response-status", strconv.Itoa(status))
w.WriteHeader(status)
w.Write(json)
func WriteError(w http.ResponseWriter, code int32, detail string) {
err := error.NewError(code, detail)
err.HttpWrite(w)
}

func WriteText(status int, text string, w http.ResponseWriter) {
w.Header().Add("x-response-status", strconv.Itoa(status))
w.WriteHeader(status)
w.Write(util.StringToBytesWithNoCopy(text))
}

func WriteTextResponse(resp *pb.Response, err error, textIfSuccess string, w http.ResponseWriter) {
if err != nil {
WriteText(http.StatusInternalServerError, err.Error(), w)
return
}
if resp.Code != pb.Response_SUCCESS {
WriteText(http.StatusBadRequest, resp.Message, w)
func WriteJsonObject(w http.ResponseWriter, obj interface{}) {
if obj == nil {
w.Header().Add("X-Response-Status", fmt.Sprint(http.StatusOK))
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
w.WriteHeader(http.StatusOK)
return
}
WriteText(http.StatusOK, textIfSuccess, w)
}

func WriteJsonResponse(resp *pb.Response, obj interface{}, err error, w http.ResponseWriter) {
objJson, err := json.Marshal(obj)
if err != nil {
WriteText(http.StatusInternalServerError, err.Error(), w)
WriteError(w, error.ErrInternal, err.Error())
return
}
if resp.Code != pb.Response_SUCCESS {
WriteText(http.StatusBadRequest, resp.Message, w)
return
}
objJson, err := json.Marshal(obj)
if err != nil {
WriteText(http.StatusInternalServerError, err.Error(), w)
w.Header().Add("X-Response-Status", fmt.Sprint(http.StatusOK))
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, util.BytesToStringWithNoCopy(objJson))
}

func WriteResponse(w http.ResponseWriter, resp *pb.Response, obj interface{}) {
if resp.GetCode() == pb.Response_SUCCESS {
WriteJsonObject(w, obj)
return
}
WriteJson(http.StatusOK, objJson, w)

WriteError(w, resp.GetCode(), resp.GetMessage())
}

0 comments on commit 6e60711

Please sign in to comment.