diff --git a/api/desc/core/pcm-core.api b/api/desc/core/pcm-core.api index e5334e24..8104cae7 100644 --- a/api/desc/core/pcm-core.api +++ b/api/desc/core/pcm-core.api @@ -78,6 +78,8 @@ type commitTaskReq { Replicas int64 `json:"replicas,optional"` MatchLabels map[string]string `json:"matchLabels,optional"` YamlList []string `json:"yamlList"` + ClusterName string `json:"clusterName"` + } type ( @@ -101,7 +103,11 @@ type ( type ( commitVmTaskReq { - server ServerCommit `json:"server,optional"` + Name string `json:"name"` + NsID string `json:"nsID"` + Replicas int64 `json:"replicas,optional"` + MatchLabels map[string]string `json:"matchLabels,optional"` + server []ServerCommit `json:"server,optional"` platform string `json:"platform,optional"` } ServerCommit { @@ -128,7 +134,19 @@ type ( uuid string `json:"uuid,optional"` } commitVmTaskResp { + Id string `json:"id" copier:"Id"` + Links []VmLinks `json:"links" copier:"Links"` + OSDCFDiskConfig string `json:"OS_DCF_diskConfig" copier:"OSDCFDiskConfig"` + SecurityGroups []VmSecurity_groups_server `json:"security_groups" copier:"SecurityGroups"` + AdminPass string `json:"adminPass" copier:"AdminPass"` + } + VmLinks { + Href string `json:"href " copier:"Href"` + Rel string `json:"rel" copier:"Rel"` + } + VmSecurity_groups_server { + Name string `json:"name" copier:"Name"` } ) diff --git a/api/desc/pcm.api b/api/desc/pcm.api index 72d06db0..41f9ecee 100644 --- a/api/desc/pcm.api +++ b/api/desc/pcm.api @@ -362,6 +362,14 @@ service pcm { @handler GetVolumeLimitsHandler get /vm/getVolumeLimits (GetVolumeLimitsReq) returns (GetVolumeLimitsResp) + @doc "查询网络数量" + @handler GetNetworkNumHandler + get /vm/getNetworkNum (ListNetworksReq) returns (NetworkNum) + + @doc "查询镜像列表" + @handler getImageNumHandler + get /vm/getImageNum (ListImagesReq) returns (ImageNum) + @doc "查询虚拟机列表" @handler ListServerHandler get /vm/listServer (ListServersReq) returns (ListServersResp) diff --git a/api/desc/vm/pcm-vm.api b/api/desc/vm/pcm-vm.api index ea709651..e51ebf21 100644 --- a/api/desc/vm/pcm-vm.api +++ b/api/desc/vm/pcm-vm.api @@ -339,13 +339,6 @@ type ( CreNetwork { Uuid string `json:"uuid" copier:"Uuid"` } - ServerResp { - Id string `json:"id" copier:"Id"` - Links []Links `json:"links" copier:"Links"` - OSDCFDiskConfig string `json:"OS_DCF_diskConfig" copier:"OSDCFDiskConfig"` - SecurityGroups []Security_groups_server `json:"security_groups" copier:"SecurityGroups"` - AdminPass string `json:"adminPass" copier:"AdminPass"` - } Security_groups_server { Name string `json:"name" copier:"Name"` } @@ -356,6 +349,13 @@ type ( DestinationType string `json:"destination_type" copier:"DestinationType"` DeleteOnTermination bool `json:"delete_on_termination" copier:"DeleteOnTermination"` } + ServerResp { + Id string `json:"id" copier:"Id"` + Links []Links `json:"links" copier:"Links"` + OSDCFDiskConfig string `json:"OS_DCF_diskConfig" copier:"OSDCFDiskConfig"` + SecurityGroups []Security_groups_server `json:"security_groups" copier:"SecurityGroups"` + AdminPass string `json:"adminPass" copier:"AdminPass"` + } ) type( @@ -674,6 +674,25 @@ type ( /******************find images end*************************/ /******************find Networks end*************************/ +type ( + + NetworkNum { + NetworkNum int32 `json:"networkNum"` + Code int32 `json:"code,omitempty"` + Msg string `json:"msg,omitempty"` + ErrorMsg string `json:"errorMsg,omitempty"` + } +) + +type ( + ImageNum { + ImageNum int32 `json:"imageNum"` + Code int32 `json:"code,omitempty"` + Msg string `json:"msg,omitempty"` + ErrorMsg string `json:"errorMsg,omitempty"` + } +) + type ( ListNetworksReq { Platform string `json:"platform,optional"` diff --git a/api/etc/pcm.yaml b/api/etc/pcm.yaml index 41c9c2e8..11432c95 100644 --- a/api/etc/pcm.yaml +++ b/api/etc/pcm.yaml @@ -67,12 +67,9 @@ OctopusRpcConf: Timeout: 20000 OpenstackRpcConf: - # target: nacos://10.206.0.12:8848/pcm.openstack.rpc?timeout=30s&namespaceid=test&groupname=DEFAULT_GROUP&appName=pcm.core.api - # target: nacos://127.0.0.1:8848/pcm.openstack.rpc?timeout=30s&namespaceid=test&groupname=DEFAULT_GROUP&appName=pcm.core.api - #Endpoints: - #- 127.0.0.1:2010 + # target: nacos://10.206.0.12:8848/pcm.openstack.rpc?timeout=30s&namespaceid=test&groupname=DEFAULT_GROUP&appName=pcm.core.api Endpoints: - - 127.0.0.1:2010 + - 127.0.0.1:2010 NonBlock: true Timeout: 20000 diff --git a/api/internal/handler/routes.go b/api/internal/handler/routes.go index f01f8ea0..e8c4b9a9 100644 --- a/api/internal/handler/routes.go +++ b/api/internal/handler/routes.go @@ -435,6 +435,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/vm/getVolumeLimits", Handler: vm.GetVolumeLimitsHandler(serverCtx), }, + { + Method: http.MethodGet, + Path: "/vm/getNetworkNum", + Handler: vm.GetNetworkNumHandler(serverCtx), + }, + { + Method: http.MethodGet, + Path: "/vm/getImageNum", + Handler: vm.GetImageNumHandler(serverCtx), + }, { Method: http.MethodGet, Path: "/vm/listServer", diff --git a/api/internal/handler/vm/getimagenumhandler.go b/api/internal/handler/vm/getimagenumhandler.go new file mode 100644 index 00000000..ecaf4ea1 --- /dev/null +++ b/api/internal/handler/vm/getimagenumhandler.go @@ -0,0 +1,28 @@ +package vm + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/logic/vm" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types" +) + +func GetImageNumHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.ListImagesReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := vm.NewGetImageNumLogic(r.Context(), svcCtx) + resp, err := l.GetImageNum(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/api/internal/handler/vm/getnetworknumhandler.go b/api/internal/handler/vm/getnetworknumhandler.go new file mode 100644 index 00000000..d1115cdf --- /dev/null +++ b/api/internal/handler/vm/getnetworknumhandler.go @@ -0,0 +1,28 @@ +package vm + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/logic/vm" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types" +) + +func GetNetworkNumHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.ListNetworksReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := vm.NewGetNetworkNumLogic(r.Context(), svcCtx) + resp, err := l.GetNetworkNum(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/api/internal/logic/core/commitvmtasklogic.go b/api/internal/logic/core/commitvmtasklogic.go index 782b0af3..5d803bf2 100644 --- a/api/internal/logic/core/commitvmtasklogic.go +++ b/api/internal/logic/core/commitvmtasklogic.go @@ -2,9 +2,13 @@ package core import ( "context" - + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/mqs" "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc" "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/pkg/response" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models" + "time" "github.com/zeromicro/go-zero/core/logx" ) @@ -25,6 +29,26 @@ func NewCommitVmTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Comm func (l *CommitVmTaskLogic) CommitVmTask(req *types.CommitVmTaskReq) (resp *types.CommitVmTaskResp, err error) { // todo: add your logic here and delete this line - + //Building the main task structure + taskModel := models.Task{ + Status: constants.Saved, + Name: req.Name, + CommitTime: time.Now(), + NsID: req.NsID, + } + // Save task data to database + tx := l.svcCtx.DbEngin.Create(&taskModel) + if tx.Error != nil { + return nil, tx.Error + } + /* hpc := models.Hpc{} + tool.Convert(req, &hpc)*/ + mqInfo := response.TaskInfo{ + TaskId: taskModel.Id, + TaskType: "vm", + MatchLabels: req.MatchLabels, + NsID: req.NsID, + } + mqs.InsQueue.Beta.Add(&mqInfo) return } diff --git a/api/internal/logic/vm/getimagenumlogic.go b/api/internal/logic/vm/getimagenumlogic.go new file mode 100644 index 00000000..eac511af --- /dev/null +++ b/api/internal/logic/vm/getimagenumlogic.go @@ -0,0 +1,49 @@ +package vm + +import ( + "context" + "fmt" + "github.com/jinzhu/copier" + "github.com/pkg/errors" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/helper/xerr" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/repository/result" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils" + "gitlink.org.cn/JointCloud/pcm-openstack/openstack" + + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetImageNumLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewGetImageNumLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetImageNumLogic { + return &GetImageNumLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetImageNumLogic) GetImageNum(req *types.ListImagesReq) (resp *types.ImageNum, err error) { + // todo: add your logic here and delete this line + resp = &types.ImageNum{} + ListImagesReq := &openstack.ListImagesReq{} + err = copier.CopyWithOption(ListImagesReq, req, copier.Option{Converters: utils.Converters}) + ListImagesResp, err := l.svcCtx.OpenstackRpc.ListImages(l.ctx, ListImagesReq) + if err != nil { + return nil, errors.Wrapf(xerr.NewErrMsg("Failed to get Networks list"), "Failed to get db Servers list err : %v ,req:%+v", err, req) + } + var count int = len(ListImagesResp.Images) + resp.ImageNum = int32(count) + fmt.Println(count) + if err != nil { + return nil, result.NewDefaultError(err.Error()) + } + return resp, err +} diff --git a/api/internal/logic/vm/getnetworknumlogic.go b/api/internal/logic/vm/getnetworknumlogic.go new file mode 100644 index 00000000..65084eba --- /dev/null +++ b/api/internal/logic/vm/getnetworknumlogic.go @@ -0,0 +1,49 @@ +package vm + +import ( + "context" + "fmt" + "github.com/jinzhu/copier" + "github.com/pkg/errors" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/helper/xerr" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/repository/result" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils" + "gitlink.org.cn/JointCloud/pcm-openstack/openstack" + + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetNetworkNumLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewGetNetworkNumLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNetworkNumLogic { + return &GetNetworkNumLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetNetworkNumLogic) GetNetworkNum(req *types.ListNetworksReq) (resp *types.NetworkNum, err error) { + // todo: add your logic here and delete this line + resp = &types.NetworkNum{} + ListNetworksReq := &openstack.ListNetworksReq{} + err = copier.CopyWithOption(ListNetworksReq, req, copier.Option{Converters: utils.Converters}) + ListNetworksResp, err := l.svcCtx.OpenstackRpc.ListNetworks(l.ctx, ListNetworksReq) + if err != nil { + return nil, errors.Wrapf(xerr.NewErrMsg("Failed to get Networks list"), "Failed to get db Servers list err : %v ,req:%+v", err, req) + } + var count int = len(ListNetworksResp.Networks) + resp.NetworkNum = int32(count) + fmt.Println(count) + if err != nil { + return nil, result.NewDefaultError(err.Error()) + } + return resp, err +} diff --git a/api/internal/logic/vm/listnetworkslogic.go b/api/internal/logic/vm/listnetworkslogic.go index 19b8af42..2433324d 100644 --- a/api/internal/logic/vm/listnetworkslogic.go +++ b/api/internal/logic/vm/listnetworkslogic.go @@ -49,7 +49,7 @@ func (l *ListNetworksLogic) ListNetworks(req *types.ListNetworksReq) (resp *type err = copier.CopyWithOption(ListNetworksReq, req, copier.Option{Converters: utils.Converters}) ListNetworksResp, err := l.svcCtx.OpenstackRpc.ListNetworks(l.ctx, ListNetworksReq) if err != nil { - return nil, errors.Wrapf(xerr.NewErrMsg("Failed to get Servers list"), "Failed to get db Servers list err : %v ,req:%+v", err, req) + return nil, errors.Wrapf(xerr.NewErrMsg("Failed to get Networks list"), "Failed to get db Servers list err : %v ,req:%+v", err, req) } marshal, err := json.Marshal(&ListNetworksResp) if err != nil { diff --git a/api/internal/mqs/ScheduleVm.go b/api/internal/mqs/ScheduleVm.go new file mode 100644 index 00000000..9cf4c203 --- /dev/null +++ b/api/internal/mqs/ScheduleVm.go @@ -0,0 +1,51 @@ +package mqs + +import ( + "context" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/schedulers" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc" +) + +/* +* + */ +type VmMq struct { + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewVmMq(ctx context.Context, svcCtx *svc.ServiceContext) *VmMq { + return &VmMq{ + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *VmMq) Consume(val string) error { + // 接受消息, 根据标签筛选过滤 + vmScheduler := schedulers.NewVmScheduler() + schdl, err := scheduler.NewScheduler(vmScheduler, val, l.svcCtx.DbEngin, l.svcCtx.ParticipantRpc) + if err != nil { + return err + } + + //检测是否指定了集群列表 + schdl.SpecifyClusters() + + //检测是否指定了nsID + schdl.SpecifyNsID() + + //通过标签匹配筛选出集群范围 + schdl.MatchLabels() + + //todo 屏蔽原调度算法,因为监控数据暂未上报,临时采用随机调度 + schdl.TempAssign() + + // 存储数据 + err = schdl.SaveToDb() + if err != nil { + return err + } + return nil +} diff --git a/api/internal/scheduler/schedulers/vmScheduler.go b/api/internal/scheduler/schedulers/vmScheduler.go index 54b249e4..d2a3bb91 100644 --- a/api/internal/scheduler/schedulers/vmScheduler.go +++ b/api/internal/scheduler/schedulers/vmScheduler.go @@ -1,21 +1,67 @@ package schedulers import ( + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/algorithm/providerPricing" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/database" "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/strategy" + "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/strategy/param" "gitlink.org.cn/JointCloud/pcm-coordinator/api/pkg/response" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils" ) type VmScheduler struct { + storage database.Storage } -func (v VmScheduler) GetNewStructForDb(task *response.TaskInfo, resource string, participantId int64) (interface{}, error) { - //TODO implement me - panic("implement me") +func NewVmScheduler() *VmScheduler { + return &VmScheduler{} } -func (v VmScheduler) PickOptimalStrategy() (strategy.Strategy, error) { +func (vm *VmScheduler) PickOptimalStrategy() (strategy.Strategy, error) { + //获取所有计算中心 + //调度算法 + strategy := strategy.NewPricingStrategy(¶m.ResourcePricingParams{}) + return strategy, nil +} + +func (v *VmScheduler) GetNewStructForDb(task *response.TaskInfo, resource string, participantId int64) (interface{}, error) { //TODO implement me - panic("implement me") + vm := models.Vm{} + utils.Convert(task.Metadata, &vm) + vm.Id = utils.GenSnowflakeID() + vm.TaskId = vm.TaskId + vm.Status = constants.Saved + vm.ParticipantId = participantId + return vm, nil + //vm.YamlString =v.yamlString + /* vm. = utils.GenSnowflakeID() + vm.NsID = task.NsID + vm.ParticipantId = participantId*/ +} + +/* + func (vm *VmScheduler) UnMarshalVmStruct(yamlString string, taskId int64, nsID string) models.vm { + var vm models.Vm + vm := kyaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(yamlString), 4096) + } +*/ +func (vm *VmScheduler) genTaskAndProviders() (*providerPricing.Task, []*providerPricing.Provider, error) { + proParams, err := vm.storage.GetProviderParams() + if err != nil { + return nil, nil, nil + } + var providerList []*providerPricing.Provider + for _, p := range proParams { + provider := providerPricing.NewProvider(p.Participant_id, p.Cpu_avail, p.Mem_avail, p.Disk_avail, 0.0, 0.0, 0.0) + providerList = append(providerList, provider) + } + + //replicas := task.Metadata.(map[string]interface{})["spec"].(map[string]interface{})["replicas"].(float64) + //t := algorithm.NewTask(0, int(replicas), 2, 75120000, 301214500, 1200, 2, 6, 2000) + + return nil, providerList, nil } func (v VmScheduler) AssignTask(clusters []*strategy.AssignedCluster) error { diff --git a/api/internal/types/types.go b/api/internal/types/types.go index 868f3109..da62e19a 100644 --- a/api/internal/types/types.go +++ b/api/internal/types/types.go @@ -67,6 +67,7 @@ type CommitTaskReq struct { Replicas int64 `json:"replicas,optional"` MatchLabels map[string]string `json:"matchLabels,optional"` YamlList []string `json:"yamlList"` + ClusterName string `json:"clusterName"` } type ScheduleTaskByYamlReq struct { @@ -88,8 +89,12 @@ type TaskYaml struct { } type CommitVmTaskReq struct { - Server ServerCommit `json:"server,optional"` - Platform string `json:"platform,optional"` + Name string `json:"name"` + NsID string `json:"nsID"` + Replicas int64 `json:"replicas,optional"` + MatchLabels map[string]string `json:"matchLabels,optional"` + Server ServerCommit `json:"server,optional"` + Platform string `json:"platform,optional"` } type ServerCommit struct { @@ -119,6 +124,20 @@ type Block_device_mapping_v2Commit struct { } type CommitVmTaskResp struct { + Id string `json:"id" copier:"Id"` + Links []VmLinks `json:"links" copier:"Links"` + OSDCFDiskConfig string `json:"OS_DCF_diskConfig" copier:"OSDCFDiskConfig"` + SecurityGroups []VmSecurity_groups_server `json:"security_groups" copier:"SecurityGroups"` + AdminPass string `json:"adminPass" copier:"AdminPass"` +} + +type VmLinks struct { + Href string `json:"href " copier:"Href"` + Rel string `json:"rel" copier:"Rel"` +} + +type VmSecurity_groups_server struct { + Name string `json:"name" copier:"Name"` } type ScheduleTaskByYamlResp struct { @@ -2853,14 +2872,6 @@ type CreNetwork struct { Uuid string `json:"uuid" copier:"Uuid"` } -type ServerResp struct { - Id string `json:"id" copier:"Id"` - Links []Links `json:"links" copier:"Links"` - OSDCFDiskConfig string `json:"OS_DCF_diskConfig" copier:"OSDCFDiskConfig"` - SecurityGroups []Security_groups_server `json:"security_groups" copier:"SecurityGroups"` - AdminPass string `json:"adminPass" copier:"AdminPass"` -} - type Security_groups_server struct { Name string `json:"name" copier:"Name"` } @@ -2873,6 +2884,14 @@ type Block_device_mapping_v2 struct { DeleteOnTermination bool `json:"delete_on_termination" copier:"DeleteOnTermination"` } +type ServerResp struct { + Id string `json:"id" copier:"Id"` + Links []Links `json:"links" copier:"Links"` + OSDCFDiskConfig string `json:"OS_DCF_diskConfig" copier:"OSDCFDiskConfig"` + SecurityGroups []Security_groups_server `json:"security_groups" copier:"SecurityGroups"` + AdminPass string `json:"adminPass" copier:"AdminPass"` +} + type RebuildServerReq struct { ServerId string `json:"server_id" copier:"ServerId"` Platform string `json:"platform,optional"` @@ -3180,6 +3199,20 @@ type DeleteImageResp struct { ErrorMsg string `json:"errorMsg,omitempty"` } +type NetworkNum struct { + NetworkNum int32 `json:"networkNum"` + Code int32 `json:"code,omitempty"` + Msg string `json:"msg,omitempty"` + ErrorMsg string `json:"errorMsg,omitempty"` +} + +type ImageNum struct { + ImageNum int32 `json:"imageNum"` + Code int32 `json:"code,omitempty"` + Msg string `json:"msg,omitempty"` + ErrorMsg string `json:"errorMsg,omitempty"` +} + type ListNetworksReq struct { Platform string `json:"platform,optional"` } diff --git a/pkg/models/vmmodel.go b/pkg/models/vmmodel.go new file mode 100644 index 00000000..0649c427 --- /dev/null +++ b/pkg/models/vmmodel.go @@ -0,0 +1,24 @@ +package models + +import "github.com/zeromicro/go-zero/core/stores/sqlx" + +var _ VmModel = (*customVmModel)(nil) + +type ( + // VmModel is an interface to be customized, add more methods here, + // and implement the added methods in customVmModel. + VmModel interface { + vmModel + } + + customVmModel struct { + *defaultVmModel + } +) + +// NewVmModel returns a model for the database table. +func NewVmModel(conn sqlx.SqlConn) VmModel { + return &customVmModel{ + defaultVmModel: newVmModel(conn), + } +} diff --git a/pkg/models/vmmodel_gen.go b/pkg/models/vmmodel_gen.go new file mode 100644 index 00000000..3fc2beeb --- /dev/null +++ b/pkg/models/vmmodel_gen.go @@ -0,0 +1,101 @@ +// Code generated by goctl. DO NOT EDIT. + +package models + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + vmFieldNames = builder.RawFieldNames(&Vm{}) + vmRows = strings.Join(vmFieldNames, ",") + vmRowsExpectAutoSet = strings.Join(stringx.Remove(vmFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") + vmRowsWithPlaceHolder = strings.Join(stringx.Remove(vmFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" +) + +type ( + vmModel interface { + Insert(ctx context.Context, data *Vm) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*Vm, error) + Update(ctx context.Context, data *Vm) error + Delete(ctx context.Context, id int64) error + } + + defaultVmModel struct { + conn sqlx.SqlConn + table string + } + + Vm struct { + Id int64 `db:"id"` // id + TaskId int64 `db:"task_id"` // 任务id + ParticipantId int64 `db:"participant_id"` // p端id + ApiVersion sql.NullString `db:"api_version"` // api版本 + Name sql.NullString `db:"name"` // 名字 + Namespace sql.NullString `db:"namespace"` // 命名空间 + Kind sql.NullString `db:"kind"` // 种类 + CreatedBy sql.NullInt64 `db:"created_by"` // 创建人 + CreatedTime sql.NullTime `db:"created_time"` // 创建时间 + UpdateBy sql.NullInt64 `db:"update_by"` // 修改人 + UpdateTime sql.NullTime `db:"update_time"` // 修改时间 + Status string `db:"status"` // 状态 + } +) + +func newVmModel(conn sqlx.SqlConn) *defaultVmModel { + return &defaultVmModel{ + conn: conn, + table: "`vm`", + } +} + +func (m *defaultVmModel) withSession(session sqlx.Session) *defaultVmModel { + return &defaultVmModel{ + conn: sqlx.NewSqlConnFromSession(session), + table: "`vm`", + } +} + +func (m *defaultVmModel) Delete(ctx context.Context, id int64) error { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + _, err := m.conn.ExecCtx(ctx, query, id) + return err +} + +func (m *defaultVmModel) FindOne(ctx context.Context, id int64) (*Vm, error) { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", vmRows, m.table) + var resp Vm + err := m.conn.QueryRowCtx(ctx, &resp, query, id) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultVmModel) Insert(ctx context.Context, data *Vm) (sql.Result, error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, vmRowsExpectAutoSet) + ret, err := m.conn.ExecCtx(ctx, query, data.TaskId, data.ParticipantId, data.ApiVersion, data.Name, data.Namespace, data.Kind, data.CreatedBy, data.CreatedTime, data.UpdateBy, data.Status) + return ret, err +} + +func (m *defaultVmModel) Update(ctx context.Context, data *Vm) error { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, vmRowsWithPlaceHolder) + _, err := m.conn.ExecCtx(ctx, query, data.TaskId, data.ParticipantId, data.ApiVersion, data.Name, data.Namespace, data.Kind, data.CreatedBy, data.CreatedTime, data.UpdateBy, data.Status, data.Id) + return err +} + +func (m *defaultVmModel) tableName() string { + return m.table +}