refactor: openpitrix module

Signed-off-by: hongming <talonwan@yunify.com>
This commit is contained in:
hongming
2019-09-25 14:07:15 +08:00
parent d0dc66cf28
commit 1b5681c12b
314 changed files with 72092 additions and 25762 deletions

View File

@@ -0,0 +1,52 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package ctxutil
import (
"context"
"google.golang.org/grpc/metadata"
)
const (
messageIdKey = "x-message-id"
requestIdKey = "x-request-id"
)
type getMetadataFromContext func(ctx context.Context) (md metadata.MD, ok bool)
var getMetadataFromContextFunc = []getMetadataFromContext{
metadata.FromOutgoingContext,
metadata.FromIncomingContext,
}
func GetValueFromContext(ctx context.Context, key string) []string {
if ctx == nil {
return []string{}
}
for _, f := range getMetadataFromContextFunc {
md, ok := f(ctx)
if !ok {
continue
}
m, ok := md[key]
if ok && len(m) > 0 {
return m
}
}
m, ok := ctx.Value(key).([]string)
if ok && len(m) > 0 {
return m
}
s, ok := ctx.Value(key).(string)
if ok && len(s) > 0 {
return []string{s}
}
return []string{}
}
func Copy(src, dst context.Context) context.Context {
return SetMessageId(dst, GetMessageId(src))
}

View File

@@ -0,0 +1,35 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package ctxutil
import (
"context"
"google.golang.org/grpc/metadata"
)
func GetMessageId(ctx context.Context) []string {
return GetValueFromContext(ctx, messageIdKey)
}
func SetMessageId(ctx context.Context, messageId []string) context.Context {
ctx = context.WithValue(ctx, messageIdKey, messageId)
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
md = metadata.MD{}
}
md[messageIdKey] = messageId
return metadata.NewOutgoingContext(ctx, md)
}
func AddMessageId(ctx context.Context, messageId ...string) context.Context {
m := GetMessageId(ctx)
m = append(m, messageId...)
return SetMessageId(ctx, m)
}
func ClearMessageId(ctx context.Context) context.Context {
return SetMessageId(ctx, []string{})
}

View File

@@ -0,0 +1,29 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package ctxutil
import (
"context"
"google.golang.org/grpc/metadata"
)
func GetRequestId(ctx context.Context) string {
rid := GetValueFromContext(ctx, requestIdKey)
if len(rid) == 0 {
return ""
}
return rid[0]
}
func SetRequestId(ctx context.Context, requestId string) context.Context {
ctx = context.WithValue(ctx, requestIdKey, []string{requestId})
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
md = metadata.MD{}
}
md[requestIdKey] = []string{requestId}
return metadata.NewOutgoingContext(ctx, md)
}

View File

@@ -0,0 +1,45 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package ctxutil
import (
"context"
"encoding/json"
"google.golang.org/grpc/metadata"
"openpitrix.io/openpitrix/pkg/sender"
)
const (
SenderKey = "sender"
TokenType = "Bearer"
)
func GetSender(ctx context.Context) *sender.Sender {
values := GetValueFromContext(ctx, SenderKey)
if len(values) == 0 || len(values[0]) == 0 {
return nil
}
s := sender.Sender{}
err := json.Unmarshal([]byte(values[0]), &s)
if err != nil {
panic(err)
}
return &s
}
func ContextWithSender(ctx context.Context, user *sender.Sender) context.Context {
if user == nil {
return ctx
}
ctx = context.WithValue(ctx, SenderKey, []string{user.ToJson()})
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
md = metadata.MD{}
}
md[SenderKey] = []string{user.ToJson()}
return metadata.NewOutgoingContext(ctx, md)
}

139
vendor/openpitrix.io/openpitrix/pkg/util/pbutil/pb.go generated vendored Normal file
View File

@@ -0,0 +1,139 @@
// Copyright 2017 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package pbutil
import (
"context"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/golang/protobuf/ptypes/wrappers"
"openpitrix.io/openpitrix/pkg/db"
"openpitrix.io/openpitrix/pkg/logger"
)
type RequestHadOffset interface {
GetOffset() uint32
}
type RequestHadLimit interface {
GetLimit() uint32
}
const (
DefaultOffset = uint64(0)
DefaultLimit = uint64(20)
)
func GetOffsetFromRequest(req RequestHadOffset) uint64 {
n := req.GetOffset()
if n == 0 {
return DefaultOffset
}
return db.GetOffset(uint64(n))
}
func GetLimitFromRequest(req RequestHadLimit) uint64 {
n := req.GetLimit()
if n == 0 {
return DefaultLimit
}
return db.GetLimit(uint64(n))
}
func GetTime(t *timestamp.Timestamp) (tt time.Time) {
if t == nil {
return time.Now()
} else {
return FromProtoTimestamp(t)
}
}
func FromProtoTimestamp(t *timestamp.Timestamp) (tt time.Time) {
tt, err := ptypes.Timestamp(t)
if err != nil {
logger.Critical(nil, "Cannot convert timestamp [T] to time.Time [%+v]: %+v", t, err)
panic(err)
}
return
}
func ToProtoTimestamp(t time.Time) (tt *timestamp.Timestamp) {
if t.IsZero() {
return nil
}
tt, err := ptypes.TimestampProto(t)
if err != nil {
logger.Critical(nil, "Cannot convert time.Time [%+v] to ToProtoTimestamp[T]: %+v", t, err)
panic(err)
}
return
}
func ToProtoString(str string) *wrappers.StringValue {
return &wrappers.StringValue{Value: str}
}
func ToProtoUInt32(uint32 uint32) *wrappers.UInt32Value {
return &wrappers.UInt32Value{Value: uint32}
}
func ToProtoInt32(i int32) *wrappers.Int32Value {
return &wrappers.Int32Value{Value: i}
}
func ToProtoBool(bool bool) *wrappers.BoolValue {
return &wrappers.BoolValue{Value: bool}
}
func ToProtoBytes(bytes []byte) *wrappers.BytesValue {
return &wrappers.BytesValue{Value: bytes}
}
type DescribeResponse interface {
GetTotalCount() uint32
}
type DescribeApi interface {
SetRequest(ctx context.Context, req interface{}, limit, offset uint32) error
Describe(ctx context.Context, req interface{}, advancedParams ...string) (DescribeResponse, error)
}
func DescribeAllResponses(ctx context.Context, describeApi DescribeApi, req interface{}, advancedParams ...string) ([]DescribeResponse, error) {
limit := uint32(db.DefaultSelectLimit)
offset := uint32(0)
var responses []DescribeResponse
if err := describeApi.SetRequest(ctx, req, limit, offset); err != nil {
return nil, err
}
response, err := describeApi.Describe(ctx, req, advancedParams...)
if err != nil {
return nil, err
}
totalCount := response.GetTotalCount()
responses = append(responses, response)
offset = offset + db.DefaultSelectLimit
for {
if totalCount > uint32(offset) {
if err := describeApi.SetRequest(ctx, req, limit, offset); err != nil {
return nil, err
}
response, err = describeApi.Describe(ctx, req)
if err != nil {
return nil, err
}
responses = append(responses, response)
offset = offset + db.DefaultSelectLimit
} else {
break
}
}
return responses, nil
}

View File

@@ -0,0 +1,38 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package reflectutil
import "reflect"
func In(value interface{}, container interface{}) bool {
containerValue := reflect.ValueOf(container)
switch reflect.TypeOf(container).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < containerValue.Len(); i++ {
if containerValue.Index(i).Interface() == value {
return true
}
}
case reflect.Map:
if containerValue.MapIndex(reflect.ValueOf(value)).IsValid() {
return true
}
default:
return false
}
return false
}
func ValueIsNil(value reflect.Value) bool {
k := value.Kind()
switch k {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Slice:
return value.IsNil()
case reflect.Invalid:
return true
}
// base type had default value, is not nil
return false
}

View File

@@ -0,0 +1,15 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package stringutil
import (
"bytes"
"encoding/base64"
"io/ioutil"
)
func DecodeBase64(i string) ([]byte, error) {
return ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(i)))
}

View File

@@ -0,0 +1,68 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package stringutil
import (
"unicode/utf8"
"github.com/asaskevich/govalidator"
)
// Creates an slice of slice values not included in the other given slice.
func Diff(base, exclude []string) (result []string) {
excludeMap := make(map[string]bool)
for _, s := range exclude {
excludeMap[s] = true
}
for _, s := range base {
if !excludeMap[s] {
result = append(result, s)
}
}
return result
}
func Unique(ss []string) (result []string) {
smap := make(map[string]bool)
for _, s := range ss {
smap[s] = true
}
for s := range smap {
result = append(result, s)
}
return result
}
func CamelCaseToUnderscore(str string) string {
return govalidator.CamelCaseToUnderscore(str)
}
func UnderscoreToCamelCase(str string) string {
return govalidator.UnderscoreToCamelCase(str)
}
func FindString(array []string, str string) int {
for index, s := range array {
if str == s {
return index
}
}
return -1
}
func StringIn(str string, array []string) bool {
return FindString(array, str) > -1
}
func Reverse(s string) string {
size := len(s)
buf := make([]byte, size)
for start := 0; start < size; {
r, n := utf8.DecodeRuneInString(s[start:])
start += n
utf8.EncodeRune(buf[size-start:], r)
}
return string(buf)
}

View File

@@ -0,0 +1,20 @@
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package yamlutil
import (
"github.com/ghodss/yaml"
)
// Marshals the object into JSON then converts JSON to YAML and returns the
// YAML.
func Encode(o interface{}) ([]byte, error) {
return yaml.Marshal(o)
}
// Converts YAML to JSON then uses JSON to unmarshal into an object.
func Decode(y []byte, o interface{}) error {
return yaml.Unmarshal(y, o)
}