[REV] update grctl and api client code

This commit is contained in:
barnettZQG 2018-07-16 19:06:57 +08:00
parent 0390fdf5b2
commit 66444ba74b
14 changed files with 992 additions and 954 deletions

View File

@ -247,45 +247,13 @@ func (t *TenantAction) GetServicesResources(tr *api_model.ServicesResources) (re
resmp[c] = map[string]interface{}{"memory": 0, "cpu": 0}
}
re = resmp
//query disk used in prometheus
proxy := GetPrometheusProxy()
query := fmt.Sprintf(`app_resource_appfs{service_id=~"%s"}`, strings.Join(tr.Body.ServiceIDs, "|"))
query = strings.Replace(query, " ", "%20", -1)
req, err := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:9999/api/v1/query?query=%s", query), nil)
if err != nil {
logrus.Error("create request prometheus api error ", err.Error())
return
}
result, err := proxy.Do(req)
if err != nil {
logrus.Error("do proxy request prometheus api error ", err.Error())
return
}
if result.Body != nil {
defer result.Body.Close()
if result.StatusCode != 200 {
return re, nil
}
var qres QueryResult
err = json.NewDecoder(result.Body).Decode(&qres)
if err == nil {
for _, re := range qres.Data.Result {
var serviceID string
var disk int
if tid, ok := re["metric"].(map[string]interface{}); ok {
serviceID = tid["service_id"].(string)
}
if re, ok := (re["value"]).([]interface{}); ok && len(re) == 2 {
disk, _ = strconv.Atoi(re[1].(string))
}
if _, ok := resmp[serviceID]; ok {
resmp[serviceID]["disk"] = disk / 1024
} else {
resmp[serviceID] = make(map[string]interface{})
resmp[serviceID]["disk"] = disk / 1024
}
}
appdisks := t.statusCli.GetAppsDisk(strings.Join(tr.Body.ServiceIDs, ","))
for serviceID, disk := range appdisks {
if _, ok := resmp[serviceID]; ok {
resmp[serviceID]["disk"] = disk / 1024
} else {
resmp[serviceID] = make(map[string]interface{})
resmp[serviceID]["disk"] = disk / 1024
}
}
return resmp, nil

View File

@ -18,95 +18,85 @@
package region
import (
"fmt"
// //DefineCloudAuth DefineCloudAuth
// func (t *tenant) DefineCloudAuth(gt *api_model.GetUserToken) DefineCloudAuthInterface {
// return &DefineCloudAuth{
// GT: gt,
// }
// }
"github.com/pquerna/ffjson/ffjson"
// //DefineCloudAuth DefineCloudAuth
// type DefineCloudAuth struct {
// GT *api_model.GetUserToken
// }
"github.com/Sirupsen/logrus"
api_model "github.com/goodrain/rainbond/api/model"
"github.com/goodrain/rainbond/api/util"
)
// //DefineCloudAuthInterface DefineCloudAuthInterface
// type DefineCloudAuthInterface interface {
// GetToken() ([]byte, error)
// PostToken() ([]byte, error)
// PutToken() error
// }
//DefineCloudAuth DefineCloudAuth
func (t *tenant) DefineCloudAuth(gt *api_model.GetUserToken) DefineCloudAuthInterface {
return &DefineCloudAuth{
GT: gt,
}
}
// //GetToken GetToken
// func (d *DefineCloudAuth) GetToken() ([]byte, error) {
// resp, code, err := request(
// fmt.Sprintf("/cloud/auth/%s", d.GT.Body.EID),
// "GET",
// nil,
// )
// if err != nil {
// return nil, util.CreateAPIHandleError(code, err)
// }
// if code > 400 {
// if code == 404 {
// return nil, util.CreateAPIHandleError(code, fmt.Errorf("eid %s is not exist", d.GT.Body.EID))
// }
// return nil, util.CreateAPIHandleError(code, fmt.Errorf("get eid infos %s failed", d.GT.Body.EID))
// }
// //valJ, err := simplejson.NewJson(resp)
// return resp, nil
// }
//DefineCloudAuth DefineCloudAuth
type DefineCloudAuth struct {
GT *api_model.GetUserToken
}
// //PostToken PostToken
// func (d *DefineCloudAuth) PostToken() ([]byte, error) {
// data, err := ffjson.Marshal(d.GT.Body)
// if err != nil {
// return nil, err
// }
// resp, code, err := request(
// "/cloud/auth",
// "POST",
// data,
// )
// if err != nil {
// logrus.Errorf("create auth token error, %v", err)
// return nil, util.CreateAPIHandleError(code, err)
// }
// if code > 400 {
// logrus.Errorf("create auth token error")
// return nil, util.CreateAPIHandleError(code, fmt.Errorf("cretae auth token failed"))
// }
// return resp, nil
// }
//DefineCloudAuthInterface DefineCloudAuthInterface
type DefineCloudAuthInterface interface {
GetToken() ([]byte, error)
PostToken() ([]byte, error)
PutToken() error
}
//GetToken GetToken
func (d *DefineCloudAuth) GetToken() ([]byte, error) {
resp, code, err := request(
fmt.Sprintf("/cloud/auth/%s", d.GT.Body.EID),
"GET",
nil,
)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code > 400 {
if code == 404 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("eid %s is not exist", d.GT.Body.EID))
}
return nil, util.CreateAPIHandleError(code, fmt.Errorf("get eid infos %s failed", d.GT.Body.EID))
}
//valJ, err := simplejson.NewJson(resp)
return resp, nil
}
//PostToken PostToken
func (d *DefineCloudAuth) PostToken() ([]byte, error) {
data, err := ffjson.Marshal(d.GT.Body)
if err != nil {
return nil, err
}
resp, code, err := request(
"/cloud/auth",
"POST",
data,
)
if err != nil {
logrus.Errorf("create auth token error, %v", err)
return nil, util.CreateAPIHandleError(code, err)
}
if code > 400 {
logrus.Errorf("create auth token error")
return nil, util.CreateAPIHandleError(code, fmt.Errorf("cretae auth token failed"))
}
return resp, nil
}
//PutToken PutToken
func (d *DefineCloudAuth) PutToken() error {
data, err := ffjson.Marshal(d.GT.Body)
if err != nil {
return err
}
_, code, err := request(
fmt.Sprintf("/cloud/auth/%s", d.GT.Body.EID),
"PUT",
data,
)
if err != nil {
logrus.Errorf("create auth token error, %v", err)
return util.CreateAPIHandleError(code, err)
}
if code > 400 {
logrus.Errorf("create auth token error")
return util.CreateAPIHandleError(code, fmt.Errorf("cretae auth token failed"))
}
return nil
}
// //PutToken PutToken
// func (d *DefineCloudAuth) PutToken() error {
// data, err := ffjson.Marshal(d.GT.Body)
// if err != nil {
// return err
// }
// _, code, err := request(
// fmt.Sprintf("/cloud/auth/%s", d.GT.Body.EID),
// "PUT",
// data,
// )
// if err != nil {
// logrus.Errorf("create auth token error, %v", err)
// return util.CreateAPIHandleError(code, err)
// }
// if code > 400 {
// logrus.Errorf("create auth token error")
// return util.CreateAPIHandleError(code, fmt.Errorf("cretae auth token failed"))
// }
// return nil
// }

View File

@ -18,126 +18,117 @@
package region
import (
"fmt"
"github.com/pquerna/ffjson/ffjson"
"github.com/Sirupsen/logrus"
api_model "github.com/goodrain/rainbond/api/model"
)
//DefineSources DefineSources
func (t *tenant) DefineSources(ss *api_model.SourceSpec) DefineSourcesInterface {
return &DefineSources{
tenant: t,
Model: Body{
SourceSpec: ss,
},
}
}
// func (t *tenant) DefineSources(ss *api_model.SourceSpec) DefineSourcesInterface {
// return &DefineSources{
// tenant: *tenant,
// Model: Body{
// SourceSpec: ss,
// },
// }
// }
//DefineSources DefineSources
type DefineSources struct {
tenant *tenant
Model Body
}
// //DefineSources DefineSources
// type DefineSources struct {
// tenant
// Model Body
// }
//Body Body
type Body struct {
SourceSpec *api_model.SourceSpec `json:"source_spec"`
}
// //Body Body
// type Body struct {
// SourceSpec *api_model.SourceSpec `json:"source_spec"`
// }
//DefineSourcesInterface DefineSourcesInterface
type DefineSourcesInterface interface {
GetSource(sourceAlias string) ([]byte, error)
PostSource(sourceAlias string) error
PutSource(SourcesAlias string) error
DeleteSource(sourceAlias string) error
}
// //DefineSourcesInterface DefineSourcesInterface
// type DefineSourcesInterface interface {
// GetSource(sourceAlias string) ([]byte, error)
// PostSource(sourceAlias string) error
// PutSource(SourcesAlias string) error
// DeleteSource(sourceAlias string) error
// }
//GetSource GetSource
func (d *DefineSources) GetSource(sourceAlias string) ([]byte, error) {
resp, status, err := request(
fmt.Sprintf("/v2/tenants/%s/sources/%s/%s",
d.tenant.tenantID, d.Model.SourceSpec.Alias, d.Model.SourceSpec.SourceBody.EnvName),
"GET",
nil,
)
if err != nil {
logrus.Errorf("get define source %s error, %v", d.Model.SourceSpec.SourceBody.EnvName, err)
return nil, err
}
if status > 400 {
if status == 404 {
return nil, fmt.Errorf("source %s is not exist", d.Model.SourceSpec.SourceBody.EnvName)
}
return nil, fmt.Errorf("get define source %s failed", d.Model.SourceSpec.SourceBody.EnvName)
}
//valJ, err := simplejson.NewJson(resp)
return resp, nil
}
// //GetSource GetSource
// func (d *DefineSources) GetSource(sourceAlias string) ([]byte, error) {
// resp, status, err := request(
// fmt.Sprintf("/v2/tenants/%s/sources/%s/%s",
// d.tenant.tenantID, d.Model.SourceSpec.Alias, d.Model.SourceSpec.SourceBody.EnvName),
// "GET",
// nil,
// )
// if err != nil {
// logrus.Errorf("get define source %s error, %v", d.Model.SourceSpec.SourceBody.EnvName, err)
// return nil, err
// }
// if status > 400 {
// if status == 404 {
// return nil, fmt.Errorf("source %s is not exist", d.Model.SourceSpec.SourceBody.EnvName)
// }
// return nil, fmt.Errorf("get define source %s failed", d.Model.SourceSpec.SourceBody.EnvName)
// }
// //valJ, err := simplejson.NewJson(resp)
// return resp, nil
// }
//PostSource PostSource
func (d *DefineSources) PostSource(sourceAlias string) error {
data, err := ffjson.Marshal(d.Model)
if err != nil {
return err
}
_, status, err := request(
fmt.Sprintf("/v2/tenants/%s/sources/%s",
d.tenant.tenantID, d.Model.SourceSpec.Alias),
"POST",
data,
)
if err != nil {
logrus.Errorf("create define source error, %v", err)
return err
}
if status > 400 {
logrus.Errorf("create define source error")
return fmt.Errorf("cretae define source failed")
}
return nil
}
// //PostSource PostSource
// func (d *DefineSources) PostSource(sourceAlias string) error {
// data, err := ffjson.Marshal(d.Model)
// if err != nil {
// return err
// }
// _, status, err := request(
// fmt.Sprintf("/v2/tenants/%s/sources/%s",
// d.tenant.tenantID, d.Model.SourceSpec.Alias),
// "POST",
// data,
// )
// if err != nil {
// logrus.Errorf("create define source error, %v", err)
// return err
// }
// if status > 400 {
// logrus.Errorf("create define source error")
// return fmt.Errorf("cretae define source failed")
// }
// return nil
// }
//PutSource PutSource
func (d *DefineSources) PutSource(sourceAlias string) error {
data, err := ffjson.Marshal(d.Model)
if err != nil {
return err
}
_, status, err := request(
fmt.Sprintf("/v2/tenants/%s/sources/%s/%s",
d.tenant.tenantID, d.Model.SourceSpec.Alias, d.Model.SourceSpec.SourceBody.EnvName),
"PUT",
data,
)
if err != nil {
logrus.Errorf("update define source error, %v", err)
return err
}
if status > 400 {
logrus.Errorf("update define source error")
return fmt.Errorf("update define source failed")
}
return nil
}
// //PutSource PutSource
// func (d *DefineSources) PutSource(sourceAlias string) error {
// data, err := ffjson.Marshal(d.Model)
// if err != nil {
// return err
// }
// _, status, err := request(
// fmt.Sprintf("/v2/tenants/%s/sources/%s/%s",
// d.tenant.tenantID, d.Model.SourceSpec.Alias, d.Model.SourceSpec.SourceBody.EnvName),
// "PUT",
// data,
// )
// if err != nil {
// logrus.Errorf("update define source error, %v", err)
// return err
// }
// if status > 400 {
// logrus.Errorf("update define source error")
// return fmt.Errorf("update define source failed")
// }
// return nil
// }
//DeleteSource DeleteSource
func (d *DefineSources) DeleteSource(sourceAlias string) error {
_, status, err := request(
fmt.Sprintf("/v2/tenants/%s/sources/%s/%s",
d.tenant.tenantID, d.Model.SourceSpec.Alias, d.Model.SourceSpec.SourceBody.EnvName),
"DELETE",
nil,
)
if err != nil {
logrus.Errorf("delete define source error, %v", err)
return err
}
if status > 400 {
logrus.Errorf("delete define source %s error", d.Model.SourceSpec.SourceBody.EnvName)
}
return nil
}
// //DeleteSource DeleteSource
// func (d *DefineSources) DeleteSource(sourceAlias string) error {
// _, status, err := request(
// fmt.Sprintf("/v2/tenants/%s/sources/%s/%s",
// d.tenant.tenantID, d.Model.SourceSpec.Alias, d.Model.SourceSpec.SourceBody.EnvName),
// "DELETE",
// nil,
// )
// if err != nil {
// logrus.Errorf("delete define source error, %v", err)
// return err
// }
// if status > 400 {
// logrus.Errorf("delete define source %s error", d.Model.SourceSpec.SourceBody.EnvName)
// }
// return nil
// }

45
api/region/model.go Normal file
View File

@ -0,0 +1,45 @@
// RAINBOND, Application Management Platform
// Copyright (C) 2014-2017 Goodrain Co., Ltd.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Rainbond,
// one or multiple Commercial Licenses authorized by Goodrain Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package region
import (
"reflect"
dbmodel "github.com/goodrain/rainbond/db/model"
)
var modelRegistry = make(map[string]reflect.Type)
func init() {
registerType("tenants", &[]*dbmodel.Tenants{})
registerType("tenant", &dbmodel.Tenants{})
}
func registerType(name string, elem interface{}) {
t := reflect.TypeOf(elem).Elem()
modelRegistry[name] = t
}
func newStruct(name string) (interface{}, bool) {
elem, ok := modelRegistry[name]
if !ok {
return nil, false
}
return reflect.New(elem).Elem().Interface(), true
}

View File

@ -23,194 +23,39 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"path"
"github.com/bitly/go-simplejson"
"github.com/goodrain/rainbond/api/model"
api_model "github.com/goodrain/rainbond/api/model"
"github.com/goodrain/rainbond/api/util"
"github.com/goodrain/rainbond/cmd"
dbmodel "github.com/goodrain/rainbond/db/model"
coreutil "github.com/goodrain/rainbond/util"
utilhttp "github.com/goodrain/rainbond/util/http"
"github.com/pquerna/ffjson/ffjson"
)
var regionAPI, token string
var region *Region
type Region struct {
regionAPI string
token string
authType string
}
var region Region
func (r *Region) Tenants() TenantInterface {
return &tenant{prefix: "/tenants"}
}
//AllTenant AllTenant
var AllTenant string
type tenant struct {
tenantID string
prefix string
}
type services struct {
tenant *tenant
prefix string
model model.ServiceStruct
}
//TenantInterface TenantInterface
type TenantInterface interface {
Get(name string) *tenant
Services() ServiceInterface
DefineSources(ss *api_model.SourceSpec) DefineSourcesInterface
DefineCloudAuth(gt *api_model.GetUserToken) DefineCloudAuthInterface
}
func (t *tenant) Get(name string) *tenant {
t.tenantID = name
return t
}
func (t *tenant) Delete(name string) error {
return nil
}
func (t *tenant) Services() ServiceInterface {
return &services{
prefix: "services",
tenant: t,
}
}
//ServiceInterface ServiceInterface
type ServiceInterface interface {
Get(name string) (map[string]string, *util.APIHandleError)
Pods(serviceAlisa string) ([]*dbmodel.K8sPod, *util.APIHandleError)
List() ([]*model.ServiceStruct, *util.APIHandleError)
Stop(serviceAlisa, eventID string) *util.APIHandleError
Start(serviceAlisa, eventID string) *util.APIHandleError
EventLog(serviceAlisa, eventID, level string) ([]*model.MessageData, *util.APIHandleError)
}
func (s *services) Pods(serviceAlisa string) ([]*dbmodel.K8sPod, *util.APIHandleError) {
body, code, err := request("/v2"+s.tenant.prefix+"/"+s.tenant.tenantID+"/"+s.prefix+"/"+serviceAlisa+"/pods", "GET", nil)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get database center configs code %d", code))
}
var res utilhttp.ResponseBody
var gc []*dbmodel.K8sPod
res.List = &gc
if err := ffjson.Unmarshal(body, &res); err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if gc, ok := res.List.(*[]*dbmodel.K8sPod); ok {
return *gc, nil
}
return nil, nil
}
func (s *services) Get(name string) (map[string]string, *util.APIHandleError) {
body, code, err := request("/v2"+s.tenant.prefix+"/"+s.tenant.tenantID+"/"+s.prefix+"/"+name, "GET", nil)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get err with code %d", code))
}
j, err := simplejson.NewJson(body)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
m := make(map[string]string)
bean := j.Get("bean")
sa, err := bean.Get("serviceAlias").String()
si, err := bean.Get("serviceId").String()
ti, err := bean.Get("tenantId").String()
tn, err := bean.Get("tenantName").String()
m["serviceAlias"] = sa
m["serviceId"] = si
m["tenantId"] = ti
m["tenantName"] = tn
return m, nil
}
func (s *services) EventLog(serviceAlisa, eventID, level string) ([]*model.MessageData, *util.APIHandleError) {
data := []byte(`{"event_id":"` + eventID + `","level":"` + level + `"}`)
body, code, err := request("/v2"+s.tenant.prefix+"/"+s.tenant.tenantID+"/"+s.prefix+"/event-log", "POST", data)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get database center configs code %d", code))
}
var res utilhttp.ResponseBody
var gc []*model.MessageData
res.List = &gc
if err := ffjson.Unmarshal(body, &res); err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if gc, ok := res.List.(*[]*model.MessageData); ok {
return *gc, nil
}
return nil, nil
}
func (s *services) List() ([]*model.ServiceStruct, *util.APIHandleError) {
body, code, err := request("/v2"+s.tenant.prefix+"/"+s.tenant.tenantID+"/"+s.prefix, "GET", nil)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get with code %d", code))
}
var res utilhttp.ResponseBody
var gc []*model.ServiceStruct
res.List = &gc
if err := ffjson.Unmarshal(body, &res); err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if gc, ok := res.List.(*[]*model.ServiceStruct); ok {
return *gc, nil
}
return nil, nil
}
func (s *services) Stop(name, eventID string) *util.APIHandleError {
data := []byte(`{"event_id":"` + eventID + `"}`)
_, code, err := request("/v2"+s.tenant.prefix+"/"+s.tenant.tenantID+"/"+s.prefix+"/"+name+"/stop", "POST", data)
return handleErrAndCode(err, code)
}
func (s *services) Start(name, eventID string) *util.APIHandleError {
data := []byte(`{"event_id":"` + eventID + `"}`)
_, code, err := request("/v2"+s.tenant.prefix+"/"+s.tenant.tenantID+"/"+s.prefix+"/"+name+"/start", "POST", data)
return handleErrAndCode(err, code)
}
func request(url, method string, body []byte) ([]byte, int, error) {
request, err := http.NewRequest(method, region.regionAPI+url, bytes.NewBuffer(body))
if err != nil {
return nil, 500, err
}
request.Header.Set("Content-Type", "application/json")
if region.token != "" {
request.Header.Set("Authorization", "Token "+region.token)
}
res, err := http.DefaultClient.Do(request)
if err != nil {
return nil, 500, err
}
data, err := ioutil.ReadAll(res.Body)
if res.Body != nil {
defer res.Body.Close()
}
return data, res.StatusCode, err
//Region region api
type Region interface {
Tenants(name string) TenantInterface
Resources() ResourcesInterface
//Nodes() NodeInterface
Version() string
DoRequest(path, method string, body io.Reader, decode *utilhttp.ResponseBody) (int, error)
}
//NewRegion NewRegion
func NewRegion(regionAPI, token, authType string) *Region {
func NewRegion(regionAPI, token, authType string) Region {
if region == nil {
region = &Region{
region = &regionImpl{
regionAPI: regionAPI,
token: token,
authType: authType,
@ -218,10 +63,191 @@ func NewRegion(regionAPI, token, authType string) *Region {
}
return region
}
func GetRegion() *Region {
//GetRegion GetRegion
func GetRegion() Region {
return region
}
type regionImpl struct {
regionAPI string
token string
authType string
}
//Tenants Tenants
func (r *regionImpl) Tenants(tenantName string) TenantInterface {
return &tenant{prefix: path.Join("/v2/tenants", tenantName), tenantName: tenantName, regionImpl: *r}
}
//Version Version
func (r *regionImpl) Version() string {
return cmd.GetVersion()
}
//Resources about resources
func (r *regionImpl) Resources() ResourcesInterface {
return &resources{prefix: "/v2/resources", regionImpl: *r}
}
type tenant struct {
regionImpl
tenantName string
prefix string
}
type services struct {
tenant
prefix string
model model.ServiceStruct
}
//TenantInterface TenantInterface
type TenantInterface interface {
Get() (*dbmodel.Tenants, *util.APIHandleError)
List() ([]*dbmodel.Tenants, *util.APIHandleError)
Delete() *util.APIHandleError
Services(serviceAlias string) ServiceInterface
// DefineSources(ss *api_model.SourceSpec) DefineSourcesInterface
// DefineCloudAuth(gt *api_model.GetUserToken) DefineCloudAuthInterface
}
func (t *tenant) Get() (*dbmodel.Tenants, *util.APIHandleError) {
var decode utilhttp.ResponseBody
var tenant dbmodel.Tenants
decode.Bean = &tenant
code, err := t.DoRequest(t.prefix, "GET", nil, &decode)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
return &tenant, nil
}
func (t *tenant) List() ([]*dbmodel.Tenants, *util.APIHandleError) {
if t.tenantName != "" {
return nil, util.CreateAPIHandleErrorf(400, "tenant name must be empty in this api")
}
var decode utilhttp.ResponseBody
var tenants []*dbmodel.Tenants
decode.List = &tenants
code, err := t.DoRequest(t.prefix, "GET", nil, &decode)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
return tenants, nil
}
func (t *tenant) Delete() *util.APIHandleError {
return nil
}
func (t *tenant) Services(serviceAlias string) ServiceInterface {
return &services{
prefix: path.Join(t.prefix, "services", serviceAlias),
tenant: *t,
}
}
//ServiceInterface ServiceInterface
type ServiceInterface interface {
Get() (*dbmodel.TenantServices, *util.APIHandleError)
Pods() ([]*dbmodel.K8sPod, *util.APIHandleError)
List() ([]*dbmodel.TenantServices, *util.APIHandleError)
Stop(eventID string) (string, *util.APIHandleError)
Start(eventID string) (string, *util.APIHandleError)
EventLog(eventID, level string) ([]*model.MessageData, *util.APIHandleError)
}
func (s *services) Pods() ([]*dbmodel.K8sPod, *util.APIHandleError) {
var gc []*dbmodel.K8sPod
var decode utilhttp.ResponseBody
decode.List = &gc
code, err := s.DoRequest(s.prefix+"/pods", "GET", nil, &decode)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get database center configs code %d", code))
}
return gc, nil
}
func (s *services) Get() (*dbmodel.TenantServices, *util.APIHandleError) {
var service dbmodel.TenantServices
var decode utilhttp.ResponseBody
decode.Bean = &service
code, err := s.DoRequest(s.prefix, "GET", nil, &decode)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get err with code %d", code))
}
return &service, nil
}
func (s *services) EventLog(eventID, level string) ([]*model.MessageData, *util.APIHandleError) {
data := []byte(`{"event_id":"` + eventID + `","level":"` + level + `"}`)
var message []*model.MessageData
var decode utilhttp.ResponseBody
decode.List = &message
code, err := s.DoRequest(s.prefix+"/event-log", "POST", bytes.NewBuffer(data), &decode)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get database center configs code %d", code))
}
return message, nil
}
func (s *services) List() ([]*dbmodel.TenantServices, *util.APIHandleError) {
var gc []*dbmodel.TenantServices
var decode utilhttp.ResponseBody
decode.List = &gc
code, err := s.DoRequest(s.prefix, "GET", nil, &decode)
if err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
if code != 200 {
return nil, util.CreateAPIHandleError(code, fmt.Errorf("Get with code %d", code))
}
return gc, nil
}
func (s *services) Stop(eventID string) (string, *util.APIHandleError) {
if eventID == "" {
eventID = coreutil.NewUUID()
}
data := []byte(`{"event_id":"` + eventID + `"}`)
code, err := s.DoRequest(s.prefix+"/stop", "POST", bytes.NewBuffer(data), nil)
return eventID, handleErrAndCode(err, code)
}
func (s *services) Start(eventID string) (string, *util.APIHandleError) {
if eventID == "" {
eventID = coreutil.NewUUID()
}
data := []byte(`{"event_id":"` + eventID + `"}`)
code, err := s.DoRequest(s.prefix+"/start", "POST", bytes.NewBuffer(data), nil)
return eventID, handleErrAndCode(err, code)
}
//DoRequest do request
func (r *regionImpl) DoRequest(path, method string, body io.Reader, decode *utilhttp.ResponseBody) (int, error) {
request, err := http.NewRequest(method, r.regionAPI+path, body)
if err != nil {
return 500, err
}
request.Header.Set("Content-Type", "application/json")
if r.token != "" {
request.Header.Set("Authorization", "Token "+r.token)
}
res, err := http.DefaultClient.Do(request)
if err != nil {
return 500, err
}
if res.Body != nil {
defer res.Body.Close()
}
if err := json.NewDecoder(res.Body).Decode(decode); err != nil {
return res.StatusCode, err
}
return res.StatusCode, err
}
func LoadConfig(regionAPI, token string) (map[string]map[string]interface{}, error) {
if regionAPI != "" {
//return nil, errors.New("region api url can not be empty")
@ -276,22 +302,18 @@ func handleErrAndCode(err error, code int) *util.APIHandleError {
return nil
}
//Resources about resources
func (r *Region) Resources() ResourcesInterface {
return &resources{prefix: "/v2/resources"}
}
//ResourcesInterface ResourcesInterface
type ResourcesInterface interface {
Tenants(tenantName string) ResourcesTenantInterface
}
type resources struct {
regionImpl
prefix string
}
func (r *resources) Tenants(tenantName string) ResourcesTenantInterface {
return &resourcesTenant{prefix: path.Join(r.prefix, "tenants", tenantName)}
return &resourcesTenant{prefix: path.Join(r.prefix, "tenants", tenantName), resources: *r}
}
//ResourcesTenantInterface ResourcesTenantInterface
@ -299,19 +321,17 @@ type ResourcesTenantInterface interface {
Get() (*model.TenantResource, *util.APIHandleError)
}
type resourcesTenant struct {
resources
prefix string
}
func (r *resourcesTenant) Get() (*model.TenantResource, *util.APIHandleError) {
res, code, err := request(r.prefix+"/res", "GET", nil)
var rt model.TenantResource
var decode utilhttp.ResponseBody
decode.Bean = &rt
code, err := r.DoRequest(r.prefix+"/res", "GET", nil, &decode)
if err != nil {
return nil, handleErrAndCode(err, code)
}
var reb utilhttp.ResponseBody
var rt model.TenantResource
reb.Bean = &rt
if err := json.Unmarshal(res, &reb); err != nil {
return nil, util.CreateAPIHandleError(code, err)
}
return &rt, nil
}

58
api/region/region_test.go Normal file
View File

@ -0,0 +1,58 @@
// RAINBOND, Application Management Platform
// Copyright (C) 2014-2017 Goodrain Co., Ltd.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Rainbond,
// one or multiple Commercial Licenses authorized by Goodrain Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package region
import (
"testing"
dbmodel "github.com/goodrain/rainbond/db/model"
utilhttp "github.com/goodrain/rainbond/util/http"
)
func TestListTenant(t *testing.T) {
region := NewRegion("http://kubeapi.goodrain.me:8888", "", "")
tenants, err := region.Tenants("").List()
if err != nil {
t.Fatal(err)
}
t.Logf("%+v", tenants)
}
func TestListServices(t *testing.T) {
region := NewRegion("http://kubeapi.goodrain.me:8888", "", "")
services, err := region.Tenants("n93lkp7t").Services("").List()
if err != nil {
t.Fatal(err)
}
for _, s := range services {
t.Logf("%+v", s)
}
}
func TestDoRequest(t *testing.T) {
region := NewRegion("http://kubeapi.goodrain.me:8888", "", "")
var decode utilhttp.ResponseBody
var tenants []*dbmodel.Tenants
decode.List = &tenants
code, err := region.DoRequest("/v2/tenants", "GET", nil, &decode)
if err != nil {
t.Fatal(err, code)
}
t.Logf("%+v", tenants)
}

View File

@ -19,20 +19,19 @@
package clients
import (
"github.com/goodrain/rainbond/cmd/grctl/option"
"github.com/goodrain/rainbond/api/region"
"github.com/goodrain/rainbond/cmd/grctl/option"
)
//RegionClient region api
var RegionClient *region.Region
var RegionClient region.Region
//NodeClient node api
var NodeClient *region.RNodeClient
//InitRegionClient init region api client
func InitRegionClient(reg option.RegionAPI) error {
region.NewRegion(reg.URL, reg.Token, reg.Type)
RegionClient = region.GetRegion()
RegionClient = region.NewRegion(reg.URL, reg.Token, reg.Type)
return nil
}

View File

@ -18,179 +18,166 @@
package cmd
import (
"fmt"
"strconv"
// //CloudAuth CloudAuth
// type CloudAuth struct {
// c *cli.Context
// }
"github.com/gosuri/uitable"
"github.com/pquerna/ffjson/ffjson"
// type respBean struct {
// Bean *dbmodel.RegionUserInfo `json:"bean"`
// }
api_model "github.com/goodrain/rainbond/api/model"
dbmodel "github.com/goodrain/rainbond/db/model"
"github.com/goodrain/rainbond/grctl/clients"
"github.com/urfave/cli"
)
// //NewCmdCloudAuth 云市授权相关操作
// func NewCmdCloudAuth() cli.Command {
// c := cli.Command{
// Name: "auth",
// Usage: "自定义云市授权相关操作。grctl auth [create/update/get] -e [EID] -t [VALIDITY DATE] ",
// Subcommands: []cli.Command{
// {
// Name: "create",
// Usage: "创建授权信息。 grctl auth create -e EID -t VALIDITY_DATE",
// Action: func(c *cli.Context) error {
// return authAction(c, "create")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "eid, e",
// Usage: "企业id-e EID",
// },
// cli.StringFlag{
// Name: "ttl, t",
// Usage: "有效期,-t VALIDITY_DATE",
// },
// },
// },
// {
// Name: "update",
// Usage: "更新授权有效期。 grctl auth update -e EID -t VALIDITY_DATE",
// Action: func(c *cli.Context) error {
// return authAction(c, "update")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "eid, e",
// Usage: "企业id-e EID",
// },
// cli.StringFlag{
// Name: "ttl, t",
// Usage: "有效期,-t VALIDITY_DATE",
// },
// },
// },
// {
// Name: "get",
// Usage: "获取授权信息。 grctl auth get -e EID",
// Action: func(c *cli.Context) error {
// return authAction(c, "get")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "eid, e",
// Usage: "企业id-e EID",
// },
// },
// },
// },
// }
// return c
// }
//CloudAuth CloudAuth
type CloudAuth struct {
c *cli.Context
}
// func authAction(c *cli.Context, action string) error {
// Common(c)
// ca := CloudAuth{
// c: c,
// }
// switch action {
// case "create", "-c":
// return ca.createToken()
// case "update", "-u":
// return ca.updateTokenTime()
// case "get", "-g":
// return ca.getToken()
// }
// return fmt.Errorf("Commands wrong, first args must in [create/update/get] or their simplified format")
// }
type respBean struct {
Bean *dbmodel.RegionUserInfo `json:"bean"`
}
// func (ca *CloudAuth) createToken() error {
// eid, err := checkoutKV(ca.c, "eid")
// if err != nil {
// return err
// }
// ttl, err := checkoutKV(ca.c, "ttl")
// if err != nil {
// return err
// }
// var gt api_model.GetUserToken
// tt, _ := strconv.Atoi(ttl)
// gt.Body.EID = eid
// gt.Body.ValidityPeriod = tt
// resp, err := clients.RegionClient.Tenants().DefineCloudAuth(&gt).PostToken()
// if err != nil {
// fmt.Printf("create auth %s failure\n", gt.Body.EID)
// return err
// }
// var rb respBean
// if err := ffjson.Unmarshal(resp, &rb); err != nil {
// return err
// }
// table := uitable.New()
// table.Wrap = true // wrap columns
// fmt.Printf("-------------------------------------------------\n")
// table.AddRow("EID:", rb.Bean.EID)
// table.AddRow("TOKEN:", rb.Bean.Token)
// table.AddRow("VALIDITY_DATE:", rb.Bean.ValidityPeriod)
// table.AddRow("CA:", rb.Bean.CA)
// fmt.Println(table)
// return nil
// }
//NewCmdCloudAuth 云市授权相关操作
func NewCmdCloudAuth() cli.Command {
c := cli.Command{
Name: "auth",
Usage: "自定义云市授权相关操作。grctl auth [create/update/get] -e [EID] -t [VALIDITY DATE] ",
Subcommands: []cli.Command{
{
Name: "create",
Usage: "创建授权信息。 grctl auth create -e EID -t VALIDITY_DATE",
Action: func(c *cli.Context) error {
return authAction(c, "create")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "eid, e",
Usage: "企业id-e EID",
},
cli.StringFlag{
Name: "ttl, t",
Usage: "有效期,-t VALIDITY_DATE",
},
},
},
{
Name: "update",
Usage: "更新授权有效期。 grctl auth update -e EID -t VALIDITY_DATE",
Action: func(c *cli.Context) error {
return authAction(c, "update")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "eid, e",
Usage: "企业id-e EID",
},
cli.StringFlag{
Name: "ttl, t",
Usage: "有效期,-t VALIDITY_DATE",
},
},
},
{
Name: "get",
Usage: "获取授权信息。 grctl auth get -e EID",
Action: func(c *cli.Context) error {
return authAction(c, "get")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "eid, e",
Usage: "企业id-e EID",
},
},
},
},
}
return c
}
// func (ca *CloudAuth) updateTokenTime() error {
// eid, err := checkoutKV(ca.c, "eid")
// if err != nil {
// return err
// }
// ttl, err := checkoutKV(ca.c, "ttl")
// if err != nil {
// return err
// }
// var gt api_model.GetUserToken
// tt, _ := strconv.Atoi(ttl)
// gt.Body.EID = eid
// gt.Body.ValidityPeriod = tt
// if err := clients.RegionClient.Tenants().DefineCloudAuth(&gt).PutToken(); err != nil {
// fmt.Printf("update auth %s failure\n", gt.Body.EID)
// return err
// }
// fmt.Printf("update auth %s success\n", gt.Body.EID)
// return nil
// }
func authAction(c *cli.Context, action string) error {
Common(c)
ca := CloudAuth{
c: c,
}
switch action {
case "create", "-c":
return ca.createToken()
case "update", "-u":
return ca.updateTokenTime()
case "get", "-g":
return ca.getToken()
}
return fmt.Errorf("Commands wrong, first args must in [create/update/get] or their simplified format")
}
func (ca *CloudAuth) createToken() error {
eid, err := checkoutKV(ca.c, "eid")
if err != nil {
return err
}
ttl, err := checkoutKV(ca.c, "ttl")
if err != nil {
return err
}
var gt api_model.GetUserToken
tt, _ := strconv.Atoi(ttl)
gt.Body.EID = eid
gt.Body.ValidityPeriod = tt
resp, err := clients.RegionClient.Tenants().DefineCloudAuth(&gt).PostToken()
if err != nil {
fmt.Printf("create auth %s failure\n", gt.Body.EID)
return err
}
var rb respBean
if err := ffjson.Unmarshal(resp, &rb); err != nil {
return err
}
table := uitable.New()
table.Wrap = true // wrap columns
fmt.Printf("-------------------------------------------------\n")
table.AddRow("EID:", rb.Bean.EID)
table.AddRow("TOKEN:", rb.Bean.Token)
table.AddRow("VALIDITY_DATE:", rb.Bean.ValidityPeriod)
table.AddRow("CA:", rb.Bean.CA)
fmt.Println(table)
return nil
}
func (ca *CloudAuth) updateTokenTime() error {
eid, err := checkoutKV(ca.c, "eid")
if err != nil {
return err
}
ttl, err := checkoutKV(ca.c, "ttl")
if err != nil {
return err
}
var gt api_model.GetUserToken
tt, _ := strconv.Atoi(ttl)
gt.Body.EID = eid
gt.Body.ValidityPeriod = tt
if err := clients.RegionClient.Tenants().DefineCloudAuth(&gt).PutToken(); err != nil {
fmt.Printf("update auth %s failure\n", gt.Body.EID)
return err
}
fmt.Printf("update auth %s success\n", gt.Body.EID)
return nil
}
func (ca *CloudAuth) getToken() error {
eid, err := checkoutKV(ca.c, "eid")
if err != nil {
return err
}
var gt api_model.GetUserToken
gt.Body.EID = eid
resp, err := clients.RegionClient.Tenants().DefineCloudAuth(&gt).GetToken()
if err != nil {
fmt.Printf("get auth %s failure\n", gt.Body.EID)
return err
}
var rb respBean
if err := ffjson.Unmarshal(resp, &rb); err != nil {
return err
}
table := uitable.New()
table.Wrap = true // wrap columns
fmt.Printf("-------------------------------------------------\n")
table.AddRow("EID:", rb.Bean.EID)
table.AddRow("TOKEN:", rb.Bean.Token)
table.AddRow("VALIDITY_DATE:", rb.Bean.ValidityPeriod)
table.AddRow("CA:", rb.Bean.CA)
fmt.Println(table)
return nil
}
// func (ca *CloudAuth) getToken() error {
// eid, err := checkoutKV(ca.c, "eid")
// if err != nil {
// return err
// }
// var gt api_model.GetUserToken
// gt.Body.EID = eid
// resp, err := clients.RegionClient.Tenants().DefineCloudAuth(&gt).GetToken()
// if err != nil {
// fmt.Printf("get auth %s failure\n", gt.Body.EID)
// return err
// }
// var rb respBean
// if err := ffjson.Unmarshal(resp, &rb); err != nil {
// return err
// }
// table := uitable.New()
// table.Wrap = true // wrap columns
// fmt.Printf("-------------------------------------------------\n")
// table.AddRow("EID:", rb.Bean.EID)
// table.AddRow("TOKEN:", rb.Bean.Token)
// table.AddRow("VALIDITY_DATE:", rb.Bean.ValidityPeriod)
// table.AddRow("CA:", rb.Bean.CA)
// fmt.Println(table)
// return nil
// }

View File

@ -32,7 +32,7 @@ func GetCmds() []cli.Command {
cmds = append(cmds, NewCmdTenant())
cmds = append(cmds, NewCmdNode())
cmds = append(cmds, NewCmdNodeRes())
cmds = append(cmds, NewCmdCluster())
cmds = append(cmds, NewCmdExec())
cmds = append(cmds, NewCmdInit())
cmds = append(cmds, NewCmdShow())
@ -51,8 +51,8 @@ func GetCmds() []cli.Command {
//cmds = append(cmds, NewCmdBaseManageGroup())
//cmds = append(cmds, NewCmdManageGroup())
cmds = append(cmds, NewCmdSources())
cmds = append(cmds, NewCmdCloudAuth())
//cmds = append(cmds, NewCmdSources())
//cmds = append(cmds, NewCmdCloudAuth())
//cmds = append(cmds, NewCmdRegionNode())
//cmds = append(cmds, NewCmdTest())
//cmds = append(cmds, NewCmdPlugin())

View File

@ -424,29 +424,28 @@ func NewCmdNode() cli.Command {
return c
}
func NewCmdNodeRes() cli.Command {
//NewCmdCluster cmd for cluster
func NewCmdCluster() cli.Command {
c := cli.Command{
Name: "noderes",
Usage: "获取计算节点资源信息 grctl noderes",
Name: "cluster",
Usage: "获取集群信息 grctl cluster",
Action: func(c *cli.Context) error {
Common(c)
return getNodeWithResource(c)
return getClusterInfo(c)
},
}
return c
}
func getNodeWithResource(c *cli.Context) error {
func getClusterInfo(c *cli.Context) error {
ns, err := clients.K8SClient.Core().Nodes().List(metav1.ListOptions{})
if err != nil {
logrus.Errorf("获取节点列表失败,details: %s", err.Error())
return err
}
table := termtables.CreateTable()
table.AddHeaders("NodeName", "Version", "CapCPU(核)", "AllocatableCPU(核)", "UsedCPU(核)", "CapMemory(M)", "AllocatableMemory(M)", "UsedMemory(M)")
for _, v := range ns.Items {
podList, err := clients.K8SClient.Core().Pods(metav1.NamespaceAll).List(metav1.ListOptions{FieldSelector: fields.SelectorFromSet(fields.Set{"spec.nodeName": v.Name}).String()})
if err != nil {
@ -479,6 +478,7 @@ func getNodeWithResource(c *cli.Context) error {
fmt.Println(table.Render())
return nil
}
func isNodeReady(node *client.HostNode) bool {
if node.NodeStatus == nil {
return false

View File

@ -18,87 +18,78 @@
package cmd
import (
"fmt"
// //NewCmdPlugin 插件相关操作
// func NewCmdPlugin() cli.Command {
// c := cli.Command{
// Name: "plugin",
// Usage: "插件相关操作。grctl plugin [create/delete/update/build] NAMESPACE PLUGIN_ID [commands] [sources]",
// Subcommands: []cli.Command{
// {
// Name: "create",
// Usage: "创建自定义资源。 grctl sources create -g NAMESPACE/SOURCEALIAS -k ENVNAME -v ENVVALUE",
// Action: func(c *cli.Context) error {
// return sourcesAction(c, "create")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "group, g",
// Usage: "--group/-g NAMESPACE/SOURCEALIAS",
// },
// cli.StringFlag{
// Name: "key, k",
// Usage: "自定义资源名,-k ENVNAME",
// },
// cli.StringFlag{
// Name: "value, v",
// Usage: "自定义资源值,-v ENVVALUE",
// },
// },
// },
// },
// }
// return c
// }
// func pluginAction(c *cli.Context) error {
// action := c.Args().First()
// switch action {
// case "create", "-c":
// return createPlugin(c)
// case "update", "-u":
// return updatePlugin(c)
// case "delete", "-d":
// return deletePlugin(c)
// }
// return fmt.Errorf("Commands wrong, first args must in [create/update/delete] or their simplified form")
// }
"github.com/pquerna/ffjson/ffjson"
// func getItems(c *cli.Context, lens int) (string, string, *api_model.CreatePluginStruct, error) {
// if len(c.Args()) != lens {
// return "", "", nil, fmt.Errorf("Commands nums wrong, need %d args", lens)
// }
// var cps api_model.CreatePluginStruct
// tenantName := c.Args().Get(1)
// pluginID := c.Args().Get(2)
// if len(c.Args()) > 3 {
// infos := c.Args().Get(4)
// if err := ffjson.Unmarshal([]byte(infos), &cps.Body); err != nil {
// return "", "", nil, err
// }
// return tenantName, pluginID, &cps, nil
// }
// return tenantName, pluginID, nil, nil
// }
api_model "github.com/goodrain/rainbond/api/model"
"github.com/urfave/cli"
)
// func createPlugin(c *cli.Context) error {
// //args 5
// return nil
// }
//NewCmdPlugin 插件相关操作
func NewCmdPlugin() cli.Command {
c := cli.Command{
Name: "plugin",
Usage: "插件相关操作。grctl plugin [create/delete/update/build] NAMESPACE PLUGIN_ID [commands] [sources]",
Subcommands: []cli.Command{
{
Name: "create",
Usage: "创建自定义资源。 grctl sources create -g NAMESPACE/SOURCEALIAS -k ENVNAME -v ENVVALUE",
Action: func(c *cli.Context) error {
return sourcesAction(c, "create")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "group, g",
Usage: "--group/-g NAMESPACE/SOURCEALIAS",
},
cli.StringFlag{
Name: "key, k",
Usage: "自定义资源名,-k ENVNAME",
},
cli.StringFlag{
Name: "value, v",
Usage: "自定义资源值,-v ENVVALUE",
},
},
},
},
}
return c
}
func pluginAction(c *cli.Context) error {
action := c.Args().First()
switch action {
case "create", "-c":
return createPlugin(c)
case "update", "-u":
return updatePlugin(c)
case "delete", "-d":
return deletePlugin(c)
}
return fmt.Errorf("Commands wrong, first args must in [create/update/delete] or their simplified form")
}
// func updatePlugin(c *cli.Context) error {
// //args 5
// return nil
// }
func getItems(c *cli.Context, lens int) (string, string, *api_model.CreatePluginStruct, error) {
if len(c.Args()) != lens {
return "", "", nil, fmt.Errorf("Commands nums wrong, need %d args", lens)
}
var cps api_model.CreatePluginStruct
tenantName := c.Args().Get(1)
pluginID := c.Args().Get(2)
if len(c.Args()) > 3 {
infos := c.Args().Get(4)
if err := ffjson.Unmarshal([]byte(infos), &cps.Body); err != nil {
return "", "", nil, err
}
return tenantName, pluginID, &cps, nil
}
return tenantName, pluginID, nil, nil
}
func createPlugin(c *cli.Context) error {
//args 5
return nil
}
func updatePlugin(c *cli.Context) error {
//args 5
return nil
}
func deletePlugin(c *cli.Context) error {
//args 3
return nil
}
// func deletePlugin(c *cli.Context) error {
// //args 3
// return nil
// }

View File

@ -198,7 +198,7 @@ func getEventLog(c *cli.Context) error {
} else {
ts := c.Args().Get(1)
tas := strings.Split(ts, "/")
dl, err := clients.RegionClient.Tenants().Get(tas[0]).Services().EventLog(tas[1], eventID, "debug")
dl, err := clients.RegionClient.Tenants(tas[0]).Services(tas[1]).EventLog(eventID, "debug")
if err != nil {
return err
}
@ -215,17 +215,17 @@ func stopTenantService(c *cli.Context) error {
//GET /v2/tenants/{tenant_name}/services/{service_alias}
//POST /v2/tenants/{tenant_name}/services/{service_alias}/stop
tenantID := c.Args().First()
if tenantID == "" {
tenantName := c.Args().First()
if tenantName == "" {
fmt.Println("Please provide tenant name")
os.Exit(1)
}
eventID := "system"
services, err := clients.RegionClient.Tenants().Get(tenantID).Services().List()
services, err := clients.RegionClient.Tenants(tenantName).Services("").List()
handleErr(err)
for _, service := range services {
if service.CurStatus != "closed" && service.CurStatus != "closing" {
err := clients.RegionClient.Tenants().Get(tenantID).Services().Stop(service.ServiceAlias, eventID)
_, err := clients.RegionClient.Tenants(tenantName).Services(service.ServiceAlias).Stop(eventID)
if c.Bool("f") {
server := "127.0.0.1:6363"
if c.String("event_log_server") != "" {
@ -252,12 +252,12 @@ func startService(c *cli.Context) error {
eventID := c.Args().Get(1)
service, err := clients.RegionClient.Tenants().Get(info[0]).Services().Get(info[1])
service, err := clients.RegionClient.Tenants(info[0]).Services(info[1]).Get()
handleErr(err)
if service == nil {
return errors.New("应用不存在:" + info[1])
}
err = clients.RegionClient.Tenants().Get(info[0]).Services().Start(info[1], eventID)
_, err = clients.RegionClient.Tenants(info[0]).Services(info[1]).Start(eventID)
handleErr(err)
if c.Bool("f") {
server := "127.0.0.1:6363"
@ -281,12 +281,12 @@ func stopService(c *cli.Context) error {
info := strings.Split(serviceAlias, "/")
eventID := c.Args().Get(1)
service, err := clients.RegionClient.Tenants().Get(info[0]).Services().Get(info[1])
service, err := clients.RegionClient.Tenants(info[0]).Services(info[1]).Get()
handleErr(err)
if service == nil {
return errors.New("应用不存在:" + info[1])
}
err = clients.RegionClient.Tenants().Get(info[0]).Services().Stop(info[1], eventID)
_, err = clients.RegionClient.Tenants(info[0]).Services(info[1]).Stop(eventID)
handleErr(err)
if c.Bool("f") {
server := "127.0.0.1:6363"
@ -327,7 +327,7 @@ func getAppInfoV2(c *cli.Context) error {
} else {
serviceAlias = value
}
service, err := clients.RegionClient.Tenants().Get(tenantName).Services().Get(serviceAlias)
service, err := clients.RegionClient.Tenants(tenantName).Services(serviceAlias).Get()
handleErr(err)
if service == nil {
fmt.Println("not found")
@ -336,8 +336,8 @@ func getAppInfoV2(c *cli.Context) error {
table := uitable.New()
table.Wrap = true // wrap columns
tenantID := service["tenantId"]
serviceID := service["serviceId"]
tenantID := service.TenantID
serviceID := service.ServiceID
//volumes:=service[""]
table.AddRow("Namespace:", tenantID)
@ -345,7 +345,7 @@ func getAppInfoV2(c *cli.Context) error {
//table.AddRow("Volume:", volumes)
option := metav1.ListOptions{LabelSelector: "name=" + serviceAlias}
ps, err := clients.RegionClient.Tenants().Get(tenantName).Services().Pods(serviceAlias)
ps, err := clients.RegionClient.Tenants(tenantName).Services(serviceAlias).Pods()
handleErr(err)
var rcMap = make(map[string]string)

View File

@ -18,262 +18,251 @@
package cmd
import (
"fmt"
"strings"
"time"
// //NewCmdSources 资源相关操作
// func NewCmdSources() cli.Command {
// c := cli.Command{
// Name: "sources",
// Usage: "自定义资源相关操作。grctl sources [create/delete/update/get] -g NAMESPACE/SOURCEALIAS [commands] [sources]",
// Subcommands: []cli.Command{
// {
// Name: "create",
// Usage: "创建自定义资源。 grctl sources create -g NAMESPACE/SOURCEALIAS -k ENVNAME -v ENVVALUE",
// Action: func(c *cli.Context) error {
// return sourcesAction(c, "create")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "group, g",
// Usage: "--group/-g NAMESPACE/SOURCEALIAS",
// },
// cli.StringFlag{
// Name: "key, k",
// Usage: "自定义资源名,-k ENVNAME",
// },
// cli.StringFlag{
// Name: "value, v",
// Usage: "自定义资源值,-v ENVVALUE",
// },
// },
// },
// {
// Name: "update",
// Usage: "更新自定义资源。 grctl sources update -g NAMESPACE/SOURCEALIAS -k ENVNAME -v ENVVALUE",
// Action: func(c *cli.Context) error {
// return sourcesAction(c, "update")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "group, g",
// Usage: "--group/-g NAMESPACE/SOURCEALIAS",
// },
// cli.StringFlag{
// Name: "key, k",
// Usage: "自定义资源名,-k ENVNAME",
// },
// cli.StringFlag{
// Name: "value, v",
// Usage: "自定义资源值,-v ENVVALUE",
// },
// },
// },
// {
// Name: "delete",
// Usage: "删除自定义资源。 grctl sources delete -g NAMESPACE/SOURCEALIAS -k ENVNAME",
// Action: func(c *cli.Context) error {
// return sourcesAction(c, "delete")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "group, g",
// Usage: "--group/-g NAMESPACE/SOURCEALIAS",
// },
// cli.StringFlag{
// Name: "key, k",
// Usage: "自定义资源名,-k ENVNAME",
// },
// },
// },
// {
// Name: "get",
// Usage: "获取自定义资源。 grctl sources get -g NAMESPACE/SOURCEALIAS -k ENVNAME",
// Action: func(c *cli.Context) error {
"github.com/Sirupsen/logrus"
api_model "github.com/goodrain/rainbond/api/model"
"github.com/goodrain/rainbond/grctl/clients"
"github.com/urfave/cli"
)
// return sourcesAction(c, "get")
// },
// Flags: []cli.Flag{
// cli.StringFlag{
// Name: "group, g",
// Usage: "--group/-g NAMESPACE/SOURCEALIAS",
// },
// cli.StringFlag{
// Name: "key, k",
// Usage: "自定义资源名,-k ENVNAME",
// },
// },
// },
// },
// }
// return c
// }
//NewCmdSources 资源相关操作
func NewCmdSources() cli.Command {
c := cli.Command{
Name: "sources",
Usage: "自定义资源相关操作。grctl sources [create/delete/update/get] -g NAMESPACE/SOURCEALIAS [commands] [sources]",
Subcommands: []cli.Command{
{
Name: "create",
Usage: "创建自定义资源。 grctl sources create -g NAMESPACE/SOURCEALIAS -k ENVNAME -v ENVVALUE",
Action: func(c *cli.Context) error {
return sourcesAction(c, "create")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "group, g",
Usage: "--group/-g NAMESPACE/SOURCEALIAS",
},
cli.StringFlag{
Name: "key, k",
Usage: "自定义资源名,-k ENVNAME",
},
cli.StringFlag{
Name: "value, v",
Usage: "自定义资源值,-v ENVVALUE",
},
},
},
{
Name: "update",
Usage: "更新自定义资源。 grctl sources update -g NAMESPACE/SOURCEALIAS -k ENVNAME -v ENVVALUE",
Action: func(c *cli.Context) error {
return sourcesAction(c, "update")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "group, g",
Usage: "--group/-g NAMESPACE/SOURCEALIAS",
},
cli.StringFlag{
Name: "key, k",
Usage: "自定义资源名,-k ENVNAME",
},
cli.StringFlag{
Name: "value, v",
Usage: "自定义资源值,-v ENVVALUE",
},
},
},
{
Name: "delete",
Usage: "删除自定义资源。 grctl sources delete -g NAMESPACE/SOURCEALIAS -k ENVNAME",
Action: func(c *cli.Context) error {
return sourcesAction(c, "delete")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "group, g",
Usage: "--group/-g NAMESPACE/SOURCEALIAS",
},
cli.StringFlag{
Name: "key, k",
Usage: "自定义资源名,-k ENVNAME",
},
},
},
{
Name: "get",
Usage: "获取自定义资源。 grctl sources get -g NAMESPACE/SOURCEALIAS -k ENVNAME",
Action: func(c *cli.Context) error {
// func sourcesAction(c *cli.Context, action string) error {
// Common(c)
// switch action {
// case "create", "-c":
// return createSource(c)
// case "update", "-u":
// return updateSource(c)
// case "delete", "-d":
// return deleteSource(c)
// case "get", "-g":
// return getSource(c)
// }
// return fmt.Errorf("Commands wrong, first args must in [create/update/delete/get] or their simplified format")
// }
return sourcesAction(c, "get")
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "group, g",
Usage: "--group/-g NAMESPACE/SOURCEALIAS",
},
cli.StringFlag{
Name: "key, k",
Usage: "自定义资源名,-k ENVNAME",
},
},
},
},
}
return c
}
// func getSourceItems(c *cli.Context, lens int) (string, string, error) {
// fmt.Printf("len is %v\n", len(c.Args()))
// if len(c.Args()) != lens {
// return "", "", fmt.Errorf("Commands nums wrong, need %d args", lens)
// }
// tenantName := c.Args().Get(1)
// sourceAlias := c.Args().Get(2)
// logrus.Debugf("tenant_name %s, source_alias %s", tenantName, sourceAlias)
// return tenantName, sourceAlias, nil
// }
func sourcesAction(c *cli.Context, action string) error {
Common(c)
switch action {
case "create", "-c":
return createSource(c)
case "update", "-u":
return updateSource(c)
case "delete", "-d":
return deleteSource(c)
case "get", "-g":
return getSource(c)
}
return fmt.Errorf("Commands wrong, first args must in [create/update/delete/get] or their simplified format")
}
// func createSource(c *cli.Context) error {
// tenantName, sourceAlias, err := checkoutGroup(c)
// if err != nil {
// return err
// }
// envName, err := checkoutKV(c, "key")
// if err != nil {
// return err
// }
// envVal, err := checkoutKV(c, "value")
// if err != nil {
// return err
// }
// sb := &api_model.SoureBody{
// EnvName: envName,
// EnvVal: envVal,
// }
// ss := &api_model.SourceSpec{
// Alias: sourceAlias,
// CreateTime: time.Now().Format("2006-01-02 15:04:05"),
// Operator: "grctl",
// SourceBody: sb,
// }
// if err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).PostSource(sourceAlias); err != nil {
// return err
// }
// fmt.Printf("create %s success\n", envName)
// return nil
// }
func getSourceItems(c *cli.Context, lens int) (string, string, error) {
fmt.Printf("len is %v\n", len(c.Args()))
if len(c.Args()) != lens {
return "", "", fmt.Errorf("Commands nums wrong, need %d args", lens)
}
tenantName := c.Args().Get(1)
sourceAlias := c.Args().Get(2)
logrus.Debugf("tenant_name %s, source_alias %s", tenantName, sourceAlias)
return tenantName, sourceAlias, nil
}
// func updateSource(c *cli.Context) error {
// tenantName, sourceAlias, err := checkoutGroup(c)
// if err != nil {
// return err
// }
// envName, err := checkoutKV(c, "key")
// if err != nil {
// return err
// }
// envVal, err := checkoutKV(c, "value")
// if err != nil {
// return err
// }
// sb := &api_model.SoureBody{
// EnvName: envName,
// EnvVal: envVal,
// }
// ss := &api_model.SourceSpec{
// Alias: sourceAlias,
// CreateTime: time.Now().Format("2006-01-02 15:04:05"),
// Operator: "grctl",
// SourceBody: sb,
// }
// if err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).PutSource(sourceAlias); err != nil {
// return err
// }
// fmt.Printf("update %s success\n", envName)
// return nil
// }
func createSource(c *cli.Context) error {
tenantName, sourceAlias, err := checkoutGroup(c)
if err != nil {
return err
}
envName, err := checkoutKV(c, "key")
if err != nil {
return err
}
envVal, err := checkoutKV(c, "value")
if err != nil {
return err
}
sb := &api_model.SoureBody{
EnvName: envName,
EnvVal: envVal,
}
ss := &api_model.SourceSpec{
Alias: sourceAlias,
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
Operator: "grctl",
SourceBody: sb,
}
if err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).PostSource(sourceAlias); err != nil {
return err
}
fmt.Printf("create %s success\n", envName)
return nil
}
// func deleteSource(c *cli.Context) error {
// tenantName, sourceAlias, err := checkoutGroup(c)
// if err != nil {
// return err
// }
// envName, err := checkoutKV(c, "key")
// if err != nil {
// return err
// }
// sb := &api_model.SoureBody{
// EnvName: envName,
// }
// ss := &api_model.SourceSpec{
// Alias: sourceAlias,
// CreateTime: time.Now().Format("2006-01-02 15:04:05"),
// Operator: "grctl",
// SourceBody: sb,
// }
// if err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).DeleteSource(sourceAlias); err != nil {
// return err
// }
// fmt.Printf("delete %s success\n", envName)
// return nil
// }
func updateSource(c *cli.Context) error {
tenantName, sourceAlias, err := checkoutGroup(c)
if err != nil {
return err
}
envName, err := checkoutKV(c, "key")
if err != nil {
return err
}
envVal, err := checkoutKV(c, "value")
if err != nil {
return err
}
sb := &api_model.SoureBody{
EnvName: envName,
EnvVal: envVal,
}
ss := &api_model.SourceSpec{
Alias: sourceAlias,
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
Operator: "grctl",
SourceBody: sb,
}
if err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).PutSource(sourceAlias); err != nil {
return err
}
fmt.Printf("update %s success\n", envName)
return nil
}
// func getSource(c *cli.Context) error {
// tenantName, sourceAlias, err := checkoutGroup(c)
// if err != nil {
// return err
// }
// envName, err := checkoutKV(c, "key")
// if err != nil {
// return err
// }
// sb := &api_model.SoureBody{
// EnvName: envName,
// }
// ss := &api_model.SourceSpec{
// Alias: sourceAlias,
// CreateTime: time.Now().Format("2006-01-02 15:04:05"),
// Operator: "grctl",
// SourceBody: sb,
// }
// resp, err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).GetSource(sourceAlias)
// if err != nil {
// return err
// }
// fmt.Printf("resp is %v", string(resp))
// return nil
// }
func deleteSource(c *cli.Context) error {
tenantName, sourceAlias, err := checkoutGroup(c)
if err != nil {
return err
}
envName, err := checkoutKV(c, "key")
if err != nil {
return err
}
sb := &api_model.SoureBody{
EnvName: envName,
}
ss := &api_model.SourceSpec{
Alias: sourceAlias,
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
Operator: "grctl",
SourceBody: sb,
}
if err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).DeleteSource(sourceAlias); err != nil {
return err
}
fmt.Printf("delete %s success\n", envName)
return nil
}
// func checkoutGroup(c *cli.Context) (string, string, error) {
// group := c.String("group")
// if group == "" {
// logrus.Errorf("Incorrect Usage: flag provided but not defined: -group")
// return "", "", fmt.Errorf("have no group set, -g TENANTID/SOURCEALIAS")
// }
// if strings.Contains(group, "/") {
// mm := strings.Split(group, "/")
// tenantName, sourceAlias := mm[0], mm[1]
// return tenantName, sourceAlias, nil
// }
// logrus.Errorf("format Error, group format must in: -g TENANTID/SOURCEALIAS ")
// return "", "", fmt.Errorf("group format wrong")
// }
func getSource(c *cli.Context) error {
tenantName, sourceAlias, err := checkoutGroup(c)
if err != nil {
return err
}
envName, err := checkoutKV(c, "key")
if err != nil {
return err
}
sb := &api_model.SoureBody{
EnvName: envName,
}
ss := &api_model.SourceSpec{
Alias: sourceAlias,
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
Operator: "grctl",
SourceBody: sb,
}
resp, err := clients.RegionClient.Tenants().Get(tenantName).DefineSources(ss).GetSource(sourceAlias)
if err != nil {
return err
}
fmt.Printf("resp is %v", string(resp))
return nil
}
func checkoutGroup(c *cli.Context) (string, string, error) {
group := c.String("group")
if group == "" {
logrus.Errorf("Incorrect Usage: flag provided but not defined: -group")
return "", "", fmt.Errorf("have no group set, -g TENANTID/SOURCEALIAS")
}
if strings.Contains(group, "/") {
mm := strings.Split(group, "/")
tenantName, sourceAlias := mm[0], mm[1]
return tenantName, sourceAlias, nil
}
logrus.Errorf("format Error, group format must in: -g TENANTID/SOURCEALIAS ")
return "", "", fmt.Errorf("group format wrong")
}
func checkoutKV(c *cli.Context, kind string) (string, error) {
value := c.String(kind)
if value == "" {
logrus.Errorf("need %s, --%s ARGV", kind, kind)
return "", fmt.Errorf("have no %s", kind)
}
return value, nil
}
// func checkoutKV(c *cli.Context, kind string) (string, error) {
// value := c.String(kind)
// if value == "" {
// logrus.Errorf("need %s, --%s ARGV", kind, kind)
// return "", fmt.Errorf("have no %s", kind)
// }
// return value, nil
// }

View File

@ -80,7 +80,7 @@ func getTenantInfo(c *cli.Context) error {
fmt.Println("Please provide tenant name")
os.Exit(1)
}
services, err := clients.RegionClient.Tenants().Get(tenantID).Services().List()
services, err := clients.RegionClient.Tenants(tenantID).Services("").List()
handleErr(err)
if services != nil {
runtable := termtables.CreateTable()
@ -117,7 +117,7 @@ func findTenantResourceUsage(c *cli.Context) error {
table.AddRow("企业ID", resources.EID)
table.AddRow("正使用CPU资源", fmt.Sprintf("%.2f Core", float64(resources.UsedCPU)/1000))
table.AddRow("正使用内存资源:", fmt.Sprintf("%d %s", resources.UsedMEM, "Mb"))
table.AddRow("正使用磁盘资源:", fmt.Sprintf("%.2f Mb", resources.UsedDisk/1024/1024))
table.AddRow("正使用磁盘资源:", fmt.Sprintf("%.2f Mb", resources.UsedDisk/1024))
table.AddRow("总分配CPU资源", fmt.Sprintf("%.2f Core", float64(resources.AllocatedCPU)/1000))
table.AddRow("总分配内存资源:", fmt.Sprintf("%d %s", resources.AllocatedMEM, "Mb"))
fmt.Println(table)