new code structure

This commit is contained in:
450705171@qq.com 2023-02-16 09:19:39 +08:00
parent f04458765e
commit ce5fd117ff
190 changed files with 4611 additions and 54098 deletions

View File

View File

@ -1,17 +0,0 @@
version: v1
plugins:
- name: go
out: gen
opt:
- paths=source_relative
- name: go-grpc
out: gen
opt:
- paths=source_relative
- name: grpc-gateway
out: gen
opt:
- paths=source_relative
- grpc_api_configuration=idl/pod.yaml
- name: openapiv2
out: gen/openapiv2

View File

@ -1,13 +0,0 @@
version: v1
name: buf.build/JCCE/PCM
breaking:
use:
- FILE
lint:
use:
- DEFAULT
# ignore:
# - google/type/datetime.proto
deps:
- buf.build/googleapis/googleapis
- buf.build/grpc-ecosystem/grpc-gateway

File diff suppressed because it is too large Load Diff

View File

@ -1,669 +0,0 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: idl/pod.proto
/*
Package podpb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package podpb
import (
"context"
"io"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// Suppress "imported and not used" errors
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = metadata.Join
func request_PodService_CreatePods_0(ctx context.Context, marshaler runtime.Marshaler, client PodServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreatePodsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CreatePods(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_PodService_CreatePods_0(ctx context.Context, marshaler runtime.Marshaler, server PodServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreatePodsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.CreatePods(ctx, &protoReq)
return msg, metadata, err
}
func request_PodService_CreatePod_0(ctx context.Context, marshaler runtime.Marshaler, client PodServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreatePodReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CreatePod(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_PodService_CreatePod_0(ctx context.Context, marshaler runtime.Marshaler, server PodServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreatePodReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.CreatePod(ctx, &protoReq)
return msg, metadata, err
}
func request_PodService_DeletePod_0(ctx context.Context, marshaler runtime.Marshaler, client PodServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DeletePodReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DeletePod(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_PodService_DeletePod_0(ctx context.Context, marshaler runtime.Marshaler, server PodServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DeletePodReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.DeletePod(ctx, &protoReq)
return msg, metadata, err
}
func request_PodService_UpdatePod_0(ctx context.Context, marshaler runtime.Marshaler, client PodServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq UpdatePodReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.UpdatePod(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_PodService_UpdatePod_0(ctx context.Context, marshaler runtime.Marshaler, server PodServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq UpdatePodReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.UpdatePod(ctx, &protoReq)
return msg, metadata, err
}
var (
filter_PodService_ListPodDetail_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_PodService_ListPodDetail_0(ctx context.Context, marshaler runtime.Marshaler, client PodServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListPodDetailReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_PodService_ListPodDetail_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ListPodDetail(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_PodService_ListPodDetail_0(ctx context.Context, marshaler runtime.Marshaler, server PodServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListPodDetailReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_PodService_ListPodDetail_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ListPodDetail(ctx, &protoReq)
return msg, metadata, err
}
var (
filter_PodService_ListPod_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_PodService_ListPod_0(ctx context.Context, marshaler runtime.Marshaler, client PodServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListPodReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_PodService_ListPod_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ListPod(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_PodService_ListPod_0(ctx context.Context, marshaler runtime.Marshaler, server PodServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListPodReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_PodService_ListPod_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ListPod(ctx, &protoReq)
return msg, metadata, err
}
func request_PodService_ListPodAll_0(ctx context.Context, marshaler runtime.Marshaler, client PodServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListPodAllReq
var metadata runtime.ServerMetadata
msg, err := client.ListPodAll(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_PodService_ListPodAll_0(ctx context.Context, marshaler runtime.Marshaler, server PodServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListPodAllReq
var metadata runtime.ServerMetadata
msg, err := server.ListPodAll(ctx, &protoReq)
return msg, metadata, err
}
// RegisterPodServiceHandlerServer registers the http handlers for service PodService to "mux".
// UnaryRPC :call PodServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterPodServiceHandlerFromEndpoint instead.
func RegisterPodServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server PodServiceServer) error {
mux.Handle("POST", pattern_PodService_CreatePods_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pod.PodService/CreatePods", runtime.WithHTTPPathPattern("/apis/pod/createMulti"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_PodService_CreatePods_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_CreatePods_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_PodService_CreatePod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pod.PodService/CreatePod", runtime.WithHTTPPathPattern("/apis/pod/create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_PodService_CreatePod_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_CreatePod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_PodService_DeletePod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pod.PodService/DeletePod", runtime.WithHTTPPathPattern("/apis/pod/delete"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_PodService_DeletePod_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_DeletePod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PUT", pattern_PodService_UpdatePod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pod.PodService/UpdatePod", runtime.WithHTTPPathPattern("/apis/pod/delete"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_PodService_UpdatePod_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_UpdatePod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_PodService_ListPodDetail_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pod.PodService/ListPodDetail", runtime.WithHTTPPathPattern("/apis/pod/detail"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_PodService_ListPodDetail_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_ListPodDetail_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_PodService_ListPod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pod.PodService/ListPod", runtime.WithHTTPPathPattern("/apis/pod"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_PodService_ListPod_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_ListPod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_PodService_ListPodAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pod.PodService/ListPodAll", runtime.WithHTTPPathPattern("/apis/pod/all"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_PodService_ListPodAll_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_ListPodAll_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterPodServiceHandlerFromEndpoint is same as RegisterPodServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterPodServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterPodServiceHandler(ctx, mux, conn)
}
// RegisterPodServiceHandler registers the http handlers for service PodService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterPodServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterPodServiceHandlerClient(ctx, mux, NewPodServiceClient(conn))
}
// RegisterPodServiceHandlerClient registers the http handlers for service PodService
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "PodServiceClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "PodServiceClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "PodServiceClient" to call the correct interceptors.
func RegisterPodServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client PodServiceClient) error {
mux.Handle("POST", pattern_PodService_CreatePods_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pod.PodService/CreatePods", runtime.WithHTTPPathPattern("/apis/pod/createMulti"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_PodService_CreatePods_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_CreatePods_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_PodService_CreatePod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pod.PodService/CreatePod", runtime.WithHTTPPathPattern("/apis/pod/create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_PodService_CreatePod_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_CreatePod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_PodService_DeletePod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pod.PodService/DeletePod", runtime.WithHTTPPathPattern("/apis/pod/delete"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_PodService_DeletePod_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_DeletePod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PUT", pattern_PodService_UpdatePod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pod.PodService/UpdatePod", runtime.WithHTTPPathPattern("/apis/pod/delete"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_PodService_UpdatePod_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_UpdatePod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_PodService_ListPodDetail_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pod.PodService/ListPodDetail", runtime.WithHTTPPathPattern("/apis/pod/detail"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_PodService_ListPodDetail_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_ListPodDetail_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_PodService_ListPod_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pod.PodService/ListPod", runtime.WithHTTPPathPattern("/apis/pod"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_PodService_ListPod_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_ListPod_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_PodService_ListPodAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pod.PodService/ListPodAll", runtime.WithHTTPPathPattern("/apis/pod/all"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_PodService_ListPodAll_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_PodService_ListPodAll_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_PodService_CreatePods_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "pod", "createMulti"}, ""))
pattern_PodService_CreatePod_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "pod", "create"}, ""))
pattern_PodService_DeletePod_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "pod", "delete"}, ""))
pattern_PodService_UpdatePod_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "pod", "delete"}, ""))
pattern_PodService_ListPodDetail_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "pod", "detail"}, ""))
pattern_PodService_ListPod_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"apis", "pod"}, ""))
pattern_PodService_ListPodAll_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "pod", "all"}, ""))
)
var (
forward_PodService_CreatePods_0 = runtime.ForwardResponseMessage
forward_PodService_CreatePod_0 = runtime.ForwardResponseMessage
forward_PodService_DeletePod_0 = runtime.ForwardResponseMessage
forward_PodService_UpdatePod_0 = runtime.ForwardResponseMessage
forward_PodService_ListPodDetail_0 = runtime.ForwardResponseMessage
forward_PodService_ListPod_0 = runtime.ForwardResponseMessage
forward_PodService_ListPodAll_0 = runtime.ForwardResponseMessage
)

View File

@ -1,335 +0,0 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc (unknown)
// source: idl/pod.proto
package podpb
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// PodServiceClient is the client API for PodService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type PodServiceClient interface {
// 创建Pods
CreatePods(ctx context.Context, in *CreatePodsReq, opts ...grpc.CallOption) (*CreatePodsResp, error)
// 创建Pod
CreatePod(ctx context.Context, in *CreatePodReq, opts ...grpc.CallOption) (*CreatePodResp, error)
// 删除Pod
DeletePod(ctx context.Context, in *DeletePodReq, opts ...grpc.CallOption) (*DeletePodResp, error)
// 更新Pod
UpdatePod(ctx context.Context, in *UpdatePodReq, opts ...grpc.CallOption) (*UpdatePodResp, error)
// 查询Pod明细
ListPodDetail(ctx context.Context, in *ListPodDetailReq, opts ...grpc.CallOption) (*ListPodDetailResp, error)
// 查询Pod全量 - 根据云类型
ListPod(ctx context.Context, in *ListPodReq, opts ...grpc.CallOption) (*ListPodResp, error)
// 查询所有云的Pod
ListPodAll(ctx context.Context, in *ListPodAllReq, opts ...grpc.CallOption) (*ListPodResp, error)
}
type podServiceClient struct {
cc grpc.ClientConnInterface
}
func NewPodServiceClient(cc grpc.ClientConnInterface) PodServiceClient {
return &podServiceClient{cc}
}
func (c *podServiceClient) CreatePods(ctx context.Context, in *CreatePodsReq, opts ...grpc.CallOption) (*CreatePodsResp, error) {
out := new(CreatePodsResp)
err := c.cc.Invoke(ctx, "/pod.PodService/CreatePods", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *podServiceClient) CreatePod(ctx context.Context, in *CreatePodReq, opts ...grpc.CallOption) (*CreatePodResp, error) {
out := new(CreatePodResp)
err := c.cc.Invoke(ctx, "/pod.PodService/CreatePod", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *podServiceClient) DeletePod(ctx context.Context, in *DeletePodReq, opts ...grpc.CallOption) (*DeletePodResp, error) {
out := new(DeletePodResp)
err := c.cc.Invoke(ctx, "/pod.PodService/DeletePod", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *podServiceClient) UpdatePod(ctx context.Context, in *UpdatePodReq, opts ...grpc.CallOption) (*UpdatePodResp, error) {
out := new(UpdatePodResp)
err := c.cc.Invoke(ctx, "/pod.PodService/UpdatePod", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *podServiceClient) ListPodDetail(ctx context.Context, in *ListPodDetailReq, opts ...grpc.CallOption) (*ListPodDetailResp, error) {
out := new(ListPodDetailResp)
err := c.cc.Invoke(ctx, "/pod.PodService/ListPodDetail", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *podServiceClient) ListPod(ctx context.Context, in *ListPodReq, opts ...grpc.CallOption) (*ListPodResp, error) {
out := new(ListPodResp)
err := c.cc.Invoke(ctx, "/pod.PodService/ListPod", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *podServiceClient) ListPodAll(ctx context.Context, in *ListPodAllReq, opts ...grpc.CallOption) (*ListPodResp, error) {
out := new(ListPodResp)
err := c.cc.Invoke(ctx, "/pod.PodService/ListPodAll", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// PodServiceServer is the server API for PodService service.
// All implementations must embed UnimplementedPodServiceServer
// for forward compatibility
type PodServiceServer interface {
// 创建Pods
CreatePods(context.Context, *CreatePodsReq) (*CreatePodsResp, error)
// 创建Pod
CreatePod(context.Context, *CreatePodReq) (*CreatePodResp, error)
// 删除Pod
DeletePod(context.Context, *DeletePodReq) (*DeletePodResp, error)
// 更新Pod
UpdatePod(context.Context, *UpdatePodReq) (*UpdatePodResp, error)
// 查询Pod明细
ListPodDetail(context.Context, *ListPodDetailReq) (*ListPodDetailResp, error)
// 查询Pod全量 - 根据云类型
ListPod(context.Context, *ListPodReq) (*ListPodResp, error)
// 查询所有云的Pod
ListPodAll(context.Context, *ListPodAllReq) (*ListPodResp, error)
mustEmbedUnimplementedPodServiceServer()
}
// UnimplementedPodServiceServer must be embedded to have forward compatible implementations.
type UnimplementedPodServiceServer struct {
}
func (UnimplementedPodServiceServer) CreatePods(context.Context, *CreatePodsReq) (*CreatePodsResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreatePods not implemented")
}
func (UnimplementedPodServiceServer) CreatePod(context.Context, *CreatePodReq) (*CreatePodResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreatePod not implemented")
}
func (UnimplementedPodServiceServer) DeletePod(context.Context, *DeletePodReq) (*DeletePodResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method DeletePod not implemented")
}
func (UnimplementedPodServiceServer) UpdatePod(context.Context, *UpdatePodReq) (*UpdatePodResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method UpdatePod not implemented")
}
func (UnimplementedPodServiceServer) ListPodDetail(context.Context, *ListPodDetailReq) (*ListPodDetailResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListPodDetail not implemented")
}
func (UnimplementedPodServiceServer) ListPod(context.Context, *ListPodReq) (*ListPodResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListPod not implemented")
}
func (UnimplementedPodServiceServer) ListPodAll(context.Context, *ListPodAllReq) (*ListPodResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListPodAll not implemented")
}
func (UnimplementedPodServiceServer) mustEmbedUnimplementedPodServiceServer() {}
// UnsafePodServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to PodServiceServer will
// result in compilation errors.
type UnsafePodServiceServer interface {
mustEmbedUnimplementedPodServiceServer()
}
func RegisterPodServiceServer(s grpc.ServiceRegistrar, srv PodServiceServer) {
s.RegisterService(&PodService_ServiceDesc, srv)
}
func _PodService_CreatePods_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreatePodsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PodServiceServer).CreatePods(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pod.PodService/CreatePods",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PodServiceServer).CreatePods(ctx, req.(*CreatePodsReq))
}
return interceptor(ctx, in, info, handler)
}
func _PodService_CreatePod_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreatePodReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PodServiceServer).CreatePod(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pod.PodService/CreatePod",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PodServiceServer).CreatePod(ctx, req.(*CreatePodReq))
}
return interceptor(ctx, in, info, handler)
}
func _PodService_DeletePod_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeletePodReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PodServiceServer).DeletePod(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pod.PodService/DeletePod",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PodServiceServer).DeletePod(ctx, req.(*DeletePodReq))
}
return interceptor(ctx, in, info, handler)
}
func _PodService_UpdatePod_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdatePodReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PodServiceServer).UpdatePod(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pod.PodService/UpdatePod",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PodServiceServer).UpdatePod(ctx, req.(*UpdatePodReq))
}
return interceptor(ctx, in, info, handler)
}
func _PodService_ListPodDetail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListPodDetailReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PodServiceServer).ListPodDetail(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pod.PodService/ListPodDetail",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PodServiceServer).ListPodDetail(ctx, req.(*ListPodDetailReq))
}
return interceptor(ctx, in, info, handler)
}
func _PodService_ListPod_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListPodReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PodServiceServer).ListPod(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pod.PodService/ListPod",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PodServiceServer).ListPod(ctx, req.(*ListPodReq))
}
return interceptor(ctx, in, info, handler)
}
func _PodService_ListPodAll_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListPodAllReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PodServiceServer).ListPodAll(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pod.PodService/ListPodAll",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PodServiceServer).ListPodAll(ctx, req.(*ListPodAllReq))
}
return interceptor(ctx, in, info, handler)
}
// PodService_ServiceDesc is the grpc.ServiceDesc for PodService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var PodService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "pod.PodService",
HandlerType: (*PodServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "CreatePods",
Handler: _PodService_CreatePods_Handler,
},
{
MethodName: "CreatePod",
Handler: _PodService_CreatePod_Handler,
},
{
MethodName: "DeletePod",
Handler: _PodService_DeletePod_Handler,
},
{
MethodName: "UpdatePod",
Handler: _PodService_UpdatePod_Handler,
},
{
MethodName: "ListPodDetail",
Handler: _PodService_ListPodDetail_Handler,
},
{
MethodName: "ListPod",
Handler: _PodService_ListPod_Handler,
},
{
MethodName: "ListPodAll",
Handler: _PodService_ListPodAll_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "idl/pod.proto",
}

View File

@ -1,316 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "idl/pod.proto",
"version": "version not set"
},
"tags": [
{
"name": "PodService"
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {},
"definitions": {
"podCloudProvider": {
"type": "string",
"enum": [
"ali",
"tencent",
"huawei",
"k8s",
"harvester"
],
"default": "ali",
"description": "- ali: 0 - 阿里云\n - tencent: 1 - 腾讯云\n - huawei: 2 - 华为云\n - k8s: 3 - K8S\n - harvester: 3 - Harvester",
"title": "云提供商"
},
"podCreatePodReq": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/podCloudProvider"
},
"accountName": {
"type": "string",
"title": "账号名称"
},
"podId": {
"type": "string",
"title": "实例id"
},
"podName": {
"type": "string",
"title": "实例名称"
},
"regionId": {
"type": "integer",
"format": "int32",
"title": "地域,数据中心"
},
"containerImage": {
"type": "string",
"title": "镜像"
},
"containerName": {
"type": "string",
"title": "容器名称"
},
"cpuPod": {
"type": "string",
"title": "v cpu数"
},
"memoryPod": {
"type": "string",
"title": "内存MB"
},
"securityGroupId": {
"type": "string",
"title": "安全组ID 对应腾讯 SecurityGroupIds(腾讯必需)"
},
"subnetId": {
"type": "string",
"title": "子网ID 对应腾讯 SubnetId(腾讯必需)"
},
"vpcId": {
"type": "string",
"title": "VPC ID 对应腾讯 VpcId(腾讯必需)"
},
"namespace": {
"type": "string",
"title": "名空间"
},
"requestSource": {
"type": "string",
"title": "请求源,如果是从pcm sdk 过来的则单独生成tenanters实体"
}
}
},
"podCreatePodResp": {
"type": "object",
"properties": {
"finished": {
"type": "boolean",
"title": "查询是否完成,如果为否-false则可以将下面三个分页参数填入到请求中继续查询"
},
"requestId": {
"type": "string",
"title": "请求id出现问题后提供给云厂商排查问题"
},
"podId": {
"type": "string",
"title": "podId"
},
"podName": {
"type": "string",
"title": "podName"
}
}
},
"podCreatePodsResp": {
"type": "object",
"properties": {
"finished": {
"type": "boolean",
"title": "查询是否完成,如果为否-false则可以将下面三个分页参数填入到请求中继续查询"
},
"requestId": {
"type": "array",
"items": {
"type": "string"
},
"title": "请求id出现问题后提供给云厂商排查问题"
}
}
},
"podDeletePodResp": {
"type": "object",
"properties": {
"finished": {
"type": "boolean",
"title": "删除是否完成"
},
"requestId": {
"type": "string",
"title": "请求id出现问题后提供给云厂商排查问题"
},
"podId": {
"type": "string",
"title": "podId"
},
"podName": {
"type": "string",
"title": "podName"
}
}
},
"podListPodDetailResp": {
"type": "object",
"properties": {
"pods": {
"type": "array",
"items": {
"$ref": "#/definitions/podPodInstance"
},
"title": "Pod集合"
},
"finished": {
"type": "boolean",
"title": "查询是否完成,如果为否-false则可以将下面三个分页参数填入到请求中继续查询"
},
"pageNumber": {
"type": "integer",
"format": "int32",
"title": "分页相关参数,页码"
},
"pageSize": {
"type": "integer",
"format": "int32",
"title": "分页相关参数,每页数量"
},
"nextToken": {
"type": "string",
"title": "分页相关参数下一页的token"
},
"requestId": {
"type": "string",
"title": "请求id出现问题后提供给云厂商排查问题"
}
}
},
"podListPodResp": {
"type": "object",
"properties": {
"pods": {
"type": "array",
"items": {
"$ref": "#/definitions/podPodInstance"
},
"title": "pod list"
}
}
},
"podPodInstance": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/podCloudProvider"
},
"accountName": {
"type": "string",
"title": "账号名称"
},
"pcmId": {
"type": "string",
"title": "pcm id"
},
"podId": {
"type": "string",
"title": "实例id"
},
"podName": {
"type": "string",
"title": "实例名称"
},
"regionId": {
"type": "integer",
"format": "int32",
"title": "地域ID"
},
"regionName": {
"type": "string",
"title": "地域Name"
},
"containerImage": {
"type": "string",
"title": "镜像"
},
"containerName": {
"type": "string",
"title": "容器名称"
},
"cpuPod": {
"type": "string",
"title": "vcpu数"
},
"memoryPod": {
"type": "string",
"title": "内存MB"
},
"securityGroupId": {
"type": "string",
"title": "安全组ID 对应腾讯 SecurityGroupIds(腾讯必需)"
},
"subnetId": {
"type": "string",
"title": "子网ID 对应腾讯 SubnetId(腾讯必需)"
},
"vpcId": {
"type": "string",
"title": "VPC ID 对应腾讯 VpcId(腾讯必需)"
},
"namespace": {
"type": "string",
"title": "名空间"
},
"status": {
"type": "string",
"title": "实例状态"
}
}
},
"podUpdatePodResp": {
"type": "object",
"properties": {
"finished": {
"type": "boolean",
"title": "更新是否完成"
},
"requestId": {
"type": "string",
"title": "请求id出现问题后提供给云厂商排查问题"
},
"podId": {
"type": "string",
"title": "podId"
},
"podName": {
"type": "string",
"title": "podName"
}
}
},
"protobufAny": {
"type": "object",
"properties": {
"@type": {
"type": "string"
}
},
"additionalProperties": {}
},
"rpcStatus": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"details": {
"type": "array",
"items": {
"$ref": "#/definitions/protobufAny"
}
}
}
}
}
}

View File

@ -1,282 +0,0 @@
syntax = "proto3";
package pod;
option go_package = "/podpb";
//
enum CloudProvider {
// 0 -
ali = 0;
// 1 -
tencent = 1;
// 2 -
huawei = 2;
// 3 - K8S
k8s = 3;
// 3 - Harvester
harvester = 4;
}
message Region {
//id
int32 id = 1;
//name
string name = 2;
}
message PodInstance {
//
CloudProvider provider = 1;
//
string account_name = 2;
//pcm id
string pcm_id = 3;
// id
string pod_id = 4;
//
string pod_name = 5;
// ID
int32 region_id = 6;
// Name
string region_name = 7;
//
string container_image = 8;
//
string container_name = 9;
// vcpu数
string cpu_pod = 10;
// MB
string memory_pod = 11;
//ID SecurityGroupIds()
string security_group_id = 12;
//ID SubnetId()
string subnet_id = 13;
//VPC ID VpcId()
string vpc_id = 14;
//
string namespace = 15;
//
string status = 16;
}
message CreatePodsReq {
//
repeated CreatePodReq createPodReq = 1;
}
message CreatePodsResp {
// -false
bool finished = 2;
// id
repeated string request_id = 3;
}
message CreatePodReq {
//
CloudProvider provider = 1;
//
string account_name = 2;
// id
string pod_id = 3;
//
string pod_name = 4;
//
int32 region_id = 5;
//
string container_image = 6;
//
string container_name = 7;
// v cpu数
string cpu_pod = 8;
// MB
string memory_pod = 9;
//ID SecurityGroupIds()
string security_group_id = 10;
//ID SubnetId()
string subnet_id = 11;
//VPC ID VpcId()
string vpc_id = 12;
//
string namespace = 13;
//,pcm sdk tenanters实体
string requestSource = 14;
}
message CreatePodResp {
// -false
bool finished = 1;
// id
string request_id = 2;
// podId
string pod_id = 3;
// podName
string pod_name = 4;
}
message DeletePodReq {
//
CloudProvider provider = 1;
//
string account_name = 2;
// pcm id
string pcm_id = 3;
// podId
string pod_id = 4;
// podName
string pod_name = 5;
//namespace
string namespace = 6;
//
int32 region_id = 7;
//,pcm sdk tenanters实体
string requestSource = 8;
}
message DeletePodResp {
//
bool finished = 1;
// id
string request_id = 2;
// podId
string pod_id = 3;
// podName
string pod_name = 4;
}
message UpdatePodReq {
//
CloudProvider provider = 1;
//
string account_name = 2;
// pcm ID
string pcm_id = 3;
// podId
string pod_id = 4;
// podName
string pod_name = 5;
//namespace
string namespace = 6;
//
int32 region_id = 7;
//
string container_image = 8;
//
string container_name = 9;
// v cpu数
string cpu_pod = 10;
// MB
string memory_pod = 11;
//
string restart_policy = 12;
// labels
string labels = 13;
//,pcm sdk tenanters实体
string requestSource = 14;
}
message UpdatePodResp {
//
bool finished = 1;
// id
string request_id = 2;
// podId
string pod_id = 3;
// podName
string pod_name = 4;
}
message ListPodDetailReq {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
// region name
int32 region_name = 4;
// podID
int32 pod_id = 5;
//
int32 page_number = 6;
//
int32 page_size = 7;
// token
string next_token = 8;
// namespace
string namespace = 9;
}
message ListPodDetailResp {
// Pod集合
repeated PodInstance pods = 1;
// -false
bool finished = 2;
//
int32 page_number = 3;
//
int32 page_size = 4;
// token
string next_token = 5;
// id
string request_id = 6;
}
message ListPodReq {
// cloud name
CloudProvider provider = 1;
//
string namespace =2;
//,pcm sdk tenanters实体
string requestSource =3;
}
message ListPodResp {
// pod list
repeated PodInstance pods = 1;
}
message GetPodRegionReq {
// cloud name
CloudProvider provider = 1;
}
message GetPodRegionResp {
// region list
repeated Region regions = 1;
}
message ListPodAllReq{}
// Pod类产品接口
// - ECI
// - TKS
// - CCI
service PodService {
// Pods
rpc CreatePods(CreatePodsReq) returns (CreatePodsResp);
// Pod
rpc CreatePod(CreatePodReq) returns (CreatePodResp);
// Pod
rpc DeletePod(DeletePodReq) returns (DeletePodResp);
// Pod
rpc UpdatePod(UpdatePodReq) returns (UpdatePodResp);
// Pod明细
rpc ListPodDetail(ListPodDetailReq) returns (ListPodDetailResp);
// Pod全量 -
rpc ListPod(ListPodReq) returns (ListPodResp);
// Pod
rpc ListPodAll(ListPodAllReq) returns (ListPodResp);
}

View File

@ -1,23 +0,0 @@
type: google.api.Service
config_version: 3
http:
rules:
- selector: pod.PodService.CreatePods
post: "/apis/pod/createMulti"
body: "*"
- selector: pod.PodService.CreatePod
post: "/apis/pod/create"
body: "*"
- selector: pod.PodService.DeletePod
post: "/apis/pod/delete"
body: "*"
- selector: pod.PodService.UpdatePod
put: "/apis/pod/delete"
body: "*"
- selector: pod.PodService.ListPodDetail
get: "/apis/pod/detail"
- selector: pod.PodService.ListPod
get: "/apis/pod"
- selector: pod.PodService.ListPodAll
get: "/apis/pod/all"

View File

@ -1,58 +0,0 @@
package main
import (
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
podserver "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/config"
"code.gitlink.org.cn/JCCE/PCM.git/common/global"
"code.gitlink.org.cn/JCCE/PCM.git/common/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"flag"
"github.com/golang/glog"
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/grpc"
"log"
)
func main() {
var configFile string
flag.StringVar(&configFile, "conf", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
// 初始化配置以及数据库
config.InitConfig()
// 新建一个zap logger实例
logger, err := zap.NewDevelopment()
if err != nil {
log.Fatalf("cannot create logger: %v", err)
}
if err != nil {
logger.Fatal("cannot open private key", zap.Error(err))
}
if err != nil {
logger.Fatal("cannot read private key", zap.Error(err))
}
if err != nil {
logger.Fatal("cannot parse private key", zap.Error(err))
}
// logger.Sugar().Fatal 直接可以少几行判错的代码
logger.Sugar().Fatal(server.RunGRPCServer(&server.GRPCConfig{
Name: "pcm_pod",
Addr: global.S.PodInfo.Address,
RegisterFunc: func(g *grpc.Server) {
podpb.RegisterPodServiceServer(g, &podserver.Server{})
},
Logger: logger,
}))
}

View File

@ -1,110 +0,0 @@
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package ali
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
)
// Client is the sdk client struct, each func corresponds to an OpenAPI
type Client struct {
sdk.Client
}
//type AliEci struct {
// cli *alieci.Client
// region tenanter.Region
// tenanter tenanter.Tenanter
//}
// NewClient creates a sdk client with environment variables
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
return
}
// NewClientWithProvider creates a sdk client with providers
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
client = &Client{}
var pc provider.Provider
if len(providers) == 0 {
pc = provider.DefaultChain
} else {
pc = provider.NewProviderChain(providers)
}
err = client.InitWithProviderChain(regionId, pc)
return
}
// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential
// this is the common api to create a sdk client
func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) {
client = &Client{}
err = client.InitWithOptions(regionId, config, credential)
return
}
// NewClientWithAccessKey is a shortcut to create sdk client with accesskey
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
return
}
// NewClientWithStsToken is a shortcut to create sdk client with sts token
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn and policy
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
return
}
// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
return
}
// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
return
}

View File

@ -1,373 +0,0 @@
package ali
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
pbtenant "code.gitlink.org.cn/JCCE/PCM.git/tenant/gen/idl"
"errors"
"flag"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/golang/glog"
"strconv"
)
// CreateContainerGroup invokes the eci.CreateContainerGroup API synchronously
// api document: https://help.aliyun.com/api/eci/createcontainergroup.html
func CreateContainerGroup(request *CreateContainerGroupRequest) (response *CreateContainerGroupResponse, err error) {
provider := pbpod.CloudProvider(request.ProviderId)
var configFile string
flag.StringVar(&configFile, "confAli", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(provider))
var regionId int32
var cpuPod string
var memoryPod string
container := *request.Container
containerImage := container[0].Image
containerName := container[0].Name
cpuPodFloat, _ := container[0].Cpu.GetValue()
memoryPodFloat, _ := container[0].Memory.GetValue()
switch request.ProviderId {
case 0:
regionId, _ = tenanter.GetAliRegionId(request.RegionId)
cpuPod = strconv.FormatFloat(cpuPodFloat, 'f', 0, 64)
memoryPod = strconv.FormatFloat(memoryPodFloat, 'f', 0, 64)
case 1:
regionId, _ = tenanter.GetTencentRegionId(request.RegionId)
cpuPod = strconv.FormatFloat(cpuPodFloat, 'f', 0, 64)
memoryPod = strconv.FormatFloat(memoryPodFloat, 'f', 0, 64)
case 2:
//华为的CPU和内存数量要进行转换
regionId, _ = tenanter.GetHuaweiRegionId(request.RegionId)
cpuPod = strconv.FormatFloat(cpuPodFloat*1000, 'f', 0, 64) + "m"
memoryPod = strconv.FormatFloat(memoryPodFloat, 'f', 0, 64) + "Gi"
case 3:
regionId, _ = tenanter.GetK8SRegionId(request.RegionId)
cpuPod = strconv.FormatFloat(cpuPodFloat*1000, 'f', 0, 64) + "m"
memoryPod = strconv.FormatFloat(memoryPodFloat, 'f', 0, 64) + "Gi"
}
requestPCM := &pbpod.CreatePodReq{
RequestSource: "ali",
Provider: pbpod.CloudProvider(provider),
AccountName: tenanters[0].AccountName(),
PodName: request.ContainerGroupName,
RegionId: regionId,
ContainerImage: containerImage,
ContainerName: containerName,
CpuPod: cpuPod,
MemoryPod: memoryPod,
SecurityGroupId: "sg-6qlun7hd",
SubnetId: "subnet-mnwfg2fk",
VpcId: "vpc-rkwt40g5",
Namespace: "pcm",
}
resp, err := server.CreatePod(nil, requestPCM)
response = &CreateContainerGroupResponse{
BaseResponse: nil,
RequestId: resp.RequestId,
ContainerGroupId: resp.PodId,
}
return response, nil
}
// CreateContainerGroupRequest is the request struct for api CreateContainerGroup
type CreateContainerGroupRequest struct {
*requests.RpcRequest
/*********PCM param************/
RequestSource string `position:"Query" name:"RequestSource"`
ProviderId int32 `position:"Query" name:"ProviderId"`
AccountName string `position:"Query" name:"AccountName"`
Namespace string `position:"Query" name:"Namespace"`
/*********PCM param************/
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
RegionId string `position:"Query" name:"RegionId"`
ZoneId string `position:"Query" name:"ZoneId"`
SecurityGroupId string `position:"Query" name:"SecurityGroupId"`
VSwitchId string `position:"Query" name:"VSwitchId"`
ContainerGroupName string `position:"Query" name:"ContainerGroupName"`
RestartPolicy string `position:"Query" name:"RestartPolicy"`
Tag *[]CreateContainerGroupTag `position:"Query" name:"Tag" type:"Repeated"`
ImageRegistryCredential *[]CreateContainerGroupImageRegistryCredential `position:"Query" name:"ImageRegistryCredential" type:"Repeated"`
Container *[]CreateContainerGroupContainer `position:"Query" name:"Container" type:"Repeated"`
Volume *[]CreateContainerGroupVolume `position:"Query" name:"Volume" type:"Repeated"`
EipInstanceId string `position:"Query" name:"EipInstanceId"`
InitContainer *[]CreateContainerGroupInitContainer `position:"Query" name:"InitContainer" type:"Repeated"`
Cpu requests.Float `position:"Query" name:"Cpu"`
Memory requests.Float `position:"Query" name:"Memory"`
ResourceGroupId string `position:"Query" name:"ResourceGroupId"`
DnsPolicy string `position:"Query" name:"DnsPolicy"`
ClientToken string `position:"Query" name:"ClientToken"`
HostAliase *[]CreateContainerGroupHostAliase `position:"Query" name:"HostAliase" type:"Repeated"`
Arn *[]CreateContainerGroupArn `position:"Query" name:"Arn" type:"Repeated"`
InstanceType string `position:"Query" name:"InstanceType"`
SlsEnable requests.Boolean `position:"Query" name:"SlsEnable"`
ImageSnapshotId string `position:"Query" name:"ImageSnapshotId"`
RamRoleName string `position:"Query" name:"RamRoleName"`
NtpServer []string `position:"Query" name:"NtpServer" type:"Repeated"`
TerminationGracePeriodSeconds requests.Integer `position:"Query" name:"TerminationGracePeriodSeconds"`
AutoMatchImageCache requests.Boolean `position:"Query" name:"AutoMatchImageCache"`
VkClientVersion string `position:"Query" name:"VkClientVersion"`
Ipv6AddressCount requests.Integer `position:"Query" name:"Ipv6AddressCount"`
ActiveDeadlineSeconds requests.Integer `position:"Query" name:"ActiveDeadlineSeconds"`
SpotStrategy string `position:"Query" name:"SpotStrategy"`
SpotPriceLimit requests.Float `position:"Query" name:"SpotPriceLimit"`
VSwitchStrategy string `position:"Query" name:"VSwitchStrategy"`
DnsConfig CreateContainerGroupDnsConfig `position:"Query" name:"DnsConfig" type:"Struct"`
SecurityContext CreateContainerGroupSecurityContext `position:"Query" name:"SecurityContext" type:"Struct"`
}
type CreateContainerGroupTag struct {
Key string `name:"Key"`
Value string `name:"Value"`
}
type CreateContainerGroupImageRegistryCredential struct {
Server string `name:"Server"`
UserName string `name:"UserName"`
Password string `name:"Password"`
}
type CreateContainerGroupContainer struct {
Image string `name:"Image"`
Name string `name:"Name"`
Cpu requests.Float `name:"Cpu"`
Memory requests.Float `name:"Memory"`
WorkingDir string `name:"WorkingDir"`
ImagePullPolicy string `name:"ImagePullPolicy"`
Command []string `name:"Command" type:"Repeated"`
Arg []string `name:"Arg" type:"Repeated"`
VolumeMount *[]CreateContainerGroupVolumeMount `name:"VolumeMount" type:"Repeated"`
Port *[]CreateContainerGroupPort `name:"Port" type:"Repeated"`
EnvironmentVar *[]CreateContainerGroupEnvironmentVar `name:"EnvironmentVar" type:"Repeated"`
Stdin requests.Boolean `name:"Stdin"`
StdinOnce requests.Boolean `name:"StdinOnce"`
Tty requests.Boolean `name:"Tty"`
Gpu requests.Integer `name:"Gpu"`
LifecyclePostStartHandlerHttpGetHost string `name:"LifecyclePostStartHandlerHttpGetHost"`
LifecyclePostStartHandlerHttpGetPort requests.Integer `name:"LifecyclePostStartHandlerHttpGetPort"`
LifecyclePostStartHandlerHttpGetPath string `name:"LifecyclePostStartHandlerHttpGetPath"`
LifecyclePostStartHandlerHttpGetScheme string `name:"LifecyclePostStartHandlerHttpGetScheme"`
LifecyclePostStartHandlerHttpGetHttpHeader *[]CreateContainerGroupLifecyclePostStartHandlerHttpGetHttpHeader `name:"LifecyclePostStartHandlerHttpGetHttpHeader" type:"Repeated"`
LifecyclePostStartHandlerExec []string `name:"LifecyclePostStartHandlerExec" type:"Repeated"`
LifecyclePostStartHandlerTcpSocketHost string `name:"LifecyclePostStartHandlerTcpSocketHost"`
LifecyclePostStartHandlerTcpSocketPort requests.Integer `name:"LifecyclePostStartHandlerTcpSocketPort"`
LifecyclePreStopHandlerHttpGetHost string `name:"LifecyclePreStopHandlerHttpGetHost"`
LifecyclePreStopHandlerHttpGetPort requests.Integer `name:"LifecyclePreStopHandlerHttpGetPort"`
LifecyclePreStopHandlerHttpGetPath string `name:"LifecyclePreStopHandlerHttpGetPath"`
LifecyclePreStopHandlerHttpGetScheme string `name:"LifecyclePreStopHandlerHttpGetScheme"`
LifecyclePreStopHandlerHttpGetHttpHeader *[]CreateContainerGroupLifecyclePreStopHandlerHttpGetHttpHeader `name:"LifecyclePreStopHandlerHttpGetHttpHeader" type:"Repeated"`
LifecyclePreStopHandlerExec []string `name:"LifecyclePreStopHandlerExec" type:"Repeated"`
LifecyclePreStopHandlerTcpSocketHost string `name:"LifecyclePreStopHandlerTcpSocketHost"`
LifecyclePreStopHandlerTcpSocketPort requests.Integer `name:"LifecyclePreStopHandlerTcpSocketPort"`
ReadinessProbe CreateContainerGroupReadinessProbe `name:"ReadinessProbe" type:"Struct"`
LivenessProbe CreateContainerGroupLivenessProbe `name:"LivenessProbe" type:"Struct"`
SecurityContext CreateContainerGroupSecurityContext `name:"SecurityContext" type:"Struct"`
}
type CreateContainerGroupVolume struct {
Name string `name:"Name"`
Type string `name:"Type"`
NFSVolume CreateContainerGroupNFSVolume `name:"NFSVolume" type:"Struct"`
ConfigFileVolume CreateContainerGroupConfigFileVolume `name:"ConfigFileVolume" type:"Struct"`
EmptyDirVolume CreateContainerGroupEmptyDirVolume `name:"EmptyDirVolume" type:"Struct"`
DiskVolume CreateContainerGroupDiskVolume `name:"DiskVolume" type:"Struct"`
FlexVolume CreateContainerGroupFlexVolume `name:"FlexVolume" type:"Struct"`
HostPathVolume CreateContainerGroupHostPathVolume `name:"HostPathVolume" type:"Struct"`
}
type CreateContainerGroupInitContainer struct {
Name string `name:"Name"`
Image string `name:"Image"`
Cpu requests.Float `name:"Cpu"`
Memory requests.Float `name:"Memory"`
WorkingDir string `name:"WorkingDir"`
ImagePullPolicy string `name:"ImagePullPolicy"`
Command []string `name:"Command" type:"Repeated"`
Arg []string `name:"Arg" type:"Repeated"`
VolumeMount *[]CreateContainerGroupVolumeMount `name:"VolumeMount" type:"Repeated"`
Port *[]CreateContainerGroupPort `name:"Port" type:"Repeated"`
EnvironmentVar *[]CreateContainerGroupEnvironmentVar `name:"EnvironmentVar" type:"Repeated"`
Gpu requests.Integer `name:"Gpu"`
SecurityContext CreateContainerGroupSecurityContext `name:"SecurityContext" type:"Struct"`
}
type CreateContainerGroupHostAliase struct {
Ip string `name:"Ip"`
Hostname []string `name:"Hostname" type:"Repeated"`
}
type CreateContainerGroupArn struct {
RoleArn string `name:"RoleArn"`
RoleType string `name:"RoleType"`
AssumeRoleFor string `name:"AssumeRoleFor"`
}
type CreateContainerGroupDnsConfig struct {
NameServer []string `name:"NameServer"`
Search []string `name:"Search"`
Option *[]CreateContainerGroupOption `name:"Option"`
}
type CreateContainerGroupSecurityContext struct {
Sysctl *[]CreateContainerGroupSysctl `name:"Sysctl"`
}
type CreateContainerGroupVolumeMount struct {
MountPath string `name:"MountPath"`
ReadOnly requests.Boolean `name:"ReadOnly"`
Name string `name:"Name"`
SubPath string `name:"SubPath"`
}
type CreateContainerGroupPort struct {
Protocol string `name:"Protocol"`
Port requests.Integer `name:"Port"`
}
type CreateContainerGroupEnvironmentVar struct {
Key string `name:"Key"`
Value string `name:"Value"`
FieldRef CreateContainerGroupFieldRef `name:"FieldRef" type:"Struct"`
}
type CreateContainerGroupFieldRef struct {
FieldPath string `name:"FieldPath"`
}
type CreateContainerGroupLifecyclePostStartHandlerHttpGetHttpHeader struct {
Name string `name:"Name"`
Value string `name:"Value"`
}
type CreateContainerGroupLifecyclePreStopHandlerHttpGetHttpHeader struct {
Name string `name:"Name"`
Value string `name:"Value"`
}
type CreateContainerGroupReadinessProbe struct {
InitialDelaySeconds requests.Integer `name:"InitialDelaySeconds"`
PeriodSeconds requests.Integer `name:"PeriodSeconds"`
SuccessThreshold requests.Integer `name:"SuccessThreshold"`
FailureThreshold requests.Integer `name:"FailureThreshold"`
TimeoutSeconds requests.Integer `name:"TimeoutSeconds"`
HttpGet CreateContainerGroupHttpGet `name:"HttpGet"`
Exec CreateContainerGroupExec `name:"Exec"`
TcpSocket CreateContainerGroupTcpSocket `name:"TcpSocket"`
}
type CreateContainerGroupHttpGet struct {
Path string `name:"Path"`
Port requests.Integer `name:"Port"`
Scheme string `name:"Scheme"`
}
type CreateContainerGroupExec struct {
Command []string `name:"Command"`
}
type CreateContainerGroupTcpSocket struct {
Port requests.Integer `name:"Port"`
}
type CreateContainerGroupLivenessProbe struct {
InitialDelaySeconds requests.Integer `name:"InitialDelaySeconds"`
PeriodSeconds requests.Integer `name:"PeriodSeconds"`
SuccessThreshold requests.Integer `name:"SuccessThreshold"`
FailureThreshold requests.Integer `name:"FailureThreshold"`
TimeoutSeconds requests.Integer `name:"TimeoutSeconds"`
HttpGet CreateContainerGroupHttpGet `name:"HttpGet"`
Exec CreateContainerGroupExec `name:"Exec"`
TcpSocket CreateContainerGroupTcpSocket `name:"TcpSocket"`
}
type CreateContainerGroupNFSVolume struct {
Server string `name:"Server"`
Path string `name:"Path"`
ReadOnly requests.Boolean `name:"ReadOnly"`
}
type CreateContainerGroupConfigFileVolume struct {
ConfigFileToPath *[]CreateContainerGroupConfigFileToPath `name:"ConfigFileToPath"`
DefaultModel requests.Integer `name:"DefaultModel"`
}
type CreateContainerGroupConfigFileToPath struct {
Content string `name:"Content"`
Path string `name:"Path"`
Mode requests.Integer `name:"Mode"`
}
type CreateContainerGroupEmptyDirVolume struct {
Medium string `name:"Medium"`
}
type CreateContainerGroupDiskVolume struct {
DiskId string `name:"DiskId"`
FsType string `name:"FsType"`
DiskSize requests.Integer `name:"DiskSize"`
}
type CreateContainerGroupFlexVolume struct {
Driver string `name:"Driver"`
FsType string `name:"FsType"`
Options string `name:"Options"`
}
type CreateContainerGroupHostPathVolume struct {
Type string `name:"Type"`
Path string `name:"Path"`
}
type CreateContainerGroupOption struct {
Name string `name:"Name"`
Value string `name:"Value"`
}
type CreateContainerGroupSysctl struct {
Name string `name:"Name"`
Value string `name:"Value"`
}
// CreateContainerGroupResponse is the response struct for api CreateContainerGroup
type CreateContainerGroupResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
ContainerGroupId string `json:"ContainerGroupId" xml:"ContainerGroupId"`
}
// CreateCreateContainerGroupRequest creates a request to invoke CreateContainerGroup API
func CreateCreateContainerGroupRequest() (request *CreateContainerGroupRequest) {
request = &CreateContainerGroupRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Eci", "2018-08-08", "CreateContainerGroup", "eci", "openAPI")
return
}
// CreateCreateContainerGroupResponse creates a response to parse from CreateContainerGroup response
func CreateCreateContainerGroupResponse() (response *CreateContainerGroupResponse) {
response = &CreateContainerGroupResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,128 +0,0 @@
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package ali
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"errors"
"flag"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/golang/glog"
)
// DeleteContainerGroup invokes the eci.DeleteContainerGroup API synchronously
// api document: https://help.aliyun.com/api/eci/deletecontainergroup.html
func DeleteContainerGroup(request *DeleteContainerGroupRequest) (response *DeleteContainerGroupResponse, err error) {
provider := pbpod.CloudProvider(request.ProviderId)
var configFile string
flag.StringVar(&configFile, "confAli", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
var regionId int32
var pcmId string
pcmId = request.PcmId
//podId := request.ContainerGroupId
//podName := request.ContainerGroupName
switch request.ProviderId {
case 0:
regionId, _ = tenanter.GetAliRegionId(request.RegionId)
case 1:
regionId, _ = tenanter.GetTencentRegionId(request.RegionId)
case 2:
regionId, _ = tenanter.GetHuaweiRegionId(request.RegionId)
case 3:
regionId, _ = tenanter.GetK8SRegionId(request.RegionId)
}
requestPCM := &pbpod.DeletePodReq{
RequestSource: "ali",
Provider: pbpod.CloudProvider(provider),
AccountName: request.AccountName,
PcmId: pcmId,
Namespace: request.Namespace,
RegionId: regionId,
}
resp, err := server.DeletePod(nil, requestPCM)
if err != nil {
return nil, err
}
response = &DeleteContainerGroupResponse{
BaseResponse: nil,
RequestId: resp.RequestId,
}
return response, err
}
// DeleteContainerGroupRequest is the request struct for api DeleteContainerGroup
type DeleteContainerGroupRequest struct {
*requests.RpcRequest
/*********PCM param************/
RequestSource string `position:"Query" name:"RequestSource"`
ProviderId int32 `position:"Query" name:"ProviderId"`
AccountName string `position:"Query" name:"AccountName"`
Namespace string `position:"Query" name:"Namespace"`
PcmId string `position:"Query" name:"PcmId"`
ContainerGroupName string `position:"Query" name:"ContainerGroupName"`
/*********PCM param************/
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
RegionId string `position:"Query" name:"RegionId"`
ContainerGroupId string `position:"Query" name:"ContainerGroupId"`
ClientToken string `position:"Query" name:"ClientToken"`
VkClientVersion string `position:"Query" name:"VkClientVersion"`
}
// DeleteContainerGroupResponse is the response struct for api DeleteContainerGroup
type DeleteContainerGroupResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteContainerGroupRequest creates a request to invoke DeleteContainerGroup API
func CreateDeleteContainerGroupRequest() (request *DeleteContainerGroupRequest) {
request = &DeleteContainerGroupRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Eci", "2018-08-08", "DeleteContainerGroup", "eci", "openAPI")
return
}
// CreateDeleteContainerGroupResponse creates a response to parse from DeleteContainerGroup response
func CreateDeleteContainerGroupResponse() (response *DeleteContainerGroupResponse) {
response = &DeleteContainerGroupResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,313 +0,0 @@
package ali
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeContainerGroups invokes the eci.DescribeContainerGroups API synchronously
// api document: https://help.aliyun.com/api/eci/describecontainergroups.html
func DescribeContainerGroups(request *DescribeContainerGroupsRequest) (response *DescribeContainerGroupsResponse, err error) {
provider := pbpod.CloudProvider(request.ProviderId)
containerGroups := make([]DescribeContainerGroupsContainerGroup0, 0)
//trans Ali request to PCM request
requestPCM := &pbpod.ListPodReq{
RequestSource: "ali",
Provider: provider,
Namespace: "pcm",
}
resp, err := server.ListPod(nil, requestPCM)
//trans PCM response pcm_pod set to Ali ContainerGroup set
for k := range resp.Pods {
podId := resp.Pods[k].PodId
podName := resp.Pods[k].PodName
containerGroup := new(DescribeContainerGroupsContainerGroup0)
containerGroup.ContainerGroupName = podName
containerGroup.ContainerGroupId = podId
containerGroups = append(containerGroups, *containerGroup)
}
response = &DescribeContainerGroupsResponse{
BaseResponse: nil,
RequestId: "",
NextToken: "",
TotalCount: 0,
ContainerGroups: containerGroups,
}
return response, nil
}
// DescribeContainerGroupsRequest is the request struct for api DescribeContainerGroups
type DescribeContainerGroupsRequest struct {
*requests.RpcRequest
/*********PCM param************/
RequestSource string `position:"Query" name:"RequestSource"`
ProviderId int32 `position:"Query" name:"ProviderId"`
AccountName string `position:"Query" name:"AccountName"`
Namespace string `position:"Query" name:"Namespace"`
/*********PCM param************/
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
RegionId string `position:"Query" name:"RegionId"`
ZoneId string `position:"Query" name:"ZoneId"`
VSwitchId string `position:"Query" name:"VSwitchId"`
NextToken string `position:"Query" name:"NextToken"`
Limit requests.Integer `position:"Query" name:"Limit"`
Tag *[]DescribeContainerGroupsTag `position:"Query" name:"Tag" type:"Repeated"`
ContainerGroupIds string `position:"Query" name:"ContainerGroupIds"`
ContainerGroupName string `position:"Query" name:"ContainerGroupName"`
Status string `position:"Query" name:"Status"`
VkClientVersion string `position:"Query" name:"VkClientVersion"`
ResourceGroupId string `position:"Query" name:"ResourceGroupId"`
WithEvent requests.Boolean `position:"Query" name:"WithEvent"`
}
type DescribeContainerGroupsTag struct {
Key string `name:"Key"`
Value string `name:"Value"`
}
// DescribeContainerGroupsResponse is the response struct for api DescribeContainerGroups
type DescribeContainerGroupsResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
NextToken string `json:"NextToken" xml:"NextToken"`
TotalCount int `json:"TotalCount" xml:"TotalCount"`
ContainerGroups []DescribeContainerGroupsContainerGroup0 `json:"ContainerGroups" xml:"ContainerGroups"`
}
type DescribeContainerGroupsContainerGroup0 struct {
ContainerGroupId string `json:"ContainerGroupId" xml:"ContainerGroupId"`
ContainerGroupName string `json:"ContainerGroupName" xml:"ContainerGroupName"`
RegionId string `json:"RegionId" xml:"RegionId"`
ZoneId string `json:"ZoneId" xml:"ZoneId"`
Memory float32 `json:"Memory" xml:"Memory"`
Cpu float32 `json:"Cpu" xml:"Cpu"`
VSwitchId string `json:"VSwitchId" xml:"VSwitchId"`
SecurityGroupId string `json:"SecurityGroupId" xml:"SecurityGroupId"`
RestartPolicy string `json:"RestartPolicy" xml:"RestartPolicy"`
IntranetIp string `json:"IntranetIp" xml:"IntranetIp"`
Status string `json:"Status" xml:"Status"`
InternetIp string `json:"InternetIp" xml:"InternetIp"`
CreationTime string `json:"CreationTime" xml:"CreationTime"`
SucceededTime string `json:"SucceededTime" xml:"SucceededTime"`
EniInstanceId string `json:"EniInstanceId" xml:"EniInstanceId"`
InstanceType string `json:"InstanceType" xml:"InstanceType"`
ExpiredTime string `json:"ExpiredTime" xml:"ExpiredTime"`
FailedTime string `json:"FailedTime" xml:"FailedTime"`
RamRoleName string `json:"RamRoleName" xml:"RamRoleName"`
Ipv6Address string `json:"Ipv6Address" xml:"Ipv6Address"`
VpcId string `json:"VpcId" xml:"VpcId"`
Discount int `json:"Discount" xml:"Discount"`
ResourceGroupId string `json:"ResourceGroupId" xml:"ResourceGroupId"`
Tags []DescribeContainerGroupsLabel1 `json:"Tags" xml:"Tags"`
Events []DescribeContainerGroupsEvent1 `json:"Events" xml:"Events"`
Containers []DescribeContainerGroupsContainer1 `json:"Containers" xml:"Containers"`
Volumes []DescribeContainerGroupsVolume1 `json:"Volumes" xml:"Volumes"`
InitContainers []DescribeContainerGroupsContainer1 `json:"InitContainers" xml:"InitContainers"`
HostAliases []DescribeContainerGroupsHostAliase1 `json:"HostAliases" xml:"HostAliases"`
DnsConfig DescribeContainerGroupsDnsConfig1 `json:"DnsConfig" xml:"DnsConfig"`
EciSecurityContext DescribeContainerGroupsEciSecurityContext1 `json:"EciSecurityContext" xml:"EciSecurityContext"`
}
type DescribeContainerGroupsLabel1 struct {
Key string `json:"Key" xml:"Key"`
Value string `json:"Value" xml:"Value"`
}
type DescribeContainerGroupsEvent1 struct {
Count int `json:"Count" xml:"Count"`
Type string `json:"Type" xml:"Type"`
Name string `json:"Name" xml:"Name"`
Message string `json:"Message" xml:"Message"`
FirstTimestamp string `json:"FirstTimestamp" xml:"FirstTimestamp"`
LastTimestamp string `json:"LastTimestamp" xml:"LastTimestamp"`
Reason string `json:"Reason" xml:"Reason"`
}
type DescribeContainerGroupsContainer1 struct {
Name string `json:"Name" xml:"Name"`
Image string `json:"Image" xml:"Image"`
Memory float32 `json:"Memory" xml:"Memory"`
Cpu float32 `json:"Cpu" xml:"Cpu"`
RestartCount int `json:"RestartCount" xml:"RestartCount"`
WorkingDir string `json:"WorkingDir" xml:"WorkingDir"`
ImagePullPolicy string `json:"ImagePullPolicy" xml:"ImagePullPolicy"`
Ready bool `json:"Ready" xml:"Ready"`
Gpu int `json:"Gpu" xml:"Gpu"`
Stdin bool `json:"Stdin" xml:"Stdin"`
StdinOnce bool `json:"StdinOnce" xml:"StdinOnce"`
Tty bool `json:"Tty" xml:"Tty"`
VolumeMounts []DescribeContainerGroupsVolumeMount2 `json:"VolumeMounts" xml:"VolumeMounts"`
Ports []DescribeContainerGroupsPort2 `json:"Ports" xml:"Ports"`
EnvironmentVars []DescribeContainerGroupsEnvironmentVar2 `json:"EnvironmentVars" xml:"EnvironmentVars"`
Commands []string `json:"Commands" xml:"Commands"`
Args []string `json:"Args" xml:"Args"`
PreviousState DescribeContainerGroupsPreviousState2 `json:"PreviousState" xml:"PreviousState"`
CurrentState DescribeContainerGroupsCurrentState2 `json:"CurrentState" xml:"CurrentState"`
ReadinessProbe DescribeContainerGroupsReadinessProbe2 `json:"ReadinessProbe" xml:"ReadinessProbe"`
LivenessProbe DescribeContainerGroupsLivenessProbe2 `json:"LivenessProbe" xml:"LivenessProbe"`
SecurityContext DescribeContainerGroupsSecurityContext2 `json:"SecurityContext" xml:"SecurityContext"`
}
type DescribeContainerGroupsVolumeMount2 struct {
Name string `json:"Name" xml:"Name"`
MountPath string `json:"MountPath" xml:"MountPath"`
ReadOnly bool `json:"ReadOnly" xml:"ReadOnly"`
}
type DescribeContainerGroupsPort2 struct {
Port int `json:"Port" xml:"Port"`
Protocol string `json:"Protocol" xml:"Protocol"`
}
type DescribeContainerGroupsEnvironmentVar2 struct {
Key string `json:"Key" xml:"Key"`
Value string `json:"Value" xml:"Value"`
ValueFrom DescribeContainerGroupsValueFrom3 `json:"ValueFrom" xml:"ValueFrom"`
}
type DescribeContainerGroupsValueFrom3 struct {
FieldRef DescribeContainerGroupsFieldRef4 `json:"FieldRef" xml:"FieldRef"`
}
type DescribeContainerGroupsFieldRef4 struct {
FieldPath string `json:"FieldPath" xml:"FieldPath"`
}
type DescribeContainerGroupsPreviousState2 struct {
State string `json:"State" xml:"State"`
DetailStatus string `json:"DetailStatus" xml:"DetailStatus"`
ExitCode int `json:"ExitCode" xml:"ExitCode"`
StartTime string `json:"StartTime" xml:"StartTime"`
FinishTime string `json:"FinishTime" xml:"FinishTime"`
Reason string `json:"Reason" xml:"Reason"`
Message string `json:"Message" xml:"Message"`
Signal int `json:"Signal" xml:"Signal"`
}
type DescribeContainerGroupsCurrentState2 struct {
State string `json:"State" xml:"State"`
DetailStatus string `json:"DetailStatus" xml:"DetailStatus"`
ExitCode int `json:"ExitCode" xml:"ExitCode"`
StartTime string `json:"StartTime" xml:"StartTime"`
FinishTime string `json:"FinishTime" xml:"FinishTime"`
Reason string `json:"Reason" xml:"Reason"`
Message string `json:"Message" xml:"Message"`
Signal int `json:"Signal" xml:"Signal"`
}
type DescribeContainerGroupsReadinessProbe2 struct {
InitialDelaySeconds int `json:"InitialDelaySeconds" xml:"InitialDelaySeconds"`
PeriodSeconds int `json:"PeriodSeconds" xml:"PeriodSeconds"`
TimeoutSeconds int `json:"TimeoutSeconds" xml:"TimeoutSeconds"`
SuccessThreshold int `json:"SuccessThreshold" xml:"SuccessThreshold"`
FailureThreshold int `json:"FailureThreshold" xml:"FailureThreshold"`
Execs []string `json:"Execs" xml:"Execs"`
HttpGet DescribeContainerGroupsHttpGet3 `json:"HttpGet" xml:"HttpGet"`
TcpSocket DescribeContainerGroupsTcpSocket3 `json:"TcpSocket" xml:"TcpSocket"`
}
type DescribeContainerGroupsHttpGet3 struct {
Path string `json:"Path" xml:"Path"`
Port int `json:"Port" xml:"Port"`
Scheme string `json:"Scheme" xml:"Scheme"`
}
type DescribeContainerGroupsTcpSocket3 struct {
Host string `json:"Host" xml:"Host"`
Port int `json:"Port" xml:"Port"`
}
type DescribeContainerGroupsLivenessProbe2 struct {
InitialDelaySeconds int `json:"InitialDelaySeconds" xml:"InitialDelaySeconds"`
PeriodSeconds int `json:"PeriodSeconds" xml:"PeriodSeconds"`
TimeoutSeconds int `json:"TimeoutSeconds" xml:"TimeoutSeconds"`
SuccessThreshold int `json:"SuccessThreshold" xml:"SuccessThreshold"`
FailureThreshold int `json:"FailureThreshold" xml:"FailureThreshold"`
Execs []string `json:"Execs" xml:"Execs"`
HttpGet DescribeContainerGroupsHttpGet3 `json:"HttpGet" xml:"HttpGet"`
TcpSocket DescribeContainerGroupsTcpSocket3 `json:"TcpSocket" xml:"TcpSocket"`
}
type DescribeContainerGroupsSecurityContext2 struct {
ReadOnlyRootFilesystem bool `json:"ReadOnlyRootFilesystem" xml:"ReadOnlyRootFilesystem"`
RunAsUser int64 `json:"RunAsUser" xml:"RunAsUser"`
Capability DescribeContainerGroupsCapability3 `json:"Capability" xml:"Capability"`
}
type DescribeContainerGroupsCapability3 struct {
Adds []string `json:"Adds" xml:"Adds"`
}
type DescribeContainerGroupsVolume1 struct {
Type string `json:"Type" xml:"Type"`
Name string `json:"Name" xml:"Name"`
NFSVolumePath string `json:"NFSVolumePath" xml:"NFSVolumePath"`
NFSVolumeServer string `json:"NFSVolumeServer" xml:"NFSVolumeServer"`
NFSVolumeReadOnly bool `json:"NFSVolumeReadOnly" xml:"NFSVolumeReadOnly"`
DiskVolumeDiskId string `json:"DiskVolumeDiskId" xml:"DiskVolumeDiskId"`
DiskVolumeFsType string `json:"DiskVolumeFsType" xml:"DiskVolumeFsType"`
FlexVolumeDriver string `json:"FlexVolumeDriver" xml:"FlexVolumeDriver"`
FlexVolumeFsType string `json:"FlexVolumeFsType" xml:"FlexVolumeFsType"`
FlexVolumeOptions string `json:"FlexVolumeOptions" xml:"FlexVolumeOptions"`
ConfigFileVolumeConfigFileToPaths []DescribeContainerGroupsConfigFileVolumeConfigFileToPath2 `json:"ConfigFileVolumeConfigFileToPaths" xml:"ConfigFileVolumeConfigFileToPaths"`
}
type DescribeContainerGroupsConfigFileVolumeConfigFileToPath2 struct {
Content string `json:"Content" xml:"Content"`
Path string `json:"Path" xml:"Path"`
}
type DescribeContainerGroupsHostAliase1 struct {
Ip string `json:"Ip" xml:"Ip"`
Hostnames []string `json:"Hostnames" xml:"Hostnames"`
}
type DescribeContainerGroupsDnsConfig1 struct {
Options []DescribeContainerGroupsOption2 `json:"Options" xml:"Options"`
NameServers []string `json:"NameServers" xml:"NameServers"`
Searches []string `json:"Searches" xml:"Searches"`
}
type DescribeContainerGroupsOption2 struct {
Name string `json:"Name" xml:"Name"`
Value string `json:"Value" xml:"Value"`
}
type DescribeContainerGroupsEciSecurityContext1 struct {
Sysctls []DescribeContainerGroupsSysctl2 `json:"Sysctls" xml:"Sysctls"`
}
type DescribeContainerGroupsSysctl2 struct {
Name string `json:"Name" xml:"Name"`
Value string `json:"Value" xml:"Value"`
}
// CreateDescribeContainerGroupsRequest creates a request to invoke DescribeContainerGroups API
func CreateDescribeContainerGroupsRequest() (request *DescribeContainerGroupsRequest) {
request = &DescribeContainerGroupsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Eci", "2018-08-08", "DescribeContainerGroups", "eci", "openAPI")
return
}
// CreateDescribeContainerGroupsResponse creates a response to parse from DescribeContainerGroups response
func CreateDescribeContainerGroupsResponse() (response *DescribeContainerGroupsResponse) {
response = &DescribeContainerGroupsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,290 +0,0 @@
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package ali
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"errors"
"flag"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/golang/glog"
)
// UpdateContainerGroup invokes the eci.UpdateContainerGroup API synchronously
// api document: https://help.aliyun.com/api/eci/updatecontainergroup.html
func UpdateContainerGroup(request *UpdateContainerGroupRequest) (response *UpdateContainerGroupResponse, err error) {
provider := pbpod.CloudProvider(request.ProviderId)
var configFile string
flag.StringVar(&configFile, "confAli", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
var regionId int32
switch request.ProviderId {
case 0:
regionId, _ = tenanter.GetAliRegionId(request.RegionId)
case 1:
regionId, _ = tenanter.GetTencentRegionId(request.RegionId)
case 2:
regionId, _ = tenanter.GetHuaweiRegionId(request.RegionId)
case 3:
regionId, _ = tenanter.GetK8SRegionId(request.RegionId)
}
containers := *request.Container
requestPCM := &pbpod.UpdatePodReq{
RequestSource: "ali",
Provider: pbpod.CloudProvider(provider),
AccountName: request.AccountName,
PcmId: request.PcmId,
PodId: request.ContainerGroupId,
PodName: request.ContainerGroupName,
Namespace: request.Namespace,
RegionId: regionId,
ContainerImage: containers[0].Image,
ContainerName: containers[0].Name,
CpuPod: string(containers[0].Cpu),
MemoryPod: string(containers[0].Memory),
RestartPolicy: request.RestartPolicy,
Labels: "sss",
}
resp, err := server.UpdatePod(nil, requestPCM)
response = &UpdateContainerGroupResponse{
BaseResponse: nil,
RequestId: resp.RequestId,
}
return response, err
}
// UpdateContainerGroupRequest is the request struct for api UpdateContainerGroup
type UpdateContainerGroupRequest struct {
*requests.RpcRequest
/*********PCM param************/
RequestSource string `position:"Query" name:"RequestSource"`
ProviderId int32 `position:"Query" name:"ProviderId"`
AccountName string `position:"Query" name:"AccountName"`
Namespace string `position:"Query" name:"Namespace"`
PcmId string `position:"Query" name:"PcmId"`
PodName string `position:"Query" name:"PodName"`
ContainerGroupName string `position:"Query" name:"ContainerGroupName"`
/*********PCM param************/
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
RegionId string `position:"Query" name:"RegionId"`
ContainerGroupId string `position:"Query" name:"ContainerGroupId"`
RestartPolicy string `position:"Query" name:"RestartPolicy"`
Tag *[]UpdateContainerGroupTag `position:"Query" name:"Tag" type:"Repeated"`
Volume *[]UpdateContainerGroupVolume `position:"Query" name:"Volume" type:"Repeated"`
Container *[]UpdateContainerGroupContainer `position:"Query" name:"Container" type:"Repeated"`
InitContainer *[]UpdateContainerGroupInitContainer `position:"Query" name:"InitContainer" type:"Repeated"`
ImageRegistryCredential *[]UpdateContainerGroupImageRegistryCredential `position:"Query" name:"ImageRegistryCredential" type:"Repeated"`
ClientToken string `position:"Query" name:"ClientToken"`
Cpu requests.Float `position:"Query" name:"Cpu"`
Memory requests.Float `position:"Query" name:"Memory"`
DnsConfig UpdateContainerGroupDnsConfig `position:"Query" name:"DnsConfig" type:"Struct"`
}
type UpdateContainerGroupTag struct {
Key string `name:"Key"`
Value string `name:"Value"`
}
type UpdateContainerGroupVolume struct {
Name string `name:"Name"`
Type string `name:"Type"`
NFSVolume UpdateContainerGroupNFSVolume `name:"NFSVolume" type:"Struct"`
ConfigFileVolume UpdateContainerGroupConfigFileVolume `name:"ConfigFileVolume" type:"Struct"`
EmptyDirVolume UpdateContainerGroupEmptyDirVolume `name:"EmptyDirVolume" type:"Struct"`
}
type UpdateContainerGroupContainer struct {
Name string `name:"Name"`
Image string `name:"Image"`
Cpu requests.Float `name:"Cpu"`
Memory requests.Float `name:"Memory"`
WorkingDir string `name:"WorkingDir"`
ImagePullPolicy string `name:"ImagePullPolicy"`
Stdin requests.Boolean `name:"Stdin"`
StdinOnce requests.Boolean `name:"StdinOnce"`
Tty requests.Boolean `name:"Tty"`
Command []string `name:"Command" type:"Repeated"`
Arg []string `name:"Arg" type:"Repeated"`
EnvironmentVar []string `name:"EnvironmentVar" type:"Repeated"`
Port []string `name:"Port" type:"Repeated"`
VolumeMount []string `name:"VolumeMount" type:"Repeated"`
Gpu requests.Integer `name:"Gpu"`
ReadinessProbe UpdateContainerGroupReadinessProbe `name:"ReadinessProbe" type:"Struct"`
LivenessProbe UpdateContainerGroupLivenessProbe `name:"LivenessProbe" type:"Struct"`
SecurityContext UpdateContainerGroupSecurityContext `name:"SecurityContext" type:"Struct"`
}
type UpdateContainerGroupInitContainer struct {
Name string `name:"Name"`
Image string `name:"Image"`
Cpu requests.Float `name:"Cpu"`
Memory requests.Float `name:"Memory"`
WorkingDir string `name:"WorkingDir"`
ImagePullPolicy string `name:"ImagePullPolicy"`
Stdin requests.Boolean `name:"Stdin"`
StdinOnce requests.Boolean `name:"StdinOnce"`
Tty requests.Boolean `name:"Tty"`
Command []string `name:"Command" type:"Repeated"`
Arg []string `name:"Arg" type:"Repeated"`
EnvironmentVar *[]UpdateContainerGroupEnvironmentVar `name:"EnvironmentVar" type:"Repeated"`
Port *[]UpdateContainerGroupPort `name:"Port" type:"Repeated"`
VolumeMount *[]UpdateContainerGroupVolumeMount `name:"VolumeMount" type:"Repeated"`
Gpu requests.Integer `name:"Gpu"`
SecurityContext UpdateContainerGroupSecurityContext `name:"SecurityContext" type:"Struct"`
}
type UpdateContainerGroupImageRegistryCredential struct {
Server string `name:"Server"`
UserName string `name:"UserName"`
Password string `name:"Password"`
}
type UpdateContainerGroupDnsConfig struct {
NameServer []string `name:"NameServer"`
Search []string `name:"Search"`
Option *[]UpdateContainerGroupOption `name:"Option"`
}
type UpdateContainerGroupNFSVolume struct {
Server string `name:"Server"`
Path string `name:"Path"`
ReadOnly requests.Boolean `name:"ReadOnly"`
}
type UpdateContainerGroupConfigFileVolume struct {
ConfigFileToPath *[]UpdateContainerGroupConfigFileToPath `name:"ConfigFileToPath"`
}
type UpdateContainerGroupConfigFileToPath struct {
Content string `name:"Content"`
Path string `name:"Path"`
}
type UpdateContainerGroupEmptyDirVolume struct {
Medium string `name:"Medium"`
}
type UpdateContainerGroupReadinessProbe struct {
InitialDelaySeconds requests.Integer `name:"InitialDelaySeconds"`
PeriodSeconds requests.Integer `name:"PeriodSeconds"`
SuccessThreshold requests.Integer `name:"SuccessThreshold"`
FailureThreshold requests.Integer `name:"FailureThreshold"`
TimeoutSeconds requests.Integer `name:"TimeoutSeconds"`
TcpSocket UpdateContainerGroupTcpSocket `name:"TcpSocket"`
Exec UpdateContainerGroupExec `name:"Exec"`
HttpGet UpdateContainerGroupHttpGet `name:"HttpGet"`
}
type UpdateContainerGroupTcpSocket struct {
Port requests.Integer `name:"Port"`
}
type UpdateContainerGroupExec struct {
Command []string `name:"Command"`
}
type UpdateContainerGroupHttpGet struct {
Path string `name:"Path"`
Port requests.Integer `name:"Port"`
Scheme string `name:"Scheme"`
}
type UpdateContainerGroupLivenessProbe struct {
InitialDelaySeconds requests.Integer `name:"InitialDelaySeconds"`
PeriodSeconds requests.Integer `name:"PeriodSeconds"`
SuccessThreshold requests.Integer `name:"SuccessThreshold"`
FailureThreshold requests.Integer `name:"FailureThreshold"`
TimeoutSeconds requests.Integer `name:"TimeoutSeconds"`
TcpSocket UpdateContainerGroupTcpSocket `name:"TcpSocket"`
Exec UpdateContainerGroupExec `name:"Exec"`
HttpGet UpdateContainerGroupHttpGet `name:"HttpGet"`
}
type UpdateContainerGroupSecurityContext struct {
ReadOnlyRootFilesystem requests.Boolean `name:"ReadOnlyRootFilesystem"`
RunAsUser requests.Integer `name:"RunAsUser"`
Capability UpdateContainerGroupCapability `name:"Capability"`
}
type UpdateContainerGroupCapability struct {
Add []string `name:"Add"`
}
type UpdateContainerGroupEnvironmentVar struct {
Key string `name:"Key"`
Value string `name:"Value"`
}
type UpdateContainerGroupPort struct {
Port requests.Integer `name:"Port"`
Protocol string `name:"Protocol"`
}
type UpdateContainerGroupVolumeMount struct {
Name string `name:"Name"`
MountPath string `name:"MountPath"`
SubPath string `name:"SubPath"`
ReadOnly requests.Boolean `name:"ReadOnly"`
}
type UpdateContainerGroupOption struct {
Name string `name:"Name"`
Value string `name:"Value"`
}
// UpdateContainerGroupResponse is the response struct for api UpdateContainerGroup
type UpdateContainerGroupResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateUpdateContainerGroupRequest creates a request to invoke UpdateContainerGroup API
func CreateUpdateContainerGroupRequest() (request *UpdateContainerGroupRequest) {
request = &UpdateContainerGroupRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Eci", "2018-08-08", "UpdateContainerGroup", "eci", "openAPI")
return
}
// CreateUpdateContainerGroupResponse creates a response to parse from UpdateContainerGroup response
func CreateUpdateContainerGroupResponse() (response *UpdateContainerGroupResponse) {
response = &UpdateContainerGroupResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,33 +0,0 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"k8s.io/apimachinery/pkg/runtime/schema"
)
// IsAnAPIObject allows clients to preemptively get a reference to an API object and pass it to places that
// intend only to get a reference to that object. This simplifies the event recording interface.
func (obj *ObjectReference) SetGroupVersionKind(gvk schema.GroupVersionKind) {
obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()
}
func (obj *ObjectReference) GroupVersionKind() schema.GroupVersionKind {
return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)
}
func (obj *ObjectReference) GetObjectKind() schema.ObjectKind { return obj }

View File

@ -1,100 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// GroupName is the group name use in this package
const GroupName = ""
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"}
// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
// We only register manually written functions here. The registration of the
// generated functions takes place in the generated files. The separation
// makes the code compile even when the generated files are missing.
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
AddToScheme = SchemeBuilder.AddToScheme
)
// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Pod{},
&PodList{},
&PodStatusResult{},
&PodTemplate{},
&PodTemplateList{},
&ReplicationController{},
&ReplicationControllerList{},
&Service{},
&ServiceProxyOptions{},
&ServiceList{},
&Endpoints{},
&EndpointsList{},
&Node{},
&NodeList{},
&NodeProxyOptions{},
&Binding{},
&Event{},
&EventList{},
&List{},
&LimitRange{},
&LimitRangeList{},
&ResourceQuota{},
&ResourceQuotaList{},
&Namespace{},
&NamespaceList{},
&Secret{},
&SecretList{},
&ServiceAccount{},
&ServiceAccountList{},
&PersistentVolume{},
&PersistentVolumeList{},
&PersistentVolumeClaim{},
&PersistentVolumeClaimList{},
&PodAttachOptions{},
&PodLogOptions{},
&PodExecOptions{},
&PodPortForwardOptions{},
&PodProxyOptions{},
&ComponentStatus{},
&ComponentStatusList{},
&SerializedReference{},
&RangeAllocation{},
&ConfigMap{},
&ConfigMapList{},
&EphemeralContainers{},
)
// Add common types
scheme.AddKnownTypes(SchemeGroupVersion, &metav1.Status{})
// Add the watch version that applies
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -1,59 +0,0 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"k8s.io/apimachinery/pkg/api/resource"
)
// Returns string version of ResourceName.
func (rn ResourceName) String() string {
return string(rn)
}
// Cpu returns the Cpu limit if specified.
func (rl *ResourceList) Cpu() *resource.Quantity {
return rl.Name(ResourceCPU, resource.DecimalSI)
}
// Memory returns the Memory limit if specified.
func (rl *ResourceList) Memory() *resource.Quantity {
return rl.Name(ResourceMemory, resource.BinarySI)
}
// Storage returns the Storage limit if specified.
func (rl *ResourceList) Storage() *resource.Quantity {
return rl.Name(ResourceStorage, resource.BinarySI)
}
// Pods returns the list of pods
func (rl *ResourceList) Pods() *resource.Quantity {
return rl.Name(ResourcePods, resource.DecimalSI)
}
// StorageEphemeral returns the list of ephemeral storage volumes, if any
func (rl *ResourceList) StorageEphemeral() *resource.Quantity {
return rl.Name(ResourceEphemeralStorage, resource.BinarySI)
}
// Name returns the resource with name if specified, otherwise it returns a nil quantity with default format.
func (rl *ResourceList) Name(name ResourceName, defaultFormat resource.Format) *resource.Quantity {
if val, ok := (*rl)[name]; ok {
return &val
}
return &resource.Quantity{Format: defaultFormat}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,181 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"encoding/json"
"time"
)
const RFC3339Micro = "2006-01-02T15:04:05.000000Z07:00"
// MicroTime is version of Time with microsecond level precision.
//
// +protobuf.options.marshal=false
// +protobuf.as=Timestamp
// +protobuf.options.(gogoproto.goproto_stringer)=false
type MicroTime struct {
time.Time `protobuf:"-"`
}
// DeepCopy returns a deep-copy of the MicroTime value. The underlying time.Time
// type is effectively immutable in the time API, so it is safe to
// copy-by-assign, despite the presence of (unexported) Pointer fields.
func (t *MicroTime) DeepCopyInto(out *MicroTime) {
*out = *t
}
// NewMicroTime returns a wrapped instance of the provided time
func NewMicroTime(time time.Time) MicroTime {
return MicroTime{time}
}
// DateMicro returns the MicroTime corresponding to the supplied parameters
// by wrapping time.Date.
func DateMicro(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) MicroTime {
return MicroTime{time.Date(year, month, day, hour, min, sec, nsec, loc)}
}
// NowMicro returns the current local time.
func NowMicro() MicroTime {
return MicroTime{time.Now()}
}
// IsZero returns true if the value is nil or time is zero.
func (t *MicroTime) IsZero() bool {
if t == nil {
return true
}
return t.Time.IsZero()
}
// Before reports whether the time instant t is before u.
func (t *MicroTime) Before(u *MicroTime) bool {
if t != nil && u != nil {
return t.Time.Before(u.Time)
}
return false
}
// Equal reports whether the time instant t is equal to u.
func (t *MicroTime) Equal(u *MicroTime) bool {
if t == nil && u == nil {
return true
}
if t != nil && u != nil {
return t.Time.Equal(u.Time)
}
return false
}
// BeforeTime reports whether the time instant t is before second-lever precision u.
func (t *MicroTime) BeforeTime(u *Time) bool {
if t != nil && u != nil {
return t.Time.Before(u.Time)
}
return false
}
// EqualTime reports whether the time instant t is equal to second-lever precision u.
func (t *MicroTime) EqualTime(u *Time) bool {
if t == nil && u == nil {
return true
}
if t != nil && u != nil {
return t.Time.Equal(u.Time)
}
return false
}
// UnixMicro returns the local time corresponding to the given Unix time
// by wrapping time.Unix.
func UnixMicro(sec int64, nsec int64) MicroTime {
return MicroTime{time.Unix(sec, nsec)}
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (t *MicroTime) UnmarshalJSON(b []byte) error {
if len(b) == 4 && string(b) == "null" {
t.Time = time.Time{}
return nil
}
var str string
err := json.Unmarshal(b, &str)
if err != nil {
return err
}
pt, err := time.Parse(RFC3339Micro, str)
if err != nil {
return err
}
t.Time = pt.Local()
return nil
}
// UnmarshalQueryParameter converts from a URL query parameter value to an object
func (t *MicroTime) UnmarshalQueryParameter(str string) error {
if len(str) == 0 {
t.Time = time.Time{}
return nil
}
// Tolerate requests from older clients that used JSON serialization to build query params
if len(str) == 4 && str == "null" {
t.Time = time.Time{}
return nil
}
pt, err := time.Parse(RFC3339Micro, str)
if err != nil {
return err
}
t.Time = pt.Local()
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (t MicroTime) MarshalJSON() ([]byte, error) {
if t.IsZero() {
// Encode unset/nil objects as JSON's "null".
return []byte("null"), nil
}
return json.Marshal(t.UTC().Format(RFC3339Micro))
}
// OpenAPISchemaType is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
//
// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
func (_ MicroTime) OpenAPISchemaType() []string { return []string{"string"} }
// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
func (_ MicroTime) OpenAPISchemaFormat() string { return "date-time" }
// MarshalQueryParameter converts to a URL query parameter value
func (t MicroTime) MarshalQueryParameter() (string, error) {
if t.IsZero() {
// Encode unset/nil objects as an empty string
return "", nil
}
return t.UTC().Format(RFC3339Micro), nil
}

View File

@ -1,182 +0,0 @@
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"encoding/json"
"time"
)
// Time is a wrapper around time.Time which supports correct
// marshaling to YAML and JSON. Wrappers are provided for many
// of the factory methods that the time package offers.
//
// +protobuf.options.marshal=false
// +protobuf.as=Timestamp
// +protobuf.options.(gogoproto.goproto_stringer)=false
type Time struct {
time.Time `protobuf:"-"`
}
// DeepCopyInto creates a deep-copy of the Time value. The underlying time.Time
// type is effectively immutable in the time API, so it is safe to
// copy-by-assign, despite the presence of (unexported) Pointer fields.
func (t *Time) DeepCopyInto(out *Time) {
*out = *t
}
// NewTime returns a wrapped instance of the provided time
func NewTime(time time.Time) Time {
return Time{time}
}
// Date returns the Time corresponding to the supplied parameters
// by wrapping time.Date.
func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time {
return Time{time.Date(year, month, day, hour, min, sec, nsec, loc)}
}
// Now returns the current local time.
func Now() Time {
return Time{time.Now()}
}
// IsZero returns true if the value is nil or time is zero.
func (t *Time) IsZero() bool {
if t == nil {
return true
}
return t.Time.IsZero()
}
// Before reports whether the time instant t is before u.
func (t *Time) Before(u *Time) bool {
if t != nil && u != nil {
return t.Time.Before(u.Time)
}
return false
}
// Equal reports whether the time instant t is equal to u.
func (t *Time) Equal(u *Time) bool {
if t == nil && u == nil {
return true
}
if t != nil && u != nil {
return t.Time.Equal(u.Time)
}
return false
}
// Unix returns the local time corresponding to the given Unix time
// by wrapping time.Unix.
func Unix(sec int64, nsec int64) Time {
return Time{time.Unix(sec, nsec)}
}
// Rfc3339Copy returns a copy of the Time at second-level precision.
func (t Time) Rfc3339Copy() Time {
copied, _ := time.Parse(time.RFC3339, t.Format(time.RFC3339))
return Time{copied}
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (t *Time) UnmarshalJSON(b []byte) error {
if len(b) == 4 && string(b) == "null" {
t.Time = time.Time{}
return nil
}
var str string
err := json.Unmarshal(b, &str)
if err != nil {
return err
}
pt, err := time.Parse(time.RFC3339, str)
if err != nil {
return err
}
t.Time = pt.Local()
return nil
}
// UnmarshalQueryParameter converts from a URL query parameter value to an object
func (t *Time) UnmarshalQueryParameter(str string) error {
if len(str) == 0 {
t.Time = time.Time{}
return nil
}
// Tolerate requests from older clients that used JSON serialization to build query params
if len(str) == 4 && str == "null" {
t.Time = time.Time{}
return nil
}
pt, err := time.Parse(time.RFC3339, str)
if err != nil {
return err
}
t.Time = pt.Local()
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (t Time) MarshalJSON() ([]byte, error) {
if t.IsZero() {
// Encode unset/nil objects as JSON's "null".
return []byte("null"), nil
}
buf := make([]byte, 0, len(time.RFC3339)+2)
buf = append(buf, '"')
// time cannot contain non escapable JSON characters
buf = t.UTC().AppendFormat(buf, time.RFC3339)
buf = append(buf, '"')
return buf, nil
}
// ToUnstructured implements the value.UnstructuredConverter interface.
func (t Time) ToUnstructured() interface{} {
if t.IsZero() {
return nil
}
buf := make([]byte, 0, len(time.RFC3339))
buf = t.UTC().AppendFormat(buf, time.RFC3339)
return string(buf)
}
// OpenAPISchemaType is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
//
// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
func (_ Time) OpenAPISchemaType() []string { return []string{"string"} }
// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
func (_ Time) OpenAPISchemaFormat() string { return "date-time" }
// MarshalQueryParameter converts to a URL query parameter value
func (t Time) MarshalQueryParameter() (string, error) {
if t.IsZero() {
// Encode unset/nil objects as an empty string
return "", nil
}
return t.UTC().Format(time.RFC3339), nil
}

View File

@ -1,685 +0,0 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package kubernetes
import (
corev1 "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server/kubernetes/client-go/kubernetes/typed/core/v1"
"fmt"
discovery "k8s.io/client-go/discovery"
admissionregistrationv1 "k8s.io/client-go/kubernetes/typed/admissionregistration/v1"
admissionregistrationv1beta1 "k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1"
internalv1alpha1 "k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1"
appsv1 "k8s.io/client-go/kubernetes/typed/apps/v1"
appsv1beta1 "k8s.io/client-go/kubernetes/typed/apps/v1beta1"
appsv1beta2 "k8s.io/client-go/kubernetes/typed/apps/v1beta2"
authenticationv1 "k8s.io/client-go/kubernetes/typed/authentication/v1"
authenticationv1beta1 "k8s.io/client-go/kubernetes/typed/authentication/v1beta1"
authorizationv1 "k8s.io/client-go/kubernetes/typed/authorization/v1"
authorizationv1beta1 "k8s.io/client-go/kubernetes/typed/authorization/v1beta1"
autoscalingv1 "k8s.io/client-go/kubernetes/typed/autoscaling/v1"
autoscalingv2beta1 "k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1"
autoscalingv2beta2 "k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2"
batchv1 "k8s.io/client-go/kubernetes/typed/batch/v1"
batchv1beta1 "k8s.io/client-go/kubernetes/typed/batch/v1beta1"
certificatesv1 "k8s.io/client-go/kubernetes/typed/certificates/v1"
certificatesv1beta1 "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
coordinationv1 "k8s.io/client-go/kubernetes/typed/coordination/v1"
coordinationv1beta1 "k8s.io/client-go/kubernetes/typed/coordination/v1beta1"
discoveryv1 "k8s.io/client-go/kubernetes/typed/discovery/v1"
discoveryv1beta1 "k8s.io/client-go/kubernetes/typed/discovery/v1beta1"
eventsv1 "k8s.io/client-go/kubernetes/typed/events/v1"
eventsv1beta1 "k8s.io/client-go/kubernetes/typed/events/v1beta1"
extensionsv1beta1 "k8s.io/client-go/kubernetes/typed/extensions/v1beta1"
flowcontrolv1alpha1 "k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1"
flowcontrolv1beta1 "k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1"
networkingv1 "k8s.io/client-go/kubernetes/typed/networking/v1"
networkingv1beta1 "k8s.io/client-go/kubernetes/typed/networking/v1beta1"
nodev1 "k8s.io/client-go/kubernetes/typed/node/v1"
nodev1alpha1 "k8s.io/client-go/kubernetes/typed/node/v1alpha1"
nodev1beta1 "k8s.io/client-go/kubernetes/typed/node/v1beta1"
policyv1 "k8s.io/client-go/kubernetes/typed/policy/v1"
policyv1beta1 "k8s.io/client-go/kubernetes/typed/policy/v1beta1"
rbacv1 "k8s.io/client-go/kubernetes/typed/rbac/v1"
rbacv1alpha1 "k8s.io/client-go/kubernetes/typed/rbac/v1alpha1"
rbacv1beta1 "k8s.io/client-go/kubernetes/typed/rbac/v1beta1"
schedulingv1 "k8s.io/client-go/kubernetes/typed/scheduling/v1"
schedulingv1alpha1 "k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1"
schedulingv1beta1 "k8s.io/client-go/kubernetes/typed/scheduling/v1beta1"
storagev1 "k8s.io/client-go/kubernetes/typed/storage/v1"
storagev1alpha1 "k8s.io/client-go/kubernetes/typed/storage/v1alpha1"
storagev1beta1 "k8s.io/client-go/kubernetes/typed/storage/v1beta1"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
)
type Interface interface {
Discovery() discovery.DiscoveryInterface
AdmissionregistrationV1() admissionregistrationv1.AdmissionregistrationV1Interface
AdmissionregistrationV1beta1() admissionregistrationv1beta1.AdmissionregistrationV1beta1Interface
InternalV1alpha1() internalv1alpha1.InternalV1alpha1Interface
AppsV1() appsv1.AppsV1Interface
AppsV1beta1() appsv1beta1.AppsV1beta1Interface
AppsV1beta2() appsv1beta2.AppsV1beta2Interface
AuthenticationV1() authenticationv1.AuthenticationV1Interface
AuthenticationV1beta1() authenticationv1beta1.AuthenticationV1beta1Interface
AuthorizationV1() authorizationv1.AuthorizationV1Interface
AuthorizationV1beta1() authorizationv1beta1.AuthorizationV1beta1Interface
AutoscalingV1() autoscalingv1.AutoscalingV1Interface
AutoscalingV2beta1() autoscalingv2beta1.AutoscalingV2beta1Interface
AutoscalingV2beta2() autoscalingv2beta2.AutoscalingV2beta2Interface
BatchV1() batchv1.BatchV1Interface
BatchV1beta1() batchv1beta1.BatchV1beta1Interface
CertificatesV1() certificatesv1.CertificatesV1Interface
CertificatesV1beta1() certificatesv1beta1.CertificatesV1beta1Interface
CoordinationV1beta1() coordinationv1beta1.CoordinationV1beta1Interface
CoordinationV1() coordinationv1.CoordinationV1Interface
CoreV1() corev1.CoreV1Interface
DiscoveryV1() discoveryv1.DiscoveryV1Interface
DiscoveryV1beta1() discoveryv1beta1.DiscoveryV1beta1Interface
EventsV1() eventsv1.EventsV1Interface
EventsV1beta1() eventsv1beta1.EventsV1beta1Interface
ExtensionsV1beta1() extensionsv1beta1.ExtensionsV1beta1Interface
FlowcontrolV1alpha1() flowcontrolv1alpha1.FlowcontrolV1alpha1Interface
FlowcontrolV1beta1() flowcontrolv1beta1.FlowcontrolV1beta1Interface
NetworkingV1() networkingv1.NetworkingV1Interface
NetworkingV1beta1() networkingv1beta1.NetworkingV1beta1Interface
NodeV1() nodev1.NodeV1Interface
NodeV1alpha1() nodev1alpha1.NodeV1alpha1Interface
NodeV1beta1() nodev1beta1.NodeV1beta1Interface
PolicyV1() policyv1.PolicyV1Interface
PolicyV1beta1() policyv1beta1.PolicyV1beta1Interface
RbacV1() rbacv1.RbacV1Interface
RbacV1beta1() rbacv1beta1.RbacV1beta1Interface
RbacV1alpha1() rbacv1alpha1.RbacV1alpha1Interface
SchedulingV1alpha1() schedulingv1alpha1.SchedulingV1alpha1Interface
SchedulingV1beta1() schedulingv1beta1.SchedulingV1beta1Interface
SchedulingV1() schedulingv1.SchedulingV1Interface
StorageV1beta1() storagev1beta1.StorageV1beta1Interface
StorageV1() storagev1.StorageV1Interface
StorageV1alpha1() storagev1alpha1.StorageV1alpha1Interface
}
// Clientset contains the clients for groups. Each group has exactly one
// version included in a Clientset.
type Clientset struct {
*discovery.DiscoveryClient
admissionregistrationV1 *admissionregistrationv1.AdmissionregistrationV1Client
admissionregistrationV1beta1 *admissionregistrationv1beta1.AdmissionregistrationV1beta1Client
internalV1alpha1 *internalv1alpha1.InternalV1alpha1Client
appsV1 *appsv1.AppsV1Client
appsV1beta1 *appsv1beta1.AppsV1beta1Client
appsV1beta2 *appsv1beta2.AppsV1beta2Client
authenticationV1 *authenticationv1.AuthenticationV1Client
authenticationV1beta1 *authenticationv1beta1.AuthenticationV1beta1Client
authorizationV1 *authorizationv1.AuthorizationV1Client
authorizationV1beta1 *authorizationv1beta1.AuthorizationV1beta1Client
autoscalingV1 *autoscalingv1.AutoscalingV1Client
autoscalingV2beta1 *autoscalingv2beta1.AutoscalingV2beta1Client
autoscalingV2beta2 *autoscalingv2beta2.AutoscalingV2beta2Client
batchV1 *batchv1.BatchV1Client
batchV1beta1 *batchv1beta1.BatchV1beta1Client
certificatesV1 *certificatesv1.CertificatesV1Client
certificatesV1beta1 *certificatesv1beta1.CertificatesV1beta1Client
coordinationV1beta1 *coordinationv1beta1.CoordinationV1beta1Client
coordinationV1 *coordinationv1.CoordinationV1Client
coreV1 *corev1.CoreV1Client
discoveryV1 *discoveryv1.DiscoveryV1Client
discoveryV1beta1 *discoveryv1beta1.DiscoveryV1beta1Client
eventsV1 *eventsv1.EventsV1Client
eventsV1beta1 *eventsv1beta1.EventsV1beta1Client
extensionsV1beta1 *extensionsv1beta1.ExtensionsV1beta1Client
flowcontrolV1alpha1 *flowcontrolv1alpha1.FlowcontrolV1alpha1Client
flowcontrolV1beta1 *flowcontrolv1beta1.FlowcontrolV1beta1Client
networkingV1 *networkingv1.NetworkingV1Client
networkingV1beta1 *networkingv1beta1.NetworkingV1beta1Client
nodeV1 *nodev1.NodeV1Client
nodeV1alpha1 *nodev1alpha1.NodeV1alpha1Client
nodeV1beta1 *nodev1beta1.NodeV1beta1Client
policyV1 *policyv1.PolicyV1Client
policyV1beta1 *policyv1beta1.PolicyV1beta1Client
rbacV1 *rbacv1.RbacV1Client
rbacV1beta1 *rbacv1beta1.RbacV1beta1Client
rbacV1alpha1 *rbacv1alpha1.RbacV1alpha1Client
schedulingV1alpha1 *schedulingv1alpha1.SchedulingV1alpha1Client
schedulingV1beta1 *schedulingv1beta1.SchedulingV1beta1Client
schedulingV1 *schedulingv1.SchedulingV1Client
storageV1beta1 *storagev1beta1.StorageV1beta1Client
storageV1 *storagev1.StorageV1Client
storageV1alpha1 *storagev1alpha1.StorageV1alpha1Client
}
// AdmissionregistrationV1 retrieves the AdmissionregistrationV1Client
func (c *Clientset) AdmissionregistrationV1() admissionregistrationv1.AdmissionregistrationV1Interface {
return c.admissionregistrationV1
}
// AdmissionregistrationV1beta1 retrieves the AdmissionregistrationV1beta1Client
func (c *Clientset) AdmissionregistrationV1beta1() admissionregistrationv1beta1.AdmissionregistrationV1beta1Interface {
return c.admissionregistrationV1beta1
}
// InternalV1alpha1 retrieves the InternalV1alpha1Client
func (c *Clientset) InternalV1alpha1() internalv1alpha1.InternalV1alpha1Interface {
return c.internalV1alpha1
}
// AppsV1 retrieves the AppsV1Client
func (c *Clientset) AppsV1() appsv1.AppsV1Interface {
return c.appsV1
}
// AppsV1beta1 retrieves the AppsV1beta1Client
func (c *Clientset) AppsV1beta1() appsv1beta1.AppsV1beta1Interface {
return c.appsV1beta1
}
// AppsV1beta2 retrieves the AppsV1beta2Client
func (c *Clientset) AppsV1beta2() appsv1beta2.AppsV1beta2Interface {
return c.appsV1beta2
}
// AuthenticationV1 retrieves the AuthenticationV1Client
func (c *Clientset) AuthenticationV1() authenticationv1.AuthenticationV1Interface {
return c.authenticationV1
}
// AuthenticationV1beta1 retrieves the AuthenticationV1beta1Client
func (c *Clientset) AuthenticationV1beta1() authenticationv1beta1.AuthenticationV1beta1Interface {
return c.authenticationV1beta1
}
// AuthorizationV1 retrieves the AuthorizationV1Client
func (c *Clientset) AuthorizationV1() authorizationv1.AuthorizationV1Interface {
return c.authorizationV1
}
// AuthorizationV1beta1 retrieves the AuthorizationV1beta1Client
func (c *Clientset) AuthorizationV1beta1() authorizationv1beta1.AuthorizationV1beta1Interface {
return c.authorizationV1beta1
}
// AutoscalingV1 retrieves the AutoscalingV1Client
func (c *Clientset) AutoscalingV1() autoscalingv1.AutoscalingV1Interface {
return c.autoscalingV1
}
// AutoscalingV2beta1 retrieves the AutoscalingV2beta1Client
func (c *Clientset) AutoscalingV2beta1() autoscalingv2beta1.AutoscalingV2beta1Interface {
return c.autoscalingV2beta1
}
// AutoscalingV2beta2 retrieves the AutoscalingV2beta2Client
func (c *Clientset) AutoscalingV2beta2() autoscalingv2beta2.AutoscalingV2beta2Interface {
return c.autoscalingV2beta2
}
// BatchV1 retrieves the BatchV1Client
func (c *Clientset) BatchV1() batchv1.BatchV1Interface {
return c.batchV1
}
// BatchV1beta1 retrieves the BatchV1beta1Client
func (c *Clientset) BatchV1beta1() batchv1beta1.BatchV1beta1Interface {
return c.batchV1beta1
}
// CertificatesV1 retrieves the CertificatesV1Client
func (c *Clientset) CertificatesV1() certificatesv1.CertificatesV1Interface {
return c.certificatesV1
}
// CertificatesV1beta1 retrieves the CertificatesV1beta1Client
func (c *Clientset) CertificatesV1beta1() certificatesv1beta1.CertificatesV1beta1Interface {
return c.certificatesV1beta1
}
// CoordinationV1beta1 retrieves the CoordinationV1beta1Client
func (c *Clientset) CoordinationV1beta1() coordinationv1beta1.CoordinationV1beta1Interface {
return c.coordinationV1beta1
}
// CoordinationV1 retrieves the CoordinationV1Client
func (c *Clientset) CoordinationV1() coordinationv1.CoordinationV1Interface {
return c.coordinationV1
}
// CoreV1 retrieves the CoreV1Client
func (c *Clientset) CoreV1() corev1.CoreV1Interface {
return c.coreV1
}
// DiscoveryV1 retrieves the DiscoveryV1Client
func (c *Clientset) DiscoveryV1() discoveryv1.DiscoveryV1Interface {
return c.discoveryV1
}
// DiscoveryV1beta1 retrieves the DiscoveryV1beta1Client
func (c *Clientset) DiscoveryV1beta1() discoveryv1beta1.DiscoveryV1beta1Interface {
return c.discoveryV1beta1
}
// EventsV1 retrieves the EventsV1Client
func (c *Clientset) EventsV1() eventsv1.EventsV1Interface {
return c.eventsV1
}
// EventsV1beta1 retrieves the EventsV1beta1Client
func (c *Clientset) EventsV1beta1() eventsv1beta1.EventsV1beta1Interface {
return c.eventsV1beta1
}
// ExtensionsV1beta1 retrieves the ExtensionsV1beta1Client
func (c *Clientset) ExtensionsV1beta1() extensionsv1beta1.ExtensionsV1beta1Interface {
return c.extensionsV1beta1
}
// FlowcontrolV1alpha1 retrieves the FlowcontrolV1alpha1Client
func (c *Clientset) FlowcontrolV1alpha1() flowcontrolv1alpha1.FlowcontrolV1alpha1Interface {
return c.flowcontrolV1alpha1
}
// FlowcontrolV1beta1 retrieves the FlowcontrolV1beta1Client
func (c *Clientset) FlowcontrolV1beta1() flowcontrolv1beta1.FlowcontrolV1beta1Interface {
return c.flowcontrolV1beta1
}
// NetworkingV1 retrieves the NetworkingV1Client
func (c *Clientset) NetworkingV1() networkingv1.NetworkingV1Interface {
return c.networkingV1
}
// NetworkingV1beta1 retrieves the NetworkingV1beta1Client
func (c *Clientset) NetworkingV1beta1() networkingv1beta1.NetworkingV1beta1Interface {
return c.networkingV1beta1
}
// NodeV1 retrieves the NodeV1Client
func (c *Clientset) NodeV1() nodev1.NodeV1Interface {
return c.nodeV1
}
// NodeV1alpha1 retrieves the NodeV1alpha1Client
func (c *Clientset) NodeV1alpha1() nodev1alpha1.NodeV1alpha1Interface {
return c.nodeV1alpha1
}
// NodeV1beta1 retrieves the NodeV1beta1Client
func (c *Clientset) NodeV1beta1() nodev1beta1.NodeV1beta1Interface {
return c.nodeV1beta1
}
// PolicyV1 retrieves the PolicyV1Client
func (c *Clientset) PolicyV1() policyv1.PolicyV1Interface {
return c.policyV1
}
// PolicyV1beta1 retrieves the PolicyV1beta1Client
func (c *Clientset) PolicyV1beta1() policyv1beta1.PolicyV1beta1Interface {
return c.policyV1beta1
}
// RbacV1 retrieves the RbacV1Client
func (c *Clientset) RbacV1() rbacv1.RbacV1Interface {
return c.rbacV1
}
// RbacV1beta1 retrieves the RbacV1beta1Client
func (c *Clientset) RbacV1beta1() rbacv1beta1.RbacV1beta1Interface {
return c.rbacV1beta1
}
// RbacV1alpha1 retrieves the RbacV1alpha1Client
func (c *Clientset) RbacV1alpha1() rbacv1alpha1.RbacV1alpha1Interface {
return c.rbacV1alpha1
}
// SchedulingV1alpha1 retrieves the SchedulingV1alpha1Client
func (c *Clientset) SchedulingV1alpha1() schedulingv1alpha1.SchedulingV1alpha1Interface {
return c.schedulingV1alpha1
}
// SchedulingV1beta1 retrieves the SchedulingV1beta1Client
func (c *Clientset) SchedulingV1beta1() schedulingv1beta1.SchedulingV1beta1Interface {
return c.schedulingV1beta1
}
// SchedulingV1 retrieves the SchedulingV1Client
func (c *Clientset) SchedulingV1() schedulingv1.SchedulingV1Interface {
return c.schedulingV1
}
// StorageV1beta1 retrieves the StorageV1beta1Client
func (c *Clientset) StorageV1beta1() storagev1beta1.StorageV1beta1Interface {
return c.storageV1beta1
}
// StorageV1 retrieves the StorageV1Client
func (c *Clientset) StorageV1() storagev1.StorageV1Interface {
return c.storageV1
}
// StorageV1alpha1 retrieves the StorageV1alpha1Client
func (c *Clientset) StorageV1alpha1() storagev1alpha1.StorageV1alpha1Interface {
return c.storageV1alpha1
}
// Discovery retrieves the DiscoveryClient
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
if c == nil {
return nil
}
return c.DiscoveryClient
}
// NewForConfig creates a new Clientset for the given config.
// If config's RateLimiter is not set and QPS and Burst are acceptable,
// NewForConfig will generate a rate-limiter in configShallowCopy.
func NewForConfig(c *rest.Config) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
if configShallowCopy.Burst <= 0 {
return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0")
}
configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset
var err error
cs.admissionregistrationV1, err = admissionregistrationv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.admissionregistrationV1beta1, err = admissionregistrationv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.internalV1alpha1, err = internalv1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.appsV1, err = appsv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.appsV1beta1, err = appsv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.appsV1beta2, err = appsv1beta2.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.authenticationV1, err = authenticationv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.authenticationV1beta1, err = authenticationv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.authorizationV1, err = authorizationv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.authorizationV1beta1, err = authorizationv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.autoscalingV1, err = autoscalingv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.autoscalingV2beta1, err = autoscalingv2beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.autoscalingV2beta2, err = autoscalingv2beta2.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.batchV1, err = batchv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.batchV1beta1, err = batchv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.certificatesV1, err = certificatesv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.certificatesV1beta1, err = certificatesv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.coordinationV1beta1, err = coordinationv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.coordinationV1, err = coordinationv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.coreV1, err = corev1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.discoveryV1, err = discoveryv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.discoveryV1beta1, err = discoveryv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.eventsV1, err = eventsv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.eventsV1beta1, err = eventsv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.extensionsV1beta1, err = extensionsv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.flowcontrolV1alpha1, err = flowcontrolv1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.flowcontrolV1beta1, err = flowcontrolv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.networkingV1, err = networkingv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.networkingV1beta1, err = networkingv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.nodeV1, err = nodev1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.nodeV1alpha1, err = nodev1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.nodeV1beta1, err = nodev1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.policyV1, err = policyv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.policyV1beta1, err = policyv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.rbacV1, err = rbacv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.rbacV1beta1, err = rbacv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.rbacV1alpha1, err = rbacv1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.schedulingV1alpha1, err = schedulingv1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.schedulingV1beta1, err = schedulingv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.schedulingV1, err = schedulingv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.storageV1beta1, err = storagev1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.storageV1, err = storagev1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.storageV1alpha1, err = storagev1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
return &cs, nil
}
// NewForConfigOrDie creates a new Clientset for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *Clientset {
var cs Clientset
cs.admissionregistrationV1 = admissionregistrationv1.NewForConfigOrDie(c)
cs.admissionregistrationV1beta1 = admissionregistrationv1beta1.NewForConfigOrDie(c)
cs.internalV1alpha1 = internalv1alpha1.NewForConfigOrDie(c)
cs.appsV1 = appsv1.NewForConfigOrDie(c)
cs.appsV1beta1 = appsv1beta1.NewForConfigOrDie(c)
cs.appsV1beta2 = appsv1beta2.NewForConfigOrDie(c)
cs.authenticationV1 = authenticationv1.NewForConfigOrDie(c)
cs.authenticationV1beta1 = authenticationv1beta1.NewForConfigOrDie(c)
cs.authorizationV1 = authorizationv1.NewForConfigOrDie(c)
cs.authorizationV1beta1 = authorizationv1beta1.NewForConfigOrDie(c)
cs.autoscalingV1 = autoscalingv1.NewForConfigOrDie(c)
cs.autoscalingV2beta1 = autoscalingv2beta1.NewForConfigOrDie(c)
cs.autoscalingV2beta2 = autoscalingv2beta2.NewForConfigOrDie(c)
cs.batchV1 = batchv1.NewForConfigOrDie(c)
cs.batchV1beta1 = batchv1beta1.NewForConfigOrDie(c)
cs.certificatesV1 = certificatesv1.NewForConfigOrDie(c)
cs.certificatesV1beta1 = certificatesv1beta1.NewForConfigOrDie(c)
cs.coordinationV1beta1 = coordinationv1beta1.NewForConfigOrDie(c)
cs.coordinationV1 = coordinationv1.NewForConfigOrDie(c)
cs.coreV1 = corev1.NewForConfigOrDie(c)
cs.discoveryV1 = discoveryv1.NewForConfigOrDie(c)
cs.discoveryV1beta1 = discoveryv1beta1.NewForConfigOrDie(c)
cs.eventsV1 = eventsv1.NewForConfigOrDie(c)
cs.eventsV1beta1 = eventsv1beta1.NewForConfigOrDie(c)
cs.extensionsV1beta1 = extensionsv1beta1.NewForConfigOrDie(c)
cs.flowcontrolV1alpha1 = flowcontrolv1alpha1.NewForConfigOrDie(c)
cs.flowcontrolV1beta1 = flowcontrolv1beta1.NewForConfigOrDie(c)
cs.networkingV1 = networkingv1.NewForConfigOrDie(c)
cs.networkingV1beta1 = networkingv1beta1.NewForConfigOrDie(c)
cs.nodeV1 = nodev1.NewForConfigOrDie(c)
cs.nodeV1alpha1 = nodev1alpha1.NewForConfigOrDie(c)
cs.nodeV1beta1 = nodev1beta1.NewForConfigOrDie(c)
cs.policyV1 = policyv1.NewForConfigOrDie(c)
cs.policyV1beta1 = policyv1beta1.NewForConfigOrDie(c)
cs.rbacV1 = rbacv1.NewForConfigOrDie(c)
cs.rbacV1beta1 = rbacv1beta1.NewForConfigOrDie(c)
cs.rbacV1alpha1 = rbacv1alpha1.NewForConfigOrDie(c)
cs.schedulingV1alpha1 = schedulingv1alpha1.NewForConfigOrDie(c)
cs.schedulingV1beta1 = schedulingv1beta1.NewForConfigOrDie(c)
cs.schedulingV1 = schedulingv1.NewForConfigOrDie(c)
cs.storageV1beta1 = storagev1beta1.NewForConfigOrDie(c)
cs.storageV1 = storagev1.NewForConfigOrDie(c)
cs.storageV1alpha1 = storagev1alpha1.NewForConfigOrDie(c)
cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
return &cs
}
// New creates a new Clientset for the given RESTClient.
func New(c rest.Interface) *Clientset {
var cs Clientset
cs.admissionregistrationV1 = admissionregistrationv1.New(c)
cs.admissionregistrationV1beta1 = admissionregistrationv1beta1.New(c)
cs.internalV1alpha1 = internalv1alpha1.New(c)
cs.appsV1 = appsv1.New(c)
cs.appsV1beta1 = appsv1beta1.New(c)
cs.appsV1beta2 = appsv1beta2.New(c)
cs.authenticationV1 = authenticationv1.New(c)
cs.authenticationV1beta1 = authenticationv1beta1.New(c)
cs.authorizationV1 = authorizationv1.New(c)
cs.authorizationV1beta1 = authorizationv1beta1.New(c)
cs.autoscalingV1 = autoscalingv1.New(c)
cs.autoscalingV2beta1 = autoscalingv2beta1.New(c)
cs.autoscalingV2beta2 = autoscalingv2beta2.New(c)
cs.batchV1 = batchv1.New(c)
cs.batchV1beta1 = batchv1beta1.New(c)
cs.certificatesV1 = certificatesv1.New(c)
cs.certificatesV1beta1 = certificatesv1beta1.New(c)
cs.coordinationV1beta1 = coordinationv1beta1.New(c)
cs.coordinationV1 = coordinationv1.New(c)
cs.coreV1 = corev1.New(c)
cs.discoveryV1 = discoveryv1.New(c)
cs.discoveryV1beta1 = discoveryv1beta1.New(c)
cs.eventsV1 = eventsv1.New(c)
cs.eventsV1beta1 = eventsv1beta1.New(c)
cs.extensionsV1beta1 = extensionsv1beta1.New(c)
cs.flowcontrolV1alpha1 = flowcontrolv1alpha1.New(c)
cs.flowcontrolV1beta1 = flowcontrolv1beta1.New(c)
cs.networkingV1 = networkingv1.New(c)
cs.networkingV1beta1 = networkingv1beta1.New(c)
cs.nodeV1 = nodev1.New(c)
cs.nodeV1alpha1 = nodev1alpha1.New(c)
cs.nodeV1beta1 = nodev1beta1.New(c)
cs.policyV1 = policyv1.New(c)
cs.policyV1beta1 = policyv1beta1.New(c)
cs.rbacV1 = rbacv1.New(c)
cs.rbacV1beta1 = rbacv1beta1.New(c)
cs.rbacV1alpha1 = rbacv1alpha1.New(c)
cs.schedulingV1alpha1 = schedulingv1alpha1.New(c)
cs.schedulingV1beta1 = schedulingv1beta1.New(c)
cs.schedulingV1 = schedulingv1.New(c)
cs.storageV1beta1 = storagev1beta1.New(c)
cs.storageV1 = storagev1.New(c)
cs.storageV1alpha1 = storagev1alpha1.New(c)
cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
return &cs
}

View File

@ -1,90 +0,0 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
type CoreV1Interface interface {
RESTClient() rest.Interface
PodsGetter
}
// CoreV1Client is used to interact with features provided by the group.
type CoreV1Client struct {
restClient rest.Interface
}
func (c *CoreV1Client) Pods(namespace string) PodInterface {
//TODO implement me
return newPods(c, namespace)
}
// NewForConfig creates a new CoreV1Client for the given config.
func NewForConfig(c *rest.Config) (*CoreV1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &CoreV1Client{client}, nil
}
// NewForConfigOrDie creates a new CoreV1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *CoreV1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new CoreV1Client for the given RESTClient.
func New(c rest.Interface) *CoreV1Client {
return &CoreV1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/api"
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *CoreV1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}

View File

@ -1,537 +0,0 @@
package v1
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/server/kubernetes/api/core/v1"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
pbtenant "code.gitlink.org.cn/JCCE/PCM.git/tenant/gen/idl"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"strconv"
"time"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/applyconfigurations/core/v1"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
)
// PodsGetter has a method to return a PodInterface.
// A group's client should implement this interface.
type PodsGetter interface {
Pods(namespace string) PodInterface
}
// PodInterface has methods to work with Pod resources.
type PodInterface interface {
Create(ctx context.Context, pod *v1.Pod, opts metav1.CreateOptions) (*v1.Pod, error)
Update(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (*v1.Pod, error)
UpdateStatus(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (*v1.Pod, error)
Delete(ctx context.Context, namespace string, providerId int32, regionName string, accountName string, pcmId string, opts metav1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error
Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Pod, error)
List(ctx context.Context, pod *v1.Pod, opts metav1.ListOptions) (*v1.PodList, error)
Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pod, err error)
Apply(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error)
ApplyStatus(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error)
GetEphemeralContainers(ctx context.Context, podName string, options metav1.GetOptions) (*v1.EphemeralContainers, error)
UpdateEphemeralContainers(ctx context.Context, podName string, ephemeralContainers *v1.EphemeralContainers, opts metav1.UpdateOptions) (*v1.EphemeralContainers, error)
PodExpansion
}
// pods implements PodInterface
type pods struct {
client rest.Interface
ns string
}
// newPods returns a Pods
func newPods(c *CoreV1Client, namespace string) *pods {
return &pods{
client: c.RESTClient(),
ns: namespace,
}
}
// Get takes name of the pcm_pod, and returns the corresponding pcm_pod object, and an error if there is any.
func (c *pods) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Pod, err error) {
result = &v1.Pod{}
err = c.client.Get().
Namespace(c.ns).
Resource("pods").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of Pods that match those selectors.
func (c *pods) List(ctx context.Context, pod *v1.Pod, opts metav1.ListOptions) (result *v1.PodList, err error) {
providerId := pod.Spec.ProviderId
regionId := pod.Spec.RegionId
accountName := pod.Spec.AccountName
provider := pbtenant.CloudProvider(providerId)
requestPCM := &pbpod.ListPodReq{
RequestSource: "huawei",
Provider: pbpod.CloudProvider(provider),
Namespace: "pcm",
}
resp, err := server.ListPod(nil, requestPCM)
//trans PCM response pcm_pod set to Ali ContainerGroup set
var pods = make([]v1.Pod, len(resp.Pods))
for k := range resp.Pods {
podId := resp.Pods[k].PodId
containerName := resp.Pods[k].ContainerName
containerImage := resp.Pods[k].ContainerImage
podName := resp.Pods[k].PodName
container := v1.Container{
Name: containerName,
Image: containerImage,
}
var containers []v1.Container
containers = append(containers, container)
podSpec := v1.PodSpec{
ProviderId: providerId,
RegionId: regionId,
AccountName: accountName,
Containers: containers,
}
pod := v1.Pod{
TypeMeta: metav1.TypeMeta{APIVersion: "core/V1", Kind: "Pod"},
ObjectMeta: metav1.ObjectMeta{Name: podName, Namespace: "pcm", UID: types.UID(podId)},
Spec: podSpec,
Status: v1.PodStatus{},
}
pods[k] = pod
}
result = &v1.PodList{
TypeMeta: metav1.TypeMeta{},
ListMeta: metav1.ListMeta{},
Items: pods,
}
return
}
// Watch returns a watch.Interface that watches the requested pods.
func (c *pods) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Namespace(c.ns).
Resource("pods").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a pcm_pod and creates it. Returns the server's representation of the pcm_pod, and an error, if there is any.
func (c *pods) Create(ctx context.Context, pod *v1.Pod, opts metav1.CreateOptions) (result *v1.Pod, err error) {
result = &v1.Pod{}
provider := pbtenant.CloudProvider(pod.Spec.ProviderId)
var configFile string
flag.StringVar(&configFile, "conf", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
tenanters, err := tenanter.GetTenanters(provider)
var regionId int32
var cpuPod string
var memoryPod string
//华为(K8S)与其他厂商的CPU单位和格式有区别,region根据字符串取各厂商的对应id
switch pod.Spec.ProviderId {
case 0:
regionId, _ = tenanter.GetAliRegionId(pod.Spec.RegionId)
cpuPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Cpu().MilliValue()/1000, 10)
memoryPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Memory().MilliValue()/1024/1024/1024/1000, 10)
case 1:
regionId, _ = tenanter.GetTencentRegionId(pod.Spec.RegionId)
cpuPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Cpu().MilliValue()/1000, 10)
memoryPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Memory().MilliValue()/1024/1024/1024/1000, 10)
case 2:
regionId, _ = tenanter.GetHuaweiRegionId(pod.Spec.RegionId)
cpuPod = pod.Spec.Containers[0].Resources.Limits.Cpu().String()
memoryPod = pod.Spec.Containers[0].Resources.Limits.Memory().String()
case 3:
regionId, _ = tenanter.GetK8SRegionId(pod.Spec.RegionId)
cpuPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Cpu().MilliValue()/1000, 10)
memoryPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Memory().MilliValue()/1024/1024/1024/1000, 10)
}
requestPCM := &pbpod.CreatePodReq{
RequestSource: "huawei",
Provider: pbpod.CloudProvider(provider),
AccountName: tenanters[0].AccountName(),
PodName: pod.Name,
RegionId: regionId,
ContainerImage: pod.Spec.Containers[0].Image,
ContainerName: pod.Spec.Containers[0].Name,
CpuPod: cpuPod,
MemoryPod: memoryPod,
//这里腾讯需要独立提供三个参数,目前固定使用以下三个
SecurityGroupId: "sg-6qlun7hd",
SubnetId: "subnet-mnwfg2fk",
VpcId: "vpc-rkwt40g5",
Namespace: pod.ObjectMeta.Namespace,
}
server.CreatePod(nil, requestPCM)
result = &v1.Pod{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{},
Spec: v1.PodSpec{
ProviderId: pod.Spec.ProviderId,
RegionId: pod.Spec.RegionId,
AccountName: pod.Spec.AccountName,
Volumes: nil,
InitContainers: nil,
Containers: pod.Spec.Containers,
},
Status: v1.PodStatus{
Phase: "",
Conditions: nil,
Message: "",
Reason: "",
NominatedNodeName: "",
HostIP: "",
PodIP: "",
PodIPs: nil,
StartTime: nil,
InitContainerStatuses: nil,
ContainerStatuses: nil,
QOSClass: "",
EphemeralContainerStatuses: nil,
},
}
return
}
// Update takes the representation of a pcm_pod and updates it. Returns the server's representation of the pcm_pod, and an error, if there is any.
func (c *pods) Update(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error) {
result = &v1.Pod{}
provider := pbtenant.CloudProvider(pod.Spec.ProviderId)
var configFile string
flag.StringVar(&configFile, "confHuawei", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
tenanters, err := tenanter.GetTenanters(provider)
var regionId int32
var cpuPod string
var memoryPod string
//华为(K8S)与其他厂商的CPU单位和格式有区别
switch pod.Spec.ProviderId {
case 0:
regionId, _ = tenanter.GetAliRegionId(pod.Spec.RegionId)
cpuPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Cpu().MilliValue()/1000, 10)
memoryPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Memory().MilliValue()/1024/1024/1024/1000, 10)
case 1:
regionId, _ = tenanter.GetTencentRegionId(pod.Spec.RegionId)
cpuPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Cpu().MilliValue()/1000, 10)
memoryPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Memory().MilliValue()/1024/1024/1024/1000, 10)
case 2:
regionId, _ = tenanter.GetHuaweiRegionId(pod.Spec.RegionId)
cpuPod = pod.Spec.Containers[0].Resources.Limits.Cpu().String()
memoryPod = pod.Spec.Containers[0].Resources.Limits.Memory().String()
case 3:
regionId, _ = tenanter.GetK8SRegionId(pod.Spec.RegionId)
cpuPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Cpu().MilliValue()/1000, 10)
memoryPod = strconv.FormatInt(pod.Spec.Containers[0].Resources.Limits.Memory().MilliValue()/1024/1024/1024/1000, 10)
}
requestPCM := &pbpod.UpdatePodReq{
RequestSource: "huawei",
Provider: pbpod.CloudProvider(provider),
PcmId: string(pod.ObjectMeta.UID),
PodId: string(pod.ObjectMeta.UID),
AccountName: tenanters[0].AccountName(),
PodName: pod.Name,
RegionId: regionId,
ContainerImage: pod.Spec.Containers[0].Image,
ContainerName: pod.Spec.Containers[0].Name,
CpuPod: cpuPod,
MemoryPod: memoryPod,
Namespace: pod.ObjectMeta.Namespace,
}
server.UpdatePod(nil, requestPCM)
result = &v1.Pod{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{},
Spec: v1.PodSpec{
ProviderId: pod.Spec.ProviderId,
RegionId: pod.Spec.RegionId,
AccountName: pod.Spec.AccountName,
Volumes: nil,
InitContainers: nil,
Containers: pod.Spec.Containers,
EphemeralContainers: nil,
RestartPolicy: "",
TerminationGracePeriodSeconds: nil,
ActiveDeadlineSeconds: nil,
DNSPolicy: "",
NodeSelector: nil,
ServiceAccountName: "",
DeprecatedServiceAccount: "",
AutomountServiceAccountToken: nil,
NodeName: "",
HostNetwork: false,
HostPID: false,
HostIPC: false,
ShareProcessNamespace: nil,
SecurityContext: nil,
ImagePullSecrets: nil,
Hostname: "",
Subdomain: "",
Affinity: nil,
SchedulerName: "",
Tolerations: nil,
HostAliases: nil,
PriorityClassName: "",
Priority: nil,
DNSConfig: nil,
ReadinessGates: nil,
RuntimeClassName: nil,
EnableServiceLinks: nil,
PreemptionPolicy: nil,
Overhead: nil,
TopologySpreadConstraints: nil,
SetHostnameAsFQDN: nil,
},
Status: v1.PodStatus{
Phase: "",
Conditions: nil,
Message: "",
Reason: "",
NominatedNodeName: "",
HostIP: "",
PodIP: "",
PodIPs: nil,
StartTime: nil,
InitContainerStatuses: nil,
ContainerStatuses: nil,
QOSClass: "",
EphemeralContainerStatuses: nil,
},
}
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *pods) UpdateStatus(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error) {
result = &v1.Pod{}
err = c.client.Put().
Namespace(c.ns).
Resource("pods").
Name(pod.Name).
SubResource("status").
VersionedParams(&opts, scheme.ParameterCodec).
Body(pod).
Do(ctx).
Into(result)
return
}
// Delete takes name of the pcm_pod and deletes it. Returns an error if one occurs.
func (c *pods) Delete(ctx context.Context, namespace string, providerId int32, regionName string, accountName string, pcmId string, opts metav1.DeleteOptions) error {
provider := pbtenant.CloudProvider(providerId)
var configFile string
flag.StringVar(&configFile, "confHuawei", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
var regionId int32
switch providerId {
case 0:
regionId, _ = tenanter.GetAliRegionId(regionName)
case 1:
regionId, _ = tenanter.GetTencentRegionId(regionName)
case 2:
regionId, _ = tenanter.GetHuaweiRegionId(regionName)
case 3:
regionId, _ = tenanter.GetK8SRegionId(regionName)
}
requestPCM := &pbpod.DeletePodReq{
RequestSource: "huawei",
Provider: pbpod.CloudProvider(provider),
AccountName: accountName,
PcmId: pcmId,
Namespace: namespace,
RegionId: regionId,
}
_, err := server.DeletePod(nil, requestPCM)
if err != nil {
return err
}
return nil
}
// DeleteCollection deletes a collection of objects.
func (c *pods) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Namespace(c.ns).
Resource("pods").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched pcm_pod.
func (c *pods) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pod, err error) {
result = &v1.Pod{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("pods").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}
// Apply takes the given apply declarative configuration, applies it and returns the applied pcm_pod.
func (c *pods) Apply(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error) {
if pod == nil {
return nil, fmt.Errorf("pcm_pod provided to Apply must not be nil")
}
patchOpts := opts.ToPatchOptions()
data, err := json.Marshal(pod)
if err != nil {
return nil, err
}
name := pod.Name
if name == nil {
return nil, fmt.Errorf("pcm_pod.Name must be provided to Apply")
}
result = &v1.Pod{}
err = c.client.Patch(types.ApplyPatchType).
Namespace(c.ns).
Resource("pods").
Name(*name).
VersionedParams(&patchOpts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}
// ApplyStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().
func (c *pods) ApplyStatus(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error) {
if pod == nil {
return nil, fmt.Errorf("pcm_pod provided to Apply must not be nil")
}
patchOpts := opts.ToPatchOptions()
data, err := json.Marshal(pod)
if err != nil {
return nil, err
}
name := pod.Name
if name == nil {
return nil, fmt.Errorf("pcm_pod.Name must be provided to Apply")
}
result = &v1.Pod{}
err = c.client.Patch(types.ApplyPatchType).
Namespace(c.ns).
Resource("pods").
Name(*name).
SubResource("status").
VersionedParams(&patchOpts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}
// GetEphemeralContainers takes name of the pcm_pod, and returns the corresponding v1.EphemeralContainers object, and an error if there is any.
func (c *pods) GetEphemeralContainers(ctx context.Context, podName string, options metav1.GetOptions) (result *v1.EphemeralContainers, err error) {
result = &v1.EphemeralContainers{}
err = c.client.Get().
Namespace(c.ns).
Resource("pods").
Name(podName).
SubResource("ephemeralcontainers").
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// UpdateEphemeralContainers takes the top resource name and the representation of a ephemeralContainers and updates it. Returns the server's representation of the ephemeralContainers, and an error, if there is any.
func (c *pods) UpdateEphemeralContainers(ctx context.Context, podName string, ephemeralContainers *v1.EphemeralContainers, opts metav1.UpdateOptions) (result *v1.EphemeralContainers, err error) {
result = &v1.EphemeralContainers{}
err = c.client.Put().
Namespace(c.ns).
Resource("pods").
Name(podName).
SubResource("ephemeralcontainers").
VersionedParams(&opts, scheme.ParameterCodec).
Body(ephemeralContainers).
Do(ctx).
Into(result)
return
}

View File

@ -1,64 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"context"
v1 "k8s.io/api/core/v1"
policy "k8s.io/api/policy/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/net"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
)
// The PodExpansion interface allows manually adding extra methods to the PodInterface.
type PodExpansion interface {
Bind(ctx context.Context, binding *v1.Binding, opts metav1.CreateOptions) error
Evict(ctx context.Context, eviction *policy.Eviction) error
GetLogs(name string, opts *v1.PodLogOptions) *restclient.Request
ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper
}
// Bind applies the provided binding to the named pcm_pod in the current namespace (binding.Namespace is ignored).
func (c *pods) Bind(ctx context.Context, binding *v1.Binding, opts metav1.CreateOptions) error {
return c.client.Post().Namespace(c.ns).Resource("pods").Name(binding.Name).VersionedParams(&opts, scheme.ParameterCodec).SubResource("binding").Body(binding).Do(ctx).Error()
}
func (c *pods) Evict(ctx context.Context, eviction *policy.Eviction) error {
return c.client.Post().Namespace(c.ns).Resource("pods").Name(eviction.Name).SubResource("eviction").Body(eviction).Do(ctx).Error()
}
// Get constructs a request for getting the logs for a pcm_pod
func (c *pods) GetLogs(name string, opts *v1.PodLogOptions) *restclient.Request {
return c.client.Get().Namespace(c.ns).Name(name).Resource("pods").SubResource("log").VersionedParams(opts, scheme.ParameterCodec)
}
// ProxyGet returns a response of the pcm_pod by calling it through the proxy.
func (c *pods) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper {
request := c.client.Get().
Namespace(c.ns).
Resource("pods").
SubResource("proxy").
Name(net.JoinSchemeNamePort(scheme, name, port)).
Suffix(path)
for k, v := range params {
request = request.Param(k, v)
}
return request
}

View File

@ -1,91 +0,0 @@
package server
import (
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"context"
"github.com/golang/glog"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Server struct {
podpb.UnimplementedPodServiceServer
}
// GetProdRegions get available region for product
func (s *Server) GetProdRegions(ctx context.Context, req *podpb.GetPodRegionReq) (*podpb.GetPodRegionResp, error) {
resp, err := GetPodRegion(ctx, req)
if err != nil {
glog.Errorf("CreatePods error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// CreatePods create multiple pcm_pod on multiple clouds
func (s *Server) CreatePods(ctx context.Context, req *podpb.CreatePodsReq) (*podpb.CreatePodsResp, error) {
resp, err := CreatePods(ctx, req)
if err != nil {
glog.Errorf("CreatePods error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// CreatePod create pcm_pod on one cloud
func (s *Server) CreatePod(ctx context.Context, req *podpb.CreatePodReq) (*podpb.CreatePodResp, error) {
resp, err := CreatePod(ctx, req)
if err != nil {
glog.Errorf("CreatePod error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// DeletePod delete specified pcm_pod
func (s *Server) DeletePod(ctx context.Context, req *podpb.DeletePodReq) (*podpb.DeletePodResp, error) {
resp, err := DeletePod(ctx, req)
if err != nil {
glog.Errorf("DeletePod error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// UpdatePod update specified pcm_pod
func (s *Server) UpdatePod(ctx context.Context, req *podpb.UpdatePodReq) (*podpb.UpdatePodResp, error) {
resp, err := UpdatePod(ctx, req)
if err != nil {
glog.Errorf("UpdatePod error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) ListPodDetail(ctx context.Context, req *podpb.ListPodDetailReq) (*podpb.ListPodDetailResp, error) {
resp, err := ListPodDetail(ctx, req)
if err != nil {
glog.Errorf("ListPodDetail error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) ListPod(ctx context.Context, req *podpb.ListPodReq) (*podpb.ListPodResp, error) {
resp, err := ListPod(ctx, req)
if err != nil {
glog.Errorf("ListPod error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) ListPodAll(ctx context.Context, req *podpb.ListPodAllReq) (*podpb.ListPodResp, error) {
resp, err := ListPodAll(ctx)
if err != nil {
glog.Errorf("ListPodAll error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}

View File

@ -1,350 +0,0 @@
package server
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/service"
pbtenant "code.gitlink.org.cn/JCCE/PCM.git/tenant/gen/idl"
"context"
"flag"
"fmt"
"sync"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"github.com/golang/glog"
"github.com/pkg/errors"
)
// GetPodRegion get the available region for pcm_pod
func GetPodRegion(ctx context.Context, req *pbpod.GetPodRegionReq) (resp *pbpod.GetPodRegionResp, err error) {
var (
regionInit tenanter.Region
regions []*pbpod.Region
)
switch req.GetProvider() {
case pbpod.CloudProvider_ali:
regionInit, _ = tenanter.NewRegion(pbtenant.CloudProvider(req.GetProvider()), 2)
case pbpod.CloudProvider_tencent:
regionInit, _ = tenanter.NewRegion(pbtenant.CloudProvider(req.GetProvider()), 5)
case pbpod.CloudProvider_huawei:
regionInit, _ = tenanter.NewRegion(pbtenant.CloudProvider(req.GetProvider()), 5)
}
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.GetProvider()))
if err != nil {
return nil, errors.WithMessage(err, "getTenanters error")
}
for _, tenant := range tenanters {
pod, err := poder.NewPodClient(req.GetProvider(), regionInit, tenant)
if err != nil {
return nil, errors.WithMessage(err, "NewPodClient error")
}
request := &pbpod.GetPodRegionReq{
Provider: req.GetProvider(),
}
resp, err := pod.GetPodRegion(ctx, request)
if err != nil {
return nil, errors.Wrap(err, "GetPodRegion error")
}
for _, region := range resp.GetRegions() {
regions = append(regions, region)
}
}
return &pbpod.GetPodRegionResp{Regions: regions}, nil
}
func CreatePods(ctx context.Context, req *pbpod.CreatePodsReq) (*pbpod.CreatePodsResp, error) {
var (
wg sync.WaitGroup
requestIds = make([]string, 0)
)
wg.Add(len(req.CreatePodReq))
c := make(chan string)
for k := range req.CreatePodReq {
reqPod := req.CreatePodReq[k]
go func() {
defer wg.Done()
resp, err := CreatePod(ctx, reqPod)
if err != nil || resp == nil {
fmt.Println(errors.Wrap(err, "Batch pcm_pod creation error"))
return
}
c <- resp.RequestId
}()
}
go func() {
defer close(c)
wg.Wait()
}()
isFinished := false
if len(requestIds) > 0 {
isFinished = true
}
for v := range c {
requestIds = append(requestIds, v)
}
return &pbpod.CreatePodsResp{
Finished: isFinished,
RequestId: requestIds,
}, nil
}
func CreatePod(ctx context.Context, req *pbpod.CreatePodReq) (*pbpod.CreatePodResp, error) {
var (
pod poder.Poder
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
if err != nil {
return nil, errors.WithMessage(err, "getTenanters error")
}
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.WithMessagef(err, "provider %v regionId %v", req.Provider, req.RegionId)
}
for _, tenant := range tenanters {
if req.AccountName == "" || tenant.AccountName() == req.AccountName {
if pod, err = poder.NewPodClient(req.Provider, region, tenant); err != nil {
return nil, errors.WithMessage(err, "NewPodClient error")
}
break
}
}
return pod.CreatePod(ctx, req)
}
func DeletePod(ctx context.Context, req *pbpod.DeletePodReq) (*pbpod.DeletePodResp, error) {
var (
pod poder.Poder
)
//pcm adk过来的请求需要从用户本地读取配置文件
if len(req.RequestSource) > 0 {
var configFile string
flag.StringVar(&configFile, "conf", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
}
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
if err != nil {
return nil, errors.WithMessage(err, "getTenanters error")
}
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.WithMessagef(err, "provider %v regionId %v", pbtenant.CloudProvider(req.Provider), req.RegionId)
}
for _, tenant := range tenanters {
if req.AccountName == "" || tenant.AccountName() == req.AccountName {
if pod, err = poder.NewPodClient(req.Provider, region, tenant); err != nil {
return nil, errors.WithMessage(err, "NewPodClient error")
}
break
}
}
return pod.DeletePod(ctx, req)
}
func UpdatePod(ctx context.Context, req *pbpod.UpdatePodReq) (*pbpod.UpdatePodResp, error) {
var (
pod poder.Poder
)
//pcm adk过来的请求需要从用户本地读取配置文件
if len(req.RequestSource) > 0 {
var configFile string
flag.StringVar(&configFile, "conf", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
}
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
if err != nil {
return nil, errors.WithMessage(err, "getTenanters error")
}
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.WithMessagef(err, "provider %v regionId %v", req.Provider, req.RegionId)
}
for _, tenant := range tenanters {
if req.AccountName == "" || tenant.AccountName() == req.AccountName {
if pod, err = poder.NewPodClient(req.Provider, region, tenant); err != nil {
return nil, errors.WithMessage(err, "NewPodClient error")
}
break
}
}
return pod.UpdatePod(ctx, req)
}
func ListPodDetail(ctx context.Context, req *pbpod.ListPodDetailReq) (*pbpod.ListPodDetailResp, error) {
var (
pod poder.Poder
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
if err != nil {
return nil, errors.WithMessage(err, "getTenanters error")
}
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.WithMessagef(err, "provider %v regionId %v", req.Provider, req.RegionId)
}
for _, tenant := range tenanters {
if req.AccountName == "" || tenant.AccountName() == req.AccountName {
if pod, err = poder.NewPodClient(req.Provider, region, tenant); err != nil {
return nil, errors.WithMessage(err, "NewPodClient error")
}
break
}
}
return pod.ListPodDetail(ctx, req)
}
func ListPod(ctx context.Context, req *pbpod.ListPodReq) (*pbpod.ListPodResp, error) {
var (
wg sync.WaitGroup
mutex sync.Mutex
pods []*pbpod.PodInstance
tenanters []tenanter.Tenanter
)
//pcm adk过来的请求需要从用户本地读取配置文件
if len(req.RequestSource) > 0 {
var configFile string
flag.StringVar(&configFile, "conf", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("tenanter.LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("tenanter.LoadCloudConfigsFromFile empty file path %s", configFile)
}
glog.Infof("load tenant from file finished")
}
tenanters, _ = tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
//get the available region for product
reqPodRegion := &pbpod.GetPodRegionReq{Provider: req.GetProvider()}
respPodRegion, err := GetPodRegion(ctx, reqPodRegion)
if err != nil {
return nil, errors.WithMessage(err, "getPodRegion error")
}
wg.Add(len(tenanters) * len(respPodRegion.Regions))
for _, t := range tenanters {
for _, region := range respPodRegion.Regions {
go func(tenant tenanter.Tenanter, region tenanter.Region) {
defer wg.Done()
pod, err := poder.NewPodClient(req.Provider, region, tenant)
if err != nil {
glog.Errorf("New Pod Client error %v", err)
return
}
request := &pbpod.ListPodDetailReq{
Provider: req.Provider,
AccountName: tenant.AccountName(),
RegionId: region.GetId(),
Namespace: req.Namespace,
PageNumber: 1,
PageSize: 100,
NextToken: "",
}
for {
resp, err := pod.ListPodDetail(ctx, request)
if err != nil {
glog.Errorf("ListDetail error %v", err)
return
}
mutex.Lock()
pods = append(pods, resp.Pods...)
mutex.Unlock()
if resp.Finished {
break
}
request.PageNumber, request.PageSize, request.NextToken = resp.PageNumber, resp.PageSize, resp.NextToken
}
}(t, region)
}
}
wg.Wait()
return &pbpod.ListPodResp{Pods: pods}, nil
}
func ListPodAll(ctx context.Context) (*pbpod.ListPodResp, error) {
var (
wg sync.WaitGroup
mutex sync.Mutex
pods []*pbpod.PodInstance
)
wg.Add(len(pbpod.CloudProvider_name))
for k := range pbpod.CloudProvider_name {
go func(provider int32) {
defer wg.Done()
//针对私有K8S集群调用listAll时默认只查询ListPodDetailReq namespace下的pod
if provider == 3 {
resp, err := ListPod(ctx, &pbpod.ListPodReq{Provider: pbpod.CloudProvider(provider), Namespace: "pcm"})
if err != nil {
glog.Errorf("List error %v", err)
return
}
mutex.Lock()
pods = append(pods, resp.Pods...)
mutex.Unlock()
} else {
resp, err := ListPod(ctx, &pbpod.ListPodReq{Provider: pbpod.CloudProvider(provider)})
if err != nil {
glog.Errorf("List error %v", err)
return
}
mutex.Lock()
pods = append(pods, resp.Pods...)
mutex.Unlock()
}
}(k)
}
wg.Wait()
return &pbpod.ListPodResp{Pods: pods}, nil
}

File diff suppressed because it is too large Load Diff

View File

@ -1,343 +0,0 @@
// Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v20180525
const (
// 此产品的特有错误码
// 操作失败。
FAILEDOPERATION = "FailedOperation"
// 子账户RBAC权限不足。
FAILEDOPERATION_RBACFORBIDDEN = "FailedOperation.RBACForbidden"
// 内部错误。
INTERNALERROR = "InternalError"
// 获取用户认证信息失败。
INTERNALERROR_ACCOUNTCOMMON = "InternalError.AccountCommon"
// 账户未通过认证。
INTERNALERROR_ACCOUNTUSERNOTAUTHENTICATED = "InternalError.AccountUserNotAuthenticated"
// 伸缩组资源创建报错。
INTERNALERROR_ASCOMMON = "InternalError.AsCommon"
// 没有权限。
INTERNALERROR_CAMNOAUTH = "InternalError.CamNoAuth"
// CIDR和其他集群CIDR冲突。
INTERNALERROR_CIDRCONFLICTWITHOTHERCLUSTER = "InternalError.CidrConflictWithOtherCluster"
// CIDR和其他路由冲突。
INTERNALERROR_CIDRCONFLICTWITHOTHERROUTE = "InternalError.CidrConflictWithOtherRoute"
// CIDR和vpc冲突。
INTERNALERROR_CIDRCONFLICTWITHVPCCIDR = "InternalError.CidrConflictWithVpcCidr"
// CIDR和全局路由冲突。
INTERNALERROR_CIDRCONFLICTWITHVPCGLOBALROUTE = "InternalError.CidrConflictWithVpcGlobalRoute"
// CIDR无效。
INTERNALERROR_CIDRINVALI = "InternalError.CidrInvali"
// CIDR掩码无效。
INTERNALERROR_CIDRMASKSIZEOUTOFRANGE = "InternalError.CidrMaskSizeOutOfRange"
// CIDR不在路由表之内。
INTERNALERROR_CIDROUTOFROUTETABLE = "InternalError.CidrOutOfRouteTable"
// 集群未找到。
INTERNALERROR_CLUSTERNOTFOUND = "InternalError.ClusterNotFound"
// 集群状态错误。
INTERNALERROR_CLUSTERSTATE = "InternalError.ClusterState"
// 集群节点版本过低。
INTERNALERROR_CLUSTERUPGRADENODEVERSION = "InternalError.ClusterUpgradeNodeVersion"
// 执行命令超时。
INTERNALERROR_CMDTIMEOUT = "InternalError.CmdTimeout"
// 内部HTTP客户端错误。
INTERNALERROR_COMPONENTCLIENTHTTP = "InternalError.ComponentClientHttp"
// 请求(http请求)其他云服务失败。
INTERNALERROR_COMPONENTCLINETHTTP = "InternalError.ComponentClinetHttp"
// 容器未找到。
INTERNALERROR_CONTAINERNOTFOUND = "InternalError.ContainerNotFound"
// 创建集群失败。
INTERNALERROR_CREATEMASTERFAILED = "InternalError.CreateMasterFailed"
// cvm创建节点报错。
INTERNALERROR_CVMCOMMON = "InternalError.CvmCommon"
// cvm不存在。
INTERNALERROR_CVMNOTFOUND = "InternalError.CvmNotFound"
// 存在云服务器在CVM侧查询不到。
INTERNALERROR_CVMNUMBERNOTMATCH = "InternalError.CvmNumberNotMatch"
// cvm状态不正常。
INTERNALERROR_CVMSTATUS = "InternalError.CvmStatus"
// db错误。
INTERNALERROR_DB = "InternalError.Db"
// DB错误。
INTERNALERROR_DBAFFECTIVEDROWS = "InternalError.DbAffectivedRows"
// 记录未找到。
INTERNALERROR_DBRECORDNOTFOUND = "InternalError.DbRecordNotFound"
// 获得当前安全组总数失败。
INTERNALERROR_DFWGETUSGCOUNT = "InternalError.DfwGetUSGCount"
// 获得安全组配额失败。
INTERNALERROR_DFWGETUSGQUOTA = "InternalError.DfwGetUSGQuota"
// 不支持空集群。
INTERNALERROR_EMPTYCLUSTERNOTSUPPORT = "InternalError.EmptyClusterNotSupport"
// 下一跳地址已关联CIDR。
INTERNALERROR_GATEWAYALREADYASSOCIATEDCIDR = "InternalError.GatewayAlreadyAssociatedCidr"
// 镜像未找到。
INTERNALERROR_IMAGEIDNOTFOUND = "InternalError.ImageIdNotFound"
// 初始化master失败。
INTERNALERROR_INITMASTERFAILED = "InternalError.InitMasterFailed"
// 无效CIDR。
INTERNALERROR_INVALIDPRIVATENETWORKCIDR = "InternalError.InvalidPrivateNetworkCidr"
// 连接用户Kubernetes集群失败。
INTERNALERROR_KUBECLIENTCONNECTION = "InternalError.KubeClientConnection"
// 创建集群Client出错。
INTERNALERROR_KUBECLIENTCREATE = "InternalError.KubeClientCreate"
// KubernetesAPI错误。
INTERNALERROR_KUBECOMMON = "InternalError.KubeCommon"
// kubernetes client建立失败。
INTERNALERROR_KUBERNETESCLIENTBUILDERROR = "InternalError.KubernetesClientBuildError"
// 创建Kubernetes资源失败。
INTERNALERROR_KUBERNETESCREATEOPERATIONERROR = "InternalError.KubernetesCreateOperationError"
// 删除Kubernetes资源失败。
INTERNALERROR_KUBERNETESDELETEOPERATIONERROR = "InternalError.KubernetesDeleteOperationError"
// 获取Kubernetes资源失败。
INTERNALERROR_KUBERNETESGETOPERATIONERROR = "InternalError.KubernetesGetOperationError"
// Kubernetes未知错误。
INTERNALERROR_KUBERNETESINTERNAL = "InternalError.KubernetesInternal"
// 底层调用CLB未知错误。
INTERNALERROR_LBCOMMON = "InternalError.LbCommon"
// 镜像OS不支持。
INTERNALERROR_OSNOTSUPPORT = "InternalError.OsNotSupport"
// Param。
INTERNALERROR_PARAM = "InternalError.Param"
// Pod未找到。
INTERNALERROR_PODNOTFOUND = "InternalError.PodNotFound"
// 集群不支持当前操作。
INTERNALERROR_PUBLICCLUSTEROPNOTSUPPORT = "InternalError.PublicClusterOpNotSupport"
// 超过配额限制。
INTERNALERROR_QUOTAMAXCLSLIMIT = "InternalError.QuotaMaxClsLimit"
// 超过配额限制。
INTERNALERROR_QUOTAMAXNODLIMIT = "InternalError.QuotaMaxNodLimit"
// 超过配额限制。
INTERNALERROR_QUOTAMAXRTLIMIT = "InternalError.QuotaMaxRtLimit"
// 安全组配额不足。
INTERNALERROR_QUOTAUSGLIMIT = "InternalError.QuotaUSGLimit"
// 资源已存在。
INTERNALERROR_RESOURCEEXISTALREADY = "InternalError.ResourceExistAlready"
// 路由表非空。
INTERNALERROR_ROUTETABLENOTEMPTY = "InternalError.RouteTableNotEmpty"
// 路由表不存在。
INTERNALERROR_ROUTETABLENOTFOUND = "InternalError.RouteTableNotFound"
// 已有相同任务执行中。
INTERNALERROR_TASKALREADYRUNNING = "InternalError.TaskAlreadyRunning"
// 创建任务失败。
INTERNALERROR_TASKCREATEFAILED = "InternalError.TaskCreateFailed"
// 任务当前所处状态不支持此操作。
INTERNALERROR_TASKLIFESTATEERROR = "InternalError.TaskLifeStateError"
// 任务未找到。
INTERNALERROR_TASKNOTFOUND = "InternalError.TaskNotFound"
// 询价错误。
INTERNALERROR_TRADECOMMON = "InternalError.TradeCommon"
// 账户余额不足。
INTERNALERROR_TRADEINSUFFICIENTBALANCE = "InternalError.TradeInsufficientBalance"
// 内部错误。
INTERNALERROR_UNEXCEPTEDINTERNAL = "InternalError.UnexceptedInternal"
// 未知的内部错误。
INTERNALERROR_UNEXPECTEDINTERNAL = "InternalError.UnexpectedInternal"
// VPC未知错误。
INTERNALERROR_VPCUNEXPECTEDERROR = "InternalError.VPCUnexpectedError"
// VPC报错。
INTERNALERROR_VPCCOMMON = "InternalError.VpcCommon"
// 对等连接不存在。
INTERNALERROR_VPCPEERNOTFOUND = "InternalError.VpcPeerNotFound"
// 未发现vpc记录。
INTERNALERROR_VPCRECODRNOTFOUND = "InternalError.VpcRecodrNotFound"
// 白名单未知错误。
INTERNALERROR_WHITELISTUNEXPECTEDERROR = "InternalError.WhitelistUnexpectedError"
// 参数错误。
INVALIDPARAMETER = "InvalidParameter"
// 弹性伸缩组创建参数错误。
INVALIDPARAMETER_ASCOMMONERROR = "InvalidParameter.AsCommonError"
// CIDR掩码超出范围(集群CIDR范围 最小值: 10 最大值: 24)。
INVALIDPARAMETER_CIDRMASKSIZEOUTOFRANGE = "InvalidParameter.CIDRMaskSizeOutOfRange"
// CIDR和其他集群CIDR冲突。
INVALIDPARAMETER_CIDRCONFLICTWITHOTHERCLUSTER = "InvalidParameter.CidrConflictWithOtherCluster"
// 创建的路由与已存在的其他路由产生冲突。
INVALIDPARAMETER_CIDRCONFLICTWITHOTHERROUTE = "InvalidParameter.CidrConflictWithOtherRoute"
// CIDR和vpc的CIDR冲突。
INVALIDPARAMETER_CIDRCONFLICTWITHVPCCIDR = "InvalidParameter.CidrConflictWithVpcCidr"
// 创建的路由与VPC下已存在的全局路由产生冲突。
INVALIDPARAMETER_CIDRCONFLICTWITHVPCGLOBALROUTE = "InvalidParameter.CidrConflictWithVpcGlobalRoute"
// 参数错误CIDR不符合规范。
INVALIDPARAMETER_CIDRINVALID = "InvalidParameter.CidrInvalid"
// CIDR不在路由表之内。
INVALIDPARAMETER_CIDROUTOFROUTETABLE = "InvalidParameter.CidrOutOfRouteTable"
// 集群ID不存在。
INVALIDPARAMETER_CLUSTERNOTFOUND = "InvalidParameter.ClusterNotFound"
// 下一跳地址已关联CIDR。
INVALIDPARAMETER_GATEWAYALREADYASSOCIATEDCIDR = "InvalidParameter.GatewayAlreadyAssociatedCidr"
// 无效的私有CIDR网段。
INVALIDPARAMETER_INVALIDPRIVATENETWORKCIDR = "InvalidParameter.InvalidPrivateNetworkCIDR"
// 参数错误。
INVALIDPARAMETER_PARAM = "InvalidParameter.Param"
// Prometheus未关联本集群。
INVALIDPARAMETER_PROMCLUSTERNOTFOUND = "InvalidParameter.PromClusterNotFound"
// Prometheus实例不存在。
INVALIDPARAMETER_PROMINSTANCENOTFOUND = "InvalidParameter.PromInstanceNotFound"
// 资源未找到。
INVALIDPARAMETER_RESOURCENOTFOUND = "InvalidParameter.ResourceNotFound"
// 路由表非空。
INVALIDPARAMETER_ROUTETABLENOTEMPTY = "InvalidParameter.RouteTableNotEmpty"
// 超过配额限制。
LIMITEXCEEDED = "LimitExceeded"
// 缺少参数错误。
MISSINGPARAMETER = "MissingParameter"
// 操作被拒绝。
OPERATIONDENIED = "OperationDenied"
// 集群处于删除保护中,禁止删除。
OPERATIONDENIED_CLUSTERINDELETIONPROTECTION = "OperationDenied.ClusterInDeletionProtection"
// 资源被占用。
RESOURCEINUSE = "ResourceInUse"
// 资源不足。
RESOURCEINSUFFICIENT = "ResourceInsufficient"
// 资源不存在。
RESOURCENOTFOUND = "ResourceNotFound"
// 伸缩组不存在。
RESOURCENOTFOUND_ASASGNOTEXIST = "ResourceNotFound.AsAsgNotExist"
// 集群不存在。
RESOURCENOTFOUND_CLUSTERNOTFOUND = "ResourceNotFound.ClusterNotFound"
// 用户Kubernetes集群中未找到指定资源。
RESOURCENOTFOUND_KUBERESOURCENOTFOUND = "ResourceNotFound.KubeResourceNotFound"
// 未找到该kubernetes资源。
RESOURCENOTFOUND_KUBERNETESRESOURCENOTFOUND = "ResourceNotFound.KubernetesResourceNotFound"
// 找不到对应路由表。
RESOURCENOTFOUND_ROUTETABLENOTFOUND = "ResourceNotFound.RouteTableNotFound"
// 资源不可用。
RESOURCEUNAVAILABLE = "ResourceUnavailable"
// 集群状态不支持该操作。
RESOURCEUNAVAILABLE_CLUSTERSTATE = "ResourceUnavailable.ClusterState"
// Eks Container Instance状态不支持改操作。
RESOURCEUNAVAILABLE_EKSCONTAINERSTATUS = "ResourceUnavailable.EksContainerStatus"
// 资源售罄。
RESOURCESSOLDOUT = "ResourcesSoldOut"
// 未授权操作。
UNAUTHORIZEDOPERATION = "UnauthorizedOperation"
// 无该接口CAM权限。
UNAUTHORIZEDOPERATION_CAMNOAUTH = "UnauthorizedOperation.CamNoAuth"
// 未知参数错误。
UNKNOWNPARAMETER = "UnknownParameter"
// 操作不支持。
UNSUPPORTEDOPERATION = "UnsupportedOperation"
// AS伸缩关闭导致无法开启CA。
UNSUPPORTEDOPERATION_CAENABLEFAILED = "UnsupportedOperation.CaEnableFailed"
// 非白名单用户。
UNSUPPORTEDOPERATION_NOTINWHITELIST = "UnsupportedOperation.NotInWhitelist"
)

File diff suppressed because it is too large Load Diff

View File

@ -1,217 +0,0 @@
package poder
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"context"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
alieci "github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
"github.com/bitly/go-simplejson"
"github.com/golang/glog"
"strconv"
"sync"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"github.com/pkg/errors"
)
var aliClientMutex sync.Mutex
type AliEci struct {
cli *alieci.Client
region tenanter.Region
tenanter tenanter.Tenanter
}
func (eci *AliEci) GetPodRegion(ctx context.Context, req *pbpod.GetPodRegionReq) (*pbpod.GetPodRegionResp, error) {
regions := make([]*pbpod.Region, 0)
requestRegion := requests.NewCommonRequest()
requestRegion.Method = "POST"
requestRegion.Scheme = "https" // https | http
requestRegion.Domain = "eci.aliyuncs.com"
requestRegion.Version = "2018-08-08"
requestRegion.ApiName = "DescribeRegions"
//这里需要给一个空字符串的RegionId
requestRegion.QueryParams["RegionId"] = ""
resp, err := eci.cli.ProcessCommonRequest(requestRegion)
var respRegion *simplejson.Json
respRegion, err = simplejson.NewJson([]byte(resp.GetHttpContentString()))
if err != nil {
panic("解析失败")
}
i := 0
for i < len(respRegion.Get("Regions").MustArray()) {
regionsJson := respRegion.Get("Regions").GetIndex(i)
regionName, _ := regionsJson.Get("RegionId").String()
regionId, _ := tenanter.GetAliRegionId(regionName)
regionPod := &pbpod.Region{
Id: regionId,
Name: regionName,
}
regions = append(regions, regionPod)
i++
}
return &pbpod.GetPodRegionResp{Regions: regions}, nil
}
func newAliEciClient(region tenanter.Region, tenant tenanter.Tenanter) (Poder, error) {
var (
client *alieci.Client
err error
)
switch t := tenant.(type) {
case *tenanter.AccessKeyTenant:
aliClientMutex.Lock()
client, err = alieci.NewClientWithAccessKey(region.GetName(), t.GetId(), t.GetSecret())
aliClientMutex.Unlock()
default:
}
if err != nil {
return nil, errors.Wrap(err, "init ali ecs client error")
}
return &AliEci{
cli: client,
region: region,
tenanter: tenant,
}, nil
}
func (eci *AliEci) CreatePod(ctx context.Context, req *pbpod.CreatePodReq) (*pbpod.CreatePodResp, error) {
request := alieci.CreateCreateContainerGroupRequest()
request.RegionId = eci.region.GetName()
request.ContainerGroupName = req.PodName
requestContainer := make([]alieci.CreateContainerGroupContainer, 1)
requestContainer[0].Image = req.ContainerImage
requestContainer[0].Name = req.ContainerName
requestContainer[0].Cpu = requests.Float(req.CpuPod)
requestContainer[0].Memory = requests.Float(req.MemoryPod)
request.Container = &requestContainer
resp, err := eci.cli.CreateContainerGroup(request)
if err != nil {
return nil, errors.Wrap(err, "Aliyun CreatePod error")
}
isFinished := false
if len(resp.ContainerGroupId) > 0 {
isFinished = true
}
glog.Infof("--------------------Aliyun ECI Instance created--------------------")
return &pbpod.CreatePodResp{
Finished: isFinished,
RequestId: "Create Ali pcm_pod request ID:" + resp.RequestId,
PodId: resp.ContainerGroupId,
PodName: req.PodName,
}, nil
}
func (eci *AliEci) DeletePod(ctx context.Context, req *pbpod.DeletePodReq) (*pbpod.DeletePodResp, error) {
deleteContainerGroupRequest := alieci.CreateDeleteContainerGroupRequest()
deleteContainerGroupRequest.RegionId = eci.region.GetName()
deleteContainerGroupRequest.ContainerGroupId = req.PcmId
resp, err := eci.cli.DeleteContainerGroup(deleteContainerGroupRequest)
isFinished := true
if err != nil {
isFinished = false
return nil, err
}
glog.Infof("--------------------Aliyun ECI Instance deleted--------------------")
return &pbpod.DeletePodResp{
Finished: isFinished,
RequestId: "Delete Ali pcm_pod request ID:" + resp.RequestId,
PodId: req.PodId,
PodName: req.PodName,
}, nil
}
func (eci *AliEci) UpdatePod(ctx context.Context, req *pbpod.UpdatePodReq) (*pbpod.UpdatePodResp, error) {
updateContainerGroupRequest := alieci.CreateUpdateContainerGroupRequest()
updateContainerGroupRequest.RegionId = eci.region.GetName()
updateContainerGroupRequest.ContainerGroupId = req.PcmId
updateContainerRequestContainer := make([]alieci.UpdateContainerGroupContainer, 1)
updateContainerRequestContainer[0].Image = req.ContainerImage
updateContainerRequestContainer[0].Name = req.ContainerName
updateContainerRequestContainer[0].Cpu = requests.Float(req.CpuPod)
updateContainerRequestContainer[0].Memory = requests.Float(req.MemoryPod)
updateContainerGroupRequest.Container = &updateContainerRequestContainer
updateContainerGroupRequest.RestartPolicy = req.RestartPolicy
resp, err := eci.cli.UpdateContainerGroup(updateContainerGroupRequest)
isFinished := true
if err != nil {
isFinished = false
return nil, err
}
glog.Infof("--------------------Aliyun ECI Instance updated--------------------")
return &pbpod.UpdatePodResp{
Finished: isFinished,
RequestId: "Update Ali pcm_pod request ID:" + resp.RequestId,
PodId: req.PodId,
PodName: req.PodName,
}, nil
}
func (eci *AliEci) ListPodDetail(ctx context.Context, req *pbpod.ListPodDetailReq) (*pbpod.ListPodDetailResp, error) {
request := alieci.CreateDescribeContainerGroupsRequest()
request.NextToken = req.NextToken
resp, err := eci.cli.DescribeContainerGroups(request)
if err != nil {
return nil, err
}
var ecies = make([]*pbpod.PodInstance, len(resp.ContainerGroups))
for k, v := range resp.ContainerGroups {
ecies[k] = &pbpod.PodInstance{
Provider: pbpod.CloudProvider_ali,
AccountName: eci.tenanter.AccountName(),
PcmId: v.ContainerGroupId,
PodId: v.ContainerGroupId,
PodName: v.ContainerGroupName,
RegionId: eci.region.GetId(),
RegionName: v.RegionId,
ContainerImage: v.Containers[0].Image,
ContainerName: v.Containers[0].Name,
CpuPod: strconv.FormatFloat(float64(v.Cpu), 'f', 6, 64),
MemoryPod: strconv.FormatFloat(float64(v.Memory), 'f', 6, 64),
SecurityGroupId: v.SecurityGroupId,
SubnetId: v.InternetIp,
VpcId: v.VpcId,
Namespace: "",
Status: v.Status,
}
}
isFinished := false
if len(ecies) < int(req.PageSize) {
isFinished = true
}
return &pbpod.ListPodDetailResp{
Pods: ecies,
Finished: isFinished,
PageNumber: req.PageNumber + 1,
PageSize: req.PageSize,
NextToken: resp.NextToken,
RequestId: resp.RequestId,
}, nil
}

View File

@ -1,244 +0,0 @@
package poder
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"context"
"fmt"
util "github.com/alibabacloud-go/tea-utils/service"
"sync"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1 "k8s.io/api/core/v1"
huaweicci "k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"github.com/pkg/errors"
)
var huaweiClientMutex sync.Mutex
type HuaweiCci struct {
cli *huaweicci.Clientset
region tenanter.Region
tenanter tenanter.Tenanter
}
func (cci *HuaweiCci) GetPodRegion(ctx context.Context, req *pbpod.GetPodRegionReq) (*pbpod.GetPodRegionResp, error) {
//todo
var (
regions []*pbpod.Region
)
huaweiRegionName, _ := tenanter.GetHuaweiRegionName(5)
region := &pbpod.Region{
Id: 5,
Name: huaweiRegionName,
}
regions = append(regions, region)
resp := &pbpod.GetPodRegionResp{
Regions: regions,
}
return resp, nil
}
// CCI auth through iam
const (
apiVersion = "client.authentication.k8s.io/v1beta1"
iamEndpoint = "https://iam.myhuaweicloud.com"
)
func newHuaweiCciClient(region tenanter.Region, tenant tenanter.Tenanter) (Poder, error) {
var (
client *huaweicci.Clientset
err error
)
cciEndpoint := "https://cci." + region.GetName() + ".myhuaweicloud.com"
cciConfig, err := clientcmd.BuildConfigFromFlags(cciEndpoint, "")
if err != nil {
return nil, err
}
switch t := tenant.(type) {
case *tenanter.AccessKeyTenant:
huaweiClientMutex.Lock()
var optionArgs []string
optionArgs = append(optionArgs, fmt.Sprintf("--iam-endpoint=%s", iamEndpoint))
optionArgs = append(optionArgs, fmt.Sprintf("--project-name=%s", region.GetName()))
optionArgs = append(optionArgs, fmt.Sprintf("--ak=%s", t.GetId()))
optionArgs = append(optionArgs, fmt.Sprintf("--sk=%s", t.GetSecret()))
cciConfig.ExecProvider = &api.ExecConfig{
Command: "cci-iam-authenticator",
APIVersion: apiVersion,
Args: append([]string{"token"}, optionArgs...),
Env: make([]api.ExecEnvVar, 0),
}
client, err = huaweicci.NewForConfig(cciConfig)
huaweiClientMutex.Unlock()
default:
}
if err != nil {
return nil, errors.Wrap(err, "init huawei pcm_pod client error")
}
return &HuaweiCci{
cli: client,
region: region,
tenanter: tenant,
}, nil
}
func (cci *HuaweiCci) CreatePod(ctx context.Context, req *pbpod.CreatePodReq) (*pbpod.CreatePodResp, error) {
pod := corev1.Pod{
TypeMeta: metav1.TypeMeta{
APIVersion: "core/V1",
Kind: "Pod",
},
ObjectMeta: metav1.ObjectMeta{
Name: req.PodName,
Namespace: req.Namespace,
Labels: map[string]string{"name": "test_api"},
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
Containers: []corev1.Container{
{
Name: req.ContainerName,
Image: req.ContainerImage,
Resources: corev1.ResourceRequirements{
Limits: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse(req.CpuPod),
corev1.ResourceMemory: resource.MustParse(req.MemoryPod),
},
},
},
},
},
Status: corev1.PodStatus{},
}
resp, err := cci.cli.CoreV1().Pods(req.Namespace).Create(context.TODO(), &pod, metav1.CreateOptions{})
if err != nil {
return nil, err
}
isFinished := false
if len(resp.UID) > 0 {
isFinished = true
}
glog.Infof("--------------------Huawei CCI Instance created--------------------")
return &pbpod.CreatePodResp{
Finished: isFinished,
RequestId: "Create huawei pcm_pod request ID:" + resp.GenerateName,
PodId: string(resp.Generation),
PodName: resp.Name,
}, nil
}
func (cci *HuaweiCci) DeletePod(ctx context.Context, req *pbpod.DeletePodReq) (*pbpod.DeletePodResp, error) {
err := cci.cli.CoreV1().Pods(req.GetNamespace()).Delete(context.TODO(), req.PcmId, metav1.DeleteOptions{})
isFinished := true
if err != nil {
return nil, err
}
glog.Infof("--------------------Huawei CCI Instance deleted--------------------")
glog.Infof(*util.ToJSONString(util.ToMap(err)))
return &pbpod.DeletePodResp{
Finished: isFinished,
RequestId: "Delete huawei pcm_pod request ID:" + req.PodName,
PodId: req.PodName,
PodName: req.PodName,
}, nil
}
func (cci *HuaweiCci) UpdatePod(ctx context.Context, req *pbpod.UpdatePodReq) (*pbpod.UpdatePodResp, error) {
qresp, err := cci.cli.CoreV1().Pods(req.GetNamespace()).Get(context.TODO(), req.PcmId, metav1.GetOptions{})
if err != nil {
return nil, err
}
pod := corev1.Pod{
TypeMeta: qresp.TypeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: req.PcmId,
Namespace: req.Namespace,
Labels: map[string]string{"name": req.Labels},
},
Spec: qresp.Spec,
Status: qresp.Status,
}
pod.Spec.Containers[0].Image = req.ContainerImage
resp, err := cci.cli.CoreV1().Pods(req.Namespace).Update(context.TODO(), &pod, metav1.UpdateOptions{})
glog.Info("Huawei update pcm_pod resp", resp)
if err != nil {
return nil, errors.Wrap(err, "Huaweiyun UpdatePod error")
}
glog.Infof("--------------------Huawei CCI Instance updated--------------------")
isFinished := false
if len(resp.UID) > 0 {
isFinished = true
}
return &pbpod.UpdatePodResp{
Finished: isFinished,
RequestId: "Update huawei pcm_pod request ID:" + resp.GenerateName,
PodId: string(resp.Generation),
PodName: resp.Name,
}, nil
}
func (cci *HuaweiCci) ListPodDetail(ctx context.Context, req *pbpod.ListPodDetailReq) (*pbpod.ListPodDetailResp, error) {
resp, err := cci.cli.CoreV1().Pods(req.GetNamespace()).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, err
}
glog.Info("Huaweiyun ListDetail pcm_pod success", resp.Items)
var pods = make([]*pbpod.PodInstance, len(resp.Items))
for k, v := range resp.Items {
pods[k] = &pbpod.PodInstance{
Provider: pbpod.CloudProvider_huawei,
AccountName: cci.tenanter.AccountName(),
PcmId: v.Name,
PodId: string(v.GetUID()),
PodName: v.Name,
RegionId: cci.region.GetId(),
ContainerImage: v.Spec.Containers[0].Image,
ContainerName: v.Spec.Containers[0].Name,
CpuPod: v.Spec.Containers[0].Resources.Requests.Cpu().String(),
MemoryPod: v.Spec.Containers[0].Resources.Requests.Memory().String(),
Namespace: v.Namespace,
Status: string(v.Status.Phase),
}
}
glog.Infof("--------------------Huawei CCI Instance updated--------------------")
isFinished := false
if len(pods) < int(req.PageSize) {
isFinished = true
}
return &pbpod.ListPodDetailResp{
Pods: pods,
Finished: isFinished,
PageNumber: req.PageNumber + 1,
PageSize: req.PageSize,
}, nil
}

View File

@ -1,231 +0,0 @@
package poder
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"context"
"fmt"
"github.com/golang/glog"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8s "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"sync"
)
var k8sClientMutex sync.Mutex
type Config struct {
Host string
Token string
Port int
}
type K8SPoder struct {
cli *k8s.Clientset
region tenanter.Region
tenanter tenanter.Tenanter
}
func (k K8SPoder) GetPodRegion(ctx context.Context, req *pbpod.GetPodRegionReq) (*pbpod.GetPodRegionResp, error) {
//todo
var (
regions []*pbpod.Region
)
huaweiRegionName, _ := tenanter.GetK8SRegionName(0)
region := &pbpod.Region{
Id: 0,
Name: huaweiRegionName,
}
regions = append(regions, region)
resp := &pbpod.GetPodRegionResp{
Regions: regions,
}
return resp, nil
}
func newK8SClient(tenant tenanter.Tenanter) (Poder, error) {
var (
client *k8s.Clientset
err error
)
switch t := tenant.(type) {
case *tenanter.AccessKeyTenant:
kubeConf := &rest.Config{
Host: fmt.Sprintf("%s:%d", t.GetUrl(), 6443),
BearerToken: t.GetToken(),
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
k8sClientMutex.Lock()
client, err = k8s.NewForConfig(kubeConf)
k8sClientMutex.Unlock()
default:
}
if err != nil {
return nil, errors.Wrap(err, "init k8s client error")
}
return &K8SPoder{
cli: client,
region: nil,
tenanter: tenant,
}, nil
}
func (k *K8SPoder) CreatePod(ctx context.Context, req *pbpod.CreatePodReq) (*pbpod.CreatePodResp, error) {
pod := corev1.Pod{
TypeMeta: metav1.TypeMeta{
APIVersion: "core/V1",
Kind: "Pod",
},
ObjectMeta: metav1.ObjectMeta{
Name: req.PodName,
Namespace: req.Namespace,
Labels: map[string]string{"name": "test_api"},
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
Containers: []corev1.Container{
{
Name: req.ContainerName,
Image: req.ContainerImage,
Resources: corev1.ResourceRequirements{
Limits: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse(req.CpuPod),
corev1.ResourceMemory: resource.MustParse(req.MemoryPod),
},
},
},
},
},
Status: corev1.PodStatus{},
}
resp, err := k.cli.CoreV1().Pods(req.Namespace).Create(context.TODO(), &pod, metav1.CreateOptions{})
if err != nil {
return nil, err
}
glog.Infof("--------------------K8S Pod Instance created--------------------")
isFinished := false
if len(resp.UID) > 0 {
isFinished = true
}
return &pbpod.CreatePodResp{
Finished: isFinished,
RequestId: "K8S pcm_pod Name:" + resp.Name,
PodId: string(resp.UID),
PodName: resp.Name,
}, nil
}
func (k K8SPoder) DeletePod(ctx context.Context, req *pbpod.DeletePodReq) (*pbpod.DeletePodResp, error) {
podName := req.PcmId
fmt.Println("K8S ContainerGroup:", podName, " Deleted")
err := k.cli.CoreV1().Pods(req.Namespace).Delete(context.TODO(), podName, metav1.DeleteOptions{})
glog.Infof("--------------------K8S Pod Instance deleted--------------------")
isFinished := true
if err != nil {
return nil, err
}
return &pbpod.DeletePodResp{
Finished: isFinished,
RequestId: "K8S pcm_pod Name:" + req.PodName,
PodId: req.PodName,
PodName: req.PodName,
}, nil
}
func (k K8SPoder) UpdatePod(ctx context.Context, req *pbpod.UpdatePodReq) (*pbpod.UpdatePodResp, error) {
qresp, err := k.cli.CoreV1().Pods(req.GetNamespace()).Get(context.TODO(), req.PcmId, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrap(err, "K8S UpdatePod error")
}
pod := corev1.Pod{
TypeMeta: qresp.TypeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: req.PcmId,
Namespace: req.Namespace,
Labels: map[string]string{"name": req.Labels},
},
Spec: qresp.Spec,
Status: qresp.Status,
}
pod.Spec.Containers[0].Image = req.ContainerImage
resp, err := k.cli.CoreV1().Pods(req.Namespace).Update(context.TODO(), &pod, metav1.UpdateOptions{})
if err != nil {
return nil, err
}
glog.Infof("--------------------K8S Pod Instance updated--------------------")
isFinished := false
if len(resp.UID) > 0 {
isFinished = true
}
return &pbpod.UpdatePodResp{
Finished: isFinished,
RequestId: "K8S pcm_pod Name:" + req.PodName,
PodId: string(resp.UID),
PodName: req.PodName,
}, nil
}
func (k K8SPoder) ListPodDetail(ctx context.Context, req *pbpod.ListPodDetailReq) (*pbpod.ListPodDetailResp, error) {
resp, err := k.cli.CoreV1().Pods(req.GetNamespace()).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, err
}
var pods = make([]*pbpod.PodInstance, len(resp.Items))
for k, v := range resp.Items {
pods[k] = &pbpod.PodInstance{
Provider: pbpod.CloudProvider_k8s,
AccountName: req.AccountName,
PcmId: v.Name,
PodId: string(v.GetUID()),
PodName: v.Name,
ContainerImage: v.Spec.Containers[0].Image,
ContainerName: v.Spec.Containers[0].Name,
CpuPod: v.Spec.Containers[0].Resources.Requests.Cpu().String(),
MemoryPod: v.Spec.Containers[0].Resources.Requests.Memory().String(),
Namespace: v.Namespace,
Status: string(v.Status.Phase),
}
}
glog.Infof("--------------------Huawei CCI Instance updated--------------------")
isFinished := false
if len(pods) < int(req.PageSize) {
isFinished = true
}
return &pbpod.ListPodDetailResp{
Pods: pods,
Finished: isFinished,
PageNumber: req.PageNumber + 1,
PageSize: req.PageSize,
}, nil
}

View File

@ -1,50 +0,0 @@
package poder
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"context"
"github.com/golang/glog"
"github.com/pkg/errors"
)
var (
ErrPodListNotSupported = errors.New("cloud not supported pcm_pod list")
ErrPoderPanic = errors.New("pcm_pod init panic")
)
type Poder interface {
ListPodDetail(ctx context.Context, req *pbpod.ListPodDetailReq) (resp *pbpod.ListPodDetailResp, err error)
CreatePod(ctx context.Context, req *pbpod.CreatePodReq) (resp *pbpod.CreatePodResp, err error)
DeletePod(ctx context.Context, req *pbpod.DeletePodReq) (*pbpod.DeletePodResp, error)
UpdatePod(ctx context.Context, req *pbpod.UpdatePodReq) (*pbpod.UpdatePodResp, error)
GetPodRegion(ctx context.Context, req *pbpod.GetPodRegionReq) (*pbpod.GetPodRegionResp, error)
}
func NewPodClient(provider pbpod.CloudProvider, region tenanter.Region, tenant tenanter.Tenanter) (poder Poder, err error) {
// 部分sdk会在内部panic
defer func() {
if err1 := recover(); err1 != nil {
glog.Errorf("NewPodClient panic %v", err1)
err = errors.WithMessagef(ErrPoderPanic, "%v", err1)
}
}()
switch provider {
case pbpod.CloudProvider_ali:
return newAliEciClient(region, tenant)
case pbpod.CloudProvider_tencent:
return newTencentEksClient(region, tenant)
case pbpod.CloudProvider_huawei:
return newHuaweiCciClient(region, tenant)
case pbpod.CloudProvider_k8s:
return newK8SClient(tenant)
//TODO aws
//case pbtenant.CloudProvider_aws:
// return newAwsPodClient(region, tenant)
}
err = errors.WithMessagef(ErrPodListNotSupported, "cloud provider %v region %v", provider, region)
return
}

View File

@ -1,220 +0,0 @@
package poder
import (
pbpod "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_pod/gen/idl"
"context"
"strconv"
"sync"
"github.com/golang/glog"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"github.com/pkg/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
tencenteks "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tke/v20180525"
)
var tencentClientMutex sync.Mutex
type TencentEks struct {
cli *tencenteks.Client
region tenanter.Region
tenanter tenanter.Tenanter
}
func (eks TencentEks) GetPodRegion(ctx context.Context, req *pbpod.GetPodRegionReq) (*pbpod.GetPodRegionResp, error) {
regions := make([]*pbpod.Region, 0)
request := tencenteks.NewDescribeEKSContainerInstanceRegionsRequest()
resp, err := eks.cli.DescribeEKSContainerInstanceRegions(request)
if err != nil {
return nil, errors.Wrap(err, "tencent eks describe region error")
}
for _, eksRegion := range resp.Response.Regions {
regionId, _ := tenanter.GetTencentRegionId(*eksRegion.RegionName)
regionPod := &pbpod.Region{
Id: regionId,
Name: *eksRegion.RegionName,
}
regions = append(regions, regionPod)
}
return &pbpod.GetPodRegionResp{Regions: regions}, nil
}
func newTencentEksClient(region tenanter.Region, tenant tenanter.Tenanter) (Poder, error) {
var (
client *tencenteks.Client
err error
)
switch t := tenant.(type) {
case *tenanter.AccessKeyTenant:
tencentClientMutex.Lock()
credential := common.NewCredential(
t.GetId(),
t.GetSecret(),
)
cpf := profile.NewClientProfile()
client, err = tencenteks.NewClient(credential, region.GetName(), cpf)
tencentClientMutex.Unlock()
default:
}
if err != nil {
return nil, errors.Wrap(err, "init tencent eks client error")
}
return &TencentEks{
cli: client,
region: region,
tenanter: tenant,
}, nil
}
func (eks TencentEks) CreatePod(ctx context.Context, req *pbpod.CreatePodReq) (*pbpod.CreatePodResp, error) {
request := tencenteks.NewCreateEKSContainerInstancesRequest()
eksCiName := req.PodName
containerName := req.ContainerName
containerImage := req.ContainerImage
eksCpu := req.CpuPod
eksMemory := req.MemoryPod
securityGroupId := req.SecurityGroupId
securityGroupIds := make([]*string, 1)
securityGroupIds[0] = &securityGroupId
subNetId := req.SubnetId
vpcId := req.VpcId
request.EksCiName = &eksCiName
container := make([]*tencenteks.Container, 1)
container[0] = new(tencenteks.Container)
container[0].Name = &containerName
container[0].Image = &containerImage
request.Containers = container
eksCpu64, err := strconv.ParseFloat(eksCpu, 64)
eksMemory64, err := strconv.ParseFloat(eksMemory, 64)
request.Cpu = &eksCpu64
request.Memory = &eksMemory64
request.SecurityGroupIds = securityGroupIds
request.SubnetId = &subNetId
request.VpcId = &vpcId
resp, err := eks.cli.CreateEKSContainerInstances(request)
if err != nil {
return nil, errors.Wrap(err, "Tencent CreatePod error")
}
isFinished := false
if resp.Response.RequestId != nil {
isFinished = true
}
glog.Infof("--------------------K8S Pod Instance created--------------------")
return &pbpod.CreatePodResp{
Finished: isFinished,
RequestId: "tencent pcm_pod create request id:" + *resp.Response.RequestId,
PodId: *resp.Response.EksCiIds[0],
PodName: req.PodName,
}, nil
}
func (eks *TencentEks) DeletePod(ctx context.Context, req *pbpod.DeletePodReq) (*pbpod.DeletePodResp, error) {
request := tencenteks.NewDeleteEKSContainerInstancesRequest()
request.EksCiIds = make([]*string, 1)
request.EksCiIds[0] = &req.PcmId
resp, err := eks.cli.DeleteEKSContainerInstances(request)
isFinished := true
if err != nil {
isFinished = false
return nil, errors.Wrap(err, "Tencent DeletePod error")
}
glog.Infof("--------------------K8S Pod Instance deleted--------------------")
return &pbpod.DeletePodResp{
Finished: isFinished,
RequestId: "tencent pcm_pod delete request id:" + *resp.Response.RequestId,
PodId: req.PodId,
PodName: req.PodName,
}, nil
}
func (eks *TencentEks) UpdatePod(ctx context.Context, req *pbpod.UpdatePodReq) (*pbpod.UpdatePodResp, error) {
//创建更新pod请求
request := tencenteks.NewUpdateEKSContainerInstanceRequest()
request.EksCiId = &req.PcmId
request.Name = &req.PodName
request.RestartPolicy = &req.RestartPolicy
request.Containers = make([]*tencenteks.Container, 1)
request.Containers[0] = new(tencenteks.Container)
request.Containers[0].Name = &req.ContainerName
request.Containers[0].Image = &req.ContainerImage
resp, err := eks.cli.UpdateEKSContainerInstance(request)
isFinished := true
if err != nil {
isFinished = false
return nil, errors.Wrap(err, "Tencent UpdatePod error")
}
glog.Infof("--------------------K8S Pod Instance deleted--------------------")
return &pbpod.UpdatePodResp{
Finished: isFinished,
RequestId: "tencent pcm_pod update request id:" + *resp.Response.RequestId,
PodId: req.PodId,
PodName: req.PodName,
}, nil
}
func (eks TencentEks) ListPodDetail(ctx context.Context, req *pbpod.ListPodDetailReq) (*pbpod.ListPodDetailResp, error) {
request := tencenteks.NewDescribeEKSContainerInstancesRequest()
resp, err := eks.cli.DescribeEKSContainerInstances(request)
if err != nil {
return nil, errors.Wrap(err, "Tencent ListDetail pcm_pod error")
}
var ekspods = make([]*pbpod.PodInstance, len(resp.Response.EksCis))
for k, v := range resp.Response.EksCis {
ekspods[k] = &pbpod.PodInstance{
Provider: pbpod.CloudProvider_tencent,
AccountName: eks.tenanter.AccountName(),
PcmId: *v.EksCiId,
PodId: *v.EksCiId,
PodName: *v.EksCiName,
RegionId: eks.region.GetId(),
RegionName: eks.region.GetName(),
ContainerImage: *v.Containers[0].Image,
ContainerName: *v.Containers[0].Name,
CpuPod: strconv.FormatFloat(*v.Cpu, 'f', 6, 64),
MemoryPod: strconv.FormatFloat(*v.Memory, 'f', 6, 64),
SecurityGroupId: *v.SecurityGroupIds[0],
SubnetId: *v.SubnetId,
VpcId: *v.VpcId,
Namespace: "",
Status: *v.Status,
}
}
isFinished := false
if len(ekspods) < int(req.PageSize) {
isFinished = true
}
glog.Infof("--------------------K8S Pod Instance listed--------------------")
return &pbpod.ListPodDetailResp{
Pods: ekspods,
Finished: isFinished,
PageNumber: req.PageNumber + 1,
PageSize: req.PageSize,
RequestId: *resp.Response.RequestId,
}, nil
}

View File

@ -1,17 +0,0 @@
version: v1
plugins:
- name: go
out: gen
opt:
- paths=source_relative
- name: go-grpc
out: gen
opt:
- paths=source_relative
- name: grpc-gateway
out: gen
opt:
- paths=source_relative
- grpc_api_configuration=idl/slurm.yaml
- name: openapiv2
out: gen/openapiv2

View File

@ -1,13 +0,0 @@
version: v1
name: buf.build/JCCE/PCM
breaking:
use:
- FILE
lint:
use:
- DEFAULT
# ignore:
# - google/type/datetime.proto
deps:
- buf.build/googleapis/googleapis
- buf.build/grpc-ecosystem/grpc-gateway

View File

@ -1,123 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/slurm_node.proto";
import "idl/slurm_partition.proto";
import "idl/slurm_reservation.proto";
import "idl/slurm_ping.proto";
import "idl/slurmdb_cluster.proto";
import "idl/slurmdb_user.proto";
import "idl/slurmdb_assoc.proto";
import "idl/slurmdb_account.proto";
import "idl/slurmdb_qos.proto";
import "idl/slurmdb_wckey.proto";
import "idl/slurm_job.proto";
import "idl/slurm_diag.proto";
import "idl/slurmdb_job.proto";
// Slurm Services
service SlurmService {
// list all users from slurmdb
rpc ListUsers(ListUsersReq) returns (ListUsersResp);
// get specific user info from slurmdb
rpc GetUser(GetUserReq) returns (GetUserResp);
// add new user
rpc AddUser(AddUserReq) returns (AddUserResp);
// delete specific user
rpc DeleteUser(DeleteUserReq) returns (DeleteUserResp);
// list all associations from slurmdb
rpc ListAssociations(ListAssociationsReq) returns (ListAssociationsResp);
// get specific association info from slurmdb
rpc GetAssociation(GetAssociationReq) returns (GetAssociationResp);
// list all accounts info from slurmdb
rpc ListAccounts(ListAccountsReq) returns (ListAccountsResp);
// get specific account info from slurmdb
rpc GetAccount(GetAccountReq) returns (GetAccountResp);
// add account
rpc AddAccount(AddAccountReq) returns (AddAccountResp);
// delete account
rpc DeleteAccount(DeleteAccountReq) returns (DeleteAccountResp);
// list all wckeys info from slurmdb
rpc ListWckeys(ListWckeysReq) returns (ListWckeysResp);
// get specific wckey info from slurmdb
rpc GetWckey(GetWckeyReq) returns (GetWckeyResp);
// list all Cluster from slurmdb
rpc ListClusters(ListClustersReq) returns (ListClustersResp);
// get specific user info from slurmdb
rpc GetCluster(GetClusterReq) returns (GetClusterResp);
// add new user
rpc AddCluster(AddClusterReq) returns (AddClusterResp);
// delete specific user
rpc DeleteCluster(DeleteClusterReq) returns (DeleteClusterResp);
// list all Node from slurm
rpc ListNodes(ListNodesReq) returns (ListNodesResp);
// get specific Node info from slurm
rpc GetNode(GetNodeReq) returns (GetNodeResp);
// list all Partition from slurm
rpc ListPartitions(ListPartitionsReq) returns (ListPartitionsResp);
// get specific Partition info from slurm
rpc GetPartition(GetPartitionReq) returns (GetPartitionResp);
// list all Reservation from slurm
rpc ListReservations(ListReservationsReq) returns (ListReservationsResp);
// get specific Reservation info from slurm
rpc GetReservation(GetReservationReq) returns (GetReservationResp);
// list all jobs from slurm
rpc GetAllJobs(JobInfoMsgReq) returns (JobInfoMsgResp);
// get job by id from slurm
rpc GetJob(JobInfoMsgReq) returns (JobInfoMsgResp);
// submit job to slurm
rpc SubmitJob(SubmitJobReq) returns (SubmitJobResp);
// delete job from slurm
rpc DeleteJob(DeleteJobReq) returns (DeleteJobResp);
// update job from slurm
rpc UpdateJob(UpdateJobReq) returns (UpdateJobResp);
// list all diag from slurm
rpc GetDiag(DiagReq) returns (DiagResp);
// list all qoses from slurm
rpc GetQos(QosReq) returns (QosResp);
// list all jobs from slurmdb
rpc GetSlurmdbJobs(SlurmDbJobReq) returns (SlurmDbJobResp);
// get job by id from slurmdb
rpc GetSlurmdbJobById(SlurmDbJobReq) returns (SlurmDbJobResp);
// delete qos from slurmdb
rpc DeleteQos(DeleteQosReq) returns (DeleteQosResp);
// get qos by name from slurmdb
rpc GetQosByName(QosReq) returns (QosResp);
// add qos to slurmdb
rpc AddQos(AddQosReq) returns (AddQosResp);
}

View File

@ -1,75 +0,0 @@
type: google.api.Service
config_version: 3
http:
rules:
- selector: slurm.SlurmService.ListUsers
get: "/apis/slurm/listUsers"
- selector: slurm.SlurmService.GetUser
get: "/apis/slurm/getUser"
- selector: slurm.SlurmService.AddUser
post: "/apis/slurm/addUser"
- selector: slurm.SlurmService.DeleteUser
delete: "/apis/slurm/deleteUser"
- selector: slurm.SlurmService.ListAssociations
get: "/apis/slurm/listAssociations"
- selector: slurm.SlurmService.GetAssociation
get: "/apis/slurm/getAssociation"
- selector: slurm.SlurmService.ListAccounts
get: "/apis/slurm/listAccounts"
- selector: slurm.SlurmService.GetAccount
get: "/apis/slurm/getAccount"
- selector: slurm.SlurmService.AddAccount
post: "/apis/slurm/addAccount"
- selector: slurm.SlurmService.DeleteAccount
delete: "/apis/slurm/deleteAccount"
- selector: slurm.SlurmService.ListWckeys
get: "/apis/slurm/listWckeys"
- selector: slurm.SlurmService.GetWckey
get: "/apis/slurm/getWckey"
- selector: slurm.SlurmService.ListClusters
get: "/apis/slurm/listClusters"
- selector: slurm.SlurmService.GetCluster
get: "/apis/slurm/getCluster"
- selector: slurm.SlurmService.AddCluster
post: "/apis/slurm/addCluster"
- selector: slurm.SlurmService.DeleteCluster
delete: "/apis/slurm/deleteCluster"
- selector: slurm.SlurmService.ListNodes
get: "/apis/slurm/listNodes"
- selector: slurm.SlurmService.GetNode
get: "/apis/slurm/getNode"
- selector: slurm.SlurmService.ListPartitions
get: "/apis/slurm/listPartitions"
- selector: slurm.SlurmService.GetPartition
get: "/apis/slurm/getPartition"
- selector: slurm.SlurmService.ListReservations
get: "/apis/slurm/listReservations"
- selector: slurm.SlurmService.GetReservation
get: "/apis/slurm/getReservation"
- selector: slurm.SlurmService.GetAllJobs
get: "/apis/slurm/getAllJobs"
- selector: slurm.SlurmService.GetJob
get: "/apis/slurm/getJob/{JobId}"
- selector: slurm.SlurmService.SubmitJob
post: "/apis/slurm/submitJob/data"
body: "data"
- selector: slurm.SlurmService.DeleteJob
delete: "/apis/slurm/deleteJob/{JobId}"
- selector: slurm.SlurmService.UpdateJob
post: "/apis/slurm/updateJob/data"
body: "data"
- selector: slurm.SlurmService.GetDiag
get: "/apis/slurm/getDiag"
- selector: slurm.SlurmService.GetQos
get: "/apis/slurm/getQos"
- selector: slurm.SlurmService.GetSlurmdbJobs
get: "/apis/slurm/getAllSlurmdbJobs"
- selector: slurm.SlurmService.GetSlurmdbJobById
get: "/apis/slurm/getSlurmdbJobById/{JobId}"
- selector: slurm.SlurmService.DeleteQos
delete: "/apis/slurm/deleteQos"
- selector: slurm.SlurmService.GetQosByName
get: "/apis/slurm/getQosByName/{name}"
- selector: slurm.SlurmService.AddQos
post: "/apis/slurm/addQos"

View File

@ -1,49 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message DiagReq{
SlurmVersion slurmVersion = 1;
}
message DiagResp{
StatsInfoResponseMsg statsInfoResponseMsg = 1;
}
message StatsInfoResponseMsg {
uint32 parts_packed =1;
int64 req_time=2;
int64 req_time_start=3;
uint32 server_thread_count=4;
uint32 agent_queue_size=5;
uint32 schedule_cycle_max=6;
uint32 schedule_cycle_last=7;
uint32 schedule_cycle_sum=8;
uint32 schedule_cycle_counter=9;
uint32 schedule_cycle_depth=10;
uint32 schedule_queue_len=11;
uint32 jobs_submitted=12;
uint32 jobs_started=13;
uint32 jobs_completed=14;
uint32 jobs_canceled=15;
uint32 jobs_failed=16;
uint32 bf_backfilled_jobs=17;
uint32 bf_last_backfilled_jobs=18;
uint32 bf_cycle_counter=19;
uint32 bf_cycle_sum=20;
uint32 bf_cycle_last=21;
uint32 bf_cycle_max=22;
uint32 bf_last_depth=23;
uint32 bf_last_depth_try=24;
uint32 bf_depth_sum=25;
uint32 bf_depth_try_sum=26;
uint32 bf_queue_len=27;
uint32 bf_queue_len_sum=28;
int64 bf_when_last_cycle=29;
uint32 bf_active=30;
}

View File

@ -1,314 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message UpdateJobReq{
uint32 JobId = 1;
Update_job_options data = 2;
SlurmVersion slurmVersion = 3;
}
message UpdateJobResp{
int32 Error_code=1;
}
message SubmitJobReq{
JobDescriptor data = 1;
SlurmVersion slurmVersion = 2;
}
message SubmitJobResp{
repeated Submit_response_msg submitResponseMsg = 1;
}
message DeleteJobReq{
uint32 JobId = 1;
SlurmVersion slurmVersion = 2;
}
message DeleteJobResp{
int32 Error_code=1;
}
message Argv{
string argv =1;
}
message Environment{
string environment =1;
}
message JobDescriptor{
string Account =1; /* charge to specified account */
string Acctg_freq =2; /* accounting polling intervals (seconds) */
string Alloc_node=3; /* node making resource allocation request
* NOTE: Normally set by slurm_submit* or
* slurm_allocate* function */
uint32 Alloc_resp_port=4; /* port to send allocation confirmation to */
uint32 Alloc_sid =5; /* local sid making resource allocation request
* NOTE: Normally set by slurm_submit* or
* slurm_allocate* function
* NOTE: Also used for update flags, see
* ALLOC_SID_* flags */
uint32 Argc =6; /* number of arguments to the script */
repeated Argv argv = 7; /* arguments to the script */
string Array_inx =8; /* job array index values */
//void *array_bitmap; /* NOTE: Set by slurmctld */
int64 Begin_time = 9; /* delay initiation until this time */
uint32 Ckpt_interval=10; /* periodically checkpoint this job */
string Ckpt_dir =11; /* directory to store checkpoint images */
string Comment =12; /* arbitrary comment (used by Moab scheduler) */
uint32 Contiguous=13; /* 1 if job requires contiguous nodes,
* 0 otherwise,default=0 */
string Cpu_bind=14; /* binding map for map/mask_cpu */
uint32 Cpu_bind_type=15; /* see cpu_bind_type_t */
string Dependency =16; /* synchronize job execution with other jobs */
int64 End_time=17; /* time by which job must complete, used for
* job update only now, possible deadline
* scheduling in the future */
repeated Environment environment=18; /* environment variables to set for job,
* name=value pairs, one per line */
uint32 Env_size =19; /* element count in environment */
string Exc_nodes =20; /* comma separated list of nodes excluded
* from job's allocation, default NONE */
string Features =21; /* comma separated list of required features,
* default NONE */
string Gres =22; /* comma separated list of required generic
* resources, default NONE */
uint32 Group_id =23; /* group to assume, if run as root. */
uint32 Immediate=24; /* 1 if allocate to run or fail immediately,
* 0 if to be queued awaiting resources */
uint32 Job_id =25; /* job ID, default set by SLURM */
uint32 Kill_on_node_fail=26; /* 1 if node failure to kill job,
* 0 otherwise,default=1 */
string Licenses=27; /* licenses required by the job */
uint32 Mail_type=28; /* see MAIL_JOB_ definitions above */
string Mail_user =29; /* user to receive notification */
string Mem_bind =30; /* binding map for map/mask_cpu */
uint32 Mem_bind_type=31; /* see mem_bind_type_t */
string Name =32; /* name of the job, default "" */
string Network=33; /* network use spec */
uint32 Nice =34; /* requested priority change,
* NICE_OFFSET == no change */
uint32 Num_tasks=35; /* number of tasks to be started,
* for batch only */
uint32 Open_mode=36; /* out/err open mode truncate or append,
* see OPEN_MODE_* */
uint32 Other_port=37; /* port to send various notification msg to */
uint32 Overcommit =38; /* over subscribe resources, for batch only */
string Partition=39; /* name of requested partition,
* default in SLURM config */
uint32 Plane_size =40; /* plane size when task_dist =
SLURM_DIST_PLANE */
uint32 Priority =41; /* relative priority of the job,
* explicitly set only for user root,
* 0 == held (don't initiate) */
uint32 Profile =42; /* Level of acct_gather_profile {all | none} */
string Qos =43; /* Quality of Service */
string Resp_host=44; /* NOTE: Set by slurmctld */
string Req_nodes=45; /* comma separated list of required nodes
* default NONE */
uint32 Requeue=46; /* enable or disable job requeue option */
string Reservation=47; /* name of reservation to use */
string Script=48; /* the actual job script, default NONE */
uint32 Shared =49; /* 1 if job can share nodes with other jobs,
* 0 if job needs exclusive access to the node,
* or NO_VAL to accept the system default.
* SHARED_FORCE to eliminate user control. */
//char **spank_job_env; environment variables for job prolog/epilog
// * scripts as set by SPANK plugins
uint32 Spank_job_env_size=50; /* element count in spank_env */
uint32 Task_dist =51; /* see enum task_dist_state */
uint32 Time_limit =52; /* maximum run time in minutes, default is
* partition limit */
uint32 Time_min =53; /* minimum run time in minutes, default is
* time_limit */
uint32 User_id=54; /* set only if different from current UID,
* can only be explicitly set by user root */
uint32 Wait_all_nodes=55; /* 0 to start job immediately after allocation
* 1 to start job after all nodes booted
* or NO_VAL to use system default */
uint32 Warn_signal=56; /* signal to send when approaching end time */
uint32 Warn_time=57; /* time before end to send signal (seconds) */
string Work_dir =58; /* pathname of working directory */
/* job constraints: */
uint32 Cpus_per_task=59; /* number of processors required for
* each task */
uint32 Min_cpus =60; /* minimum number of processors required,
* default=0 */
uint32 Max_cpus=61; /* maximum number of processors required,
* default=0 */
uint32 Min_nodes=62; /* minimum number of nodes required by job,
* default=0 */
uint32 Max_nodes=63; /* maximum number of nodes usable by job,
* default=0 */
uint32 Boards_per_node =64; /* boards per node required by job */
uint32 Sockets_per_board=65; /* sockets per board required by job */
uint32 Sockets_per_node =66; /* sockets per node required by job */
uint32 Cores_per_socket=67; /* cores per socket required by job */
uint32 Threads_per_core=68; /* threads per core required by job */
uint32 Ntasks_per_node =69; /* number of tasks to invoke on each node */
uint32 Ntasks_per_socket=70; /* number of tasks to invoke on
* each socket */
uint32 Ntasks_per_core =71; /* number of tasks to invoke on each core */
uint32 Ntasks_per_board=72; /* number of tasks to invoke on each board */
uint32 Pn_min_cpus =73; /* minimum # CPUs per node, default=0 */
uint32 Pn_min_memory=74; /* minimum real memory per node OR
* real memory per CPU | MEM_PER_CPU,
* default=0 (no limit) */
uint32 Pn_min_tmp_disk =75; /* minimum tmp disk per node,
* default=0 */
/*
* The following parameters are only meaningful on a Blue Gene
* system at present. Some will be of value on other system. Don't remove these
* they are needed for LCRM and others that can't talk to the opaque data type
* select_jobinfo.
*/
//uint16_t geometry[HIGHEST_DIMENSIONS]; node count in various
// * dimensions, e.g. X, Y, and Z
//uint16_t conn_type[HIGHEST_DIMENSIONS]; see enum connection_type
uint32 Reboot=76; /* force node reboot before startup */
uint32 Rotate=77; /* permit geometry rotation if set */
//char *blrtsimage; /* BlrtsImage for block */
//char *linuximage; /* LinuxImage for block */
//char *mloaderimage; /* MloaderImage for block */
//char *ramdiskimage; /* RamDiskImage for block */
/* End of Blue Gene specific values */
uint32 Req_switch =78; /* Minimum number of switches */
//dynamic_plugin_data_t *select_jobinfo; /* opaque data type,
// * SLURM internal use only */
string Std_err=79; /* pathname of stderr */
string Std_in =80; /* pathname of stdin */
string Std_out=81; /* pathname of stdout */
uint32 Wait4switch=82; /* Maximum time to wait for minimum switches */
string Wckey =83; /* wckey for job */
}
message Submit_response_msg{
uint32 Job_id = 1;
uint32 Step_id =2;
uint32 Error_code=3;
}
message JobInfoMsgReq{
uint32 JobId = 1;
SlurmVersion slurmVersion = 2;
}
message JobInfoMsgResp {
Job_info_msg jobInfoMsg =1;
}
message Job_info_msg{
int64 Last_update = 1;
uint32 Record_count = 2;
repeated Job_info Job_list = 3;
}
message Job_info{
string account = 1; /* charge to specified account */
string alloc_node = 2; /* local node making resource alloc */
uint32 alloc_sid =3; /* local sid making resource alloc */
uint32 array_job_id =4; /* job_id of a job array or 0 if N/A */
uint32 array_task_id =5; /* task_id of a job array */
uint32 assoc_id =6; /* association id for job */
uint32 batch_flag =7; /* 1 if batch: queued job with script */
string batch_host =8; /* name of host running batch script */
string batch_script=9; /* contents of batch script */
string command =10; /* command to be executed, built from submitted
* job's argv and NULL for salloc command */
string comment =11; /* arbitrary comment (used by Moab scheduler) */
uint32 contiguous =12; /* 1 if job requires contiguous nodes */
uint32 cpus_per_task=13; /* number of processors required for
* each task */
string dependency =14; /* synchronize job execution with other jobs */
uint32 derived_ec =15; /* highest exit code of all job steps */
int64 eligible_time =16; /* time job is eligible for running */
int64 end_time =17; /* time of termination, actual or expected */
string exc_nodes =18; /* comma separated list of excluded nodes */
int32 exc_node_inx =19; /* excluded list index pairs into node_table:
* start_range_1, end_range_1,
* start_range_2, .., -1 */
uint32 exit_code =20; /* exit code for job (status from wait call) */
string features =21; /* comma separated list of required features */
string gres =22; /* comma separated list of generic resources */
uint32 group_id =23; /* group job sumitted as */
uint32 job_id =24; /* job ID */
uint32 job_state =25; /* state of the job, see enum job_states */
string licenses =26; /* licenses required by the job */
uint32 max_cpus =27; /* maximum number of cpus usable by job */
uint32 max_nodes =28; /* maximum number of nodes usable by job */
uint32 boards_per_node =29; /* boards per node required by job */
uint32 sockets_per_board=30; /* sockets per board required by job */
uint32 sockets_per_node=31; /* sockets per node required by job */
uint32 cores_per_socket=32; /* cores per socket required by job */
uint32 threads_per_core=33; /* threads per core required by job */
string name =34; /* name of the job */
string network =35; /* network specification */
string nodes =36; /* list of nodes allocated to job */
uint32 nice =37; /* requested priority change */
int32 node_inx =38; /* list index pairs into node_table for *nodes:
* start_range_1, end_range_1,
* start_range_2, .., -1 */
uint32 ntasks_per_core =39; /* number of tasks to invoke on each core */
uint32 ntasks_per_node =40; /* number of tasks to invoke on each node */
uint32 ntasks_per_socket =41; /* number of tasks to invoke on each socket*/
uint32 ntasks_per_board =42; /* number of tasks to invoke on each board */
uint32 num_nodes =43; /* minimum number of nodes required by job */
uint32 num_cpus =44; /* minimum number of cpus required by job */
string partition =45; /* name of assigned partition */
uint32 pn_min_memory =46; /* minimum real memory per node, default=0 */
uint32 pn_min_cpus =47; /* minimum # CPUs per node, default=0 */
uint32 pn_min_tmp_disk =48; /* minimum tmp disk per node, default=0 */
int64 pre_sus_time =49; /* time job ran prior to last suspend */
uint32 priority =50; /* relative priority of the job,
* 0=held, 1=required nodes DOWN/DRAINED */
uint32 profile =51; /* Level of acct_gather_profile {all | none} */
string qos =52; /* Quality of Service */
string req_nodes =53; /* comma separated list of required nodes */
int32 req_node_inx =54; /* required list index pairs into node_table:
* start_range_1, end_range_1,
* start_range_2, .., -1 */
uint32 req_switch =55; /* Minimum number of switches */
uint32 requeue =56; /* enable or disable job requeue option */
int64 resize_time =57; /* time of latest size change */
uint32 restart_cnt =58;/* count of job restarts */
string resv_name =59; /* reservation name */
/*dynamic_plugin_data_t *select_jobinfo;*/ /* opaque data type,
* process using
* slurm_get_select_jobinfo()
*/
/*job_resources_t *job_resrcs;*/ /* opaque data type, job resources */
uint32 shared =60; /* 1 if job can share nodes with other jobs */
uint32 show_flags =61; /* conveys level of details requested */
int64 start_time =62; /* time execution begins, actual or expected */
string state_desc =63; /* optional details for state_reason */
uint32 state_reason =64; /* reason job still pending or failed, see
* slurm.h:enum job_state_reason */
int64 submit_time =65; /* time of job submission */
int64 suspend_time =66; /* time job last suspended or resumed */
uint32 time_limit =67; /* maximum run time in minutes or INFINITE */
uint32 time_min =68; /* minimum run time in minutes or INFINITE */
uint32 user_id =69; /* user the job runs as */
int64 preempt_time =70; /* preemption signal time */
uint32 wait4switch =71;/* Maximum time to wait for minimum switches */
string wckey =72; /* wckey for job */
string work_dir =73; /* pathname of working directory */
}
message Update_job_options {
string Partition =1;
string Qos =2;
uint32 Num_tasks =3;
uint32 Ntasks_per_node =4;
uint32 Ntasks_per_socket =5;
uint32 Ntasks_per_core =6;
uint32 Min_nodes =7;
uint32 Max_nodes =8;
}

View File

@ -1,56 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message NodeInfo{
string Arch = 1 ;
uint32 Boards = 2 ;
int64 Boot_time = 3 ;
uint32 Cores = 4 ;
uint32 Cpu_load = 5 ;
uint32 Cpus = 6 ;
string Features = 7;
string Gres = 8 ;
string Name = 9 ;
string Node_addr = 10 ;
string Node_hostname = 11 ;
uint32 Node_state = 12 ;
string Os = 13 ;
uint64 Real_memory = 14 ;
string Reason = 15 ;
int64 Reason_time = 16 ;
uint32 Reason_uid = 17 ;
int64 Slurmd_start_time = 18 ;
uint32 Sockets = 19 ;
uint32 Threads = 20 ;
uint32 Tmp_disk = 21 ;
uint32 Weight = 22 ;
}
message ListNodesReq{
SlurmVersion slurm_version = 1;
}
message ListNodesResp {
repeated NodeInfo node_infos = 1;
}
message GetNodeReq{
SlurmVersion slurm_version = 1;
string node_name = 2;
}
message GetNodeResp {
repeated NodeInfo node_infos = 1;
}
/*message Nodes_info_msg{
int64 Last_update =1;
uint32 Record_count =2;
uint32 Error_code =3;
repeated NodeInfo node_infos =4;
}*/

View File

@ -1,54 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message PartitionInfo{
string Allow_alloc_nodes =1;
string Allow_groups =2;
string Alternate =3;
uint32 Cr_type =4;
uint64 Def_mem_per_cpu =5;
uint32 Default_time = 6;
uint32 Flags =7;
uint32 Grace_time =8;
uint32 Max_cpus_per_node =9;
uint64 Max_mem_per_cpu =10;
uint32 Max_nodes =11;
uint32 Max_share =12;
uint32 Max_time =13;
uint32 Min_nodes =14;
string Name =15;
int32 Node_inx =16;
string Nodes =17;
uint32 Preempt_mode =18;
uint32 State_up =19;
uint32 Total_cpus =20;
uint32 Total_nodes =21;
}
message ListPartitionsReq{
SlurmVersion SlurmVersion = 1;
}
message ListPartitionsResp{
repeated PartitionInfo Partition_list =1;
}
message GetPartitionReq{
SlurmVersion slurm_version = 1;
string partition_name = 2;
}
message GetPartitionResp {
repeated PartitionInfo partition_infos = 1;
}
/*message Partition_info_msg{
int64 Last_update =1;
uint32 Record_count =2;
uint32 Error_code =3;
repeated PartitionInfo Partition_list =4;
}*/

View File

@ -1,14 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message PingInfoMsgReq{
SlurmVersion SlurmVersion = 1;
int32 controller = 2;
}
message PingInfoMsgResp{
int32 Ping_result =1;
}

View File

@ -1,46 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message ReservationInfo{
string Accounts = 1;
int64 End_time =2;
string Features =3;
uint32 Flags =4;
string Licenses =5;
string Name =6;
uint32 Node_cnt =7;
uint32 Core_cnt =8;
int32 Node_inx =9;
string Node_list =10;
string Partition =11;
int64 Start_time =12;
string Users =13;
}
message ListReservationsReq{
SlurmVersion SlurmVersion = 1;
}
message ListReservationsResp{
repeated ReservationInfo Reservation_list =1;
}
message GetReservationReq{
SlurmVersion slurm_version = 1;
string reservation_name = 2;
}
message GetReservationResp {
repeated ReservationInfo reservation_infos = 1;
}
/*message Partition_info_msg{
int64 Last_update =1;
uint32 Record_count =2;
uint32 Error_code =3;
repeated PartitionInfo Partition_list =4;
}*/

View File

@ -1,71 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "google/protobuf/timestamp.proto";
import "idl/static.proto";
import "idl/slurmdb_assoc.proto";
import "idl/slurmdb_coord.proto";
message AccountInfo{
repeated AssociationInfo assoc_list = 1;
repeated CoordInfo coordinators = 2;
string description = 3;
string name = 4;
string organization = 5;
}
message ListAccountsReq{
SlurmVersion slurm_version = 1;
}
message ListAccountsResp {
repeated AccountInfo account_infos = 1;
}
message GetAccountReq{
SlurmVersion slurm_version = 1;
string account_name = 2;
}
message GetAccountResp {
repeated AccountInfo account_infos = 1;
}
message AddAccountReq{
SlurmVersion slurm_version = 1;
string clusters =2;
string default_qos=3;
string description=4;
string fair_share=5;
string grp_cpu_mins=6;
string grp_cpus=7;
string grp_jobs=8;
string grp_memory=9;
string grp_nodes=10;
string grp_submit_jobs=11;
string grp_wall=12;
string max_cpu_mins=13;
string max_cpus=14;
string max_jobs=15;
string max_nodes=16;
string max_submit_jobs=17;
string max_wall=18;
string names=19;
string organization=20;
string parent=21;
string qos_level=22;
}
message AddAccountResp {
string result = 1;
}
message DeleteAccountReq{
SlurmVersion slurm_version = 1;
string names=2;
}
message DeleteAccountResp {
string result = 1;
}

View File

@ -1,12 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "google/protobuf/timestamp.proto";
import "idl/static.proto";
message AccountingInfo{
int64 alloc_secs = 1 ;
int32 id = 2 ;
google.protobuf.Timestamp period_start = 3;
}

View File

@ -1,76 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "google/protobuf/timestamp.proto";
import "idl/static.proto";
import "idl/slurmdb_accounting.proto";
import "idl/slurmdb_qos.proto";
message AssocUsageInfo{
}
message AssociationInfo{
repeated AccountingInfo accounting_list = 1 ;
string acct = 2 ;
string cluster = 3 ;
int32 def_qos_id = 4 ;
int64 grp_cpu_mins = 5 ;
int64 grp_gpu_run_mins = 6 ;
int32 grp_cpus = 7 ;
int32 grp_jobs = 8 ;
int32 grp_mem = 9 ;
int32 grp_nodes = 10 ;
int32 grp_submit_jobs = 11 ;
int32 grp_wall = 12 ;
int32 id = 13 ;
int32 is_def = 14 ;
int32 lft = 15 ;
int64 max_cpu_mins_pj = 16 ;
int64 max_cpu_run_mins = 17 ;
int32 max_cpus_pj = 18 ;
int32 max_jobs = 19 ;
int32 max_nodes_pj = 20 ;
int32 max_submit_jobs = 21 ;
int32 max_wall_pj = 22 ;
string parent_acct = 23 ;
int32 parent_id = 24 ;
string partition = 25 ;
repeated Slurmdb_qos_rec qos_list = 26 ;
int32 rgt = 27 ;
int32 shares_raw = 28 ;
int32 uid = 29 ;
AssocUsageInfo assoc_usage = 30 ;
string user = 31 ;
}
message ListAssociationsReq{
SlurmVersion slurm_version = 1;
}
message ListAssociationsResp {
repeated AssociationInfo assoc_infos = 1;
}
message GetAssociationReq{
SlurmVersion slurm_version = 1;
string cluster = 2;
string account = 3;
string user = 4;
string partition = 5;
}
message GetAssociationResp {
repeated AssociationInfo assoc_infos = 1;
}
message SetAssociationReq{
SlurmVersion slurm_version = 1;
AssociationInfo assoc_info = 2;
}
message SetAssociationResp {
bool result = 1;
}

View File

@ -1,69 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "google/protobuf/timestamp.proto";
import "idl/static.proto";
import "idl/slurmdb_accounting.proto";
import "idl/slurmdb_assoc.proto";
message ClusterInfo{
repeated AccountingInfo accounting_list = 1 ;
int32 classification = 2 ;
string control_host = 3 ;
int32 control_port = 4 ;
int32 cpu_count = 5 ;
int32 dimensions = 6 ;
int32 dim_size = 7 ;
int32 flags = 8 ;
string name = 9 ;
string nodes = 10 ;
int32 plugin_id_select = 11 ;
AssociationInfo root_assoc = 12 ;
int32 rpc_version = 13 ;
}
message ListClustersReq{
SlurmVersion slurm_version = 1;
}
message ListClustersResp {
repeated ClusterInfo cluster_infos = 1;
}
message GetClusterReq{
SlurmVersion slurm_version = 1;
string cluster_name = 2;
}
message GetClusterResp {
repeated ClusterInfo cluster_infos = 1;
}
message AddClusterReq{
SlurmVersion slurm_version = 1;
string name =2;
string nodes =3;
string control_port = 4 ;
string cpu_count = 5 ;
string dimensions = 6 ;
string dim_size = 7 ;
string flags = 8 ;
string classification = 9 ;
string control_host = 10 ;
string plugin_id_select = 11 ;
string rpc_version = 13 ;
}
message AddClusterResp {
string result = 1;
}
message DeleteClusterReq{
SlurmVersion slurm_version = 1;
string names=2;
}
message DeleteClusterResp {
string result = 1;
}

View File

@ -1,12 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "google/protobuf/timestamp.proto";
import "idl/static.proto";
message CoordInfo{
string name = 1 ;
int32 direct = 2 ;
}

View File

@ -1,92 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message SlurmDbJobReq{
SlurmVersion slurmVersion = 1;
uint32 JobId = 2;
}
message SlurmDbJobResp{
repeated Slurmdb_job_rec slurmdb_job_rec = 1;
}
message Slurmdb_job_rec {
uint32 alloc_cpu = 1;
uint32 alloc_nodes =2;
string account= 3;
uint32 associd=4;
string blockid=5;
string cluster=6;
uint32 derived_ec=7;
string derived_es=8;
uint32 elapsed=9;
int64 eligible=10;
int64 end=11;
uint32 exitcode=12;
// void *first_step_ptr;
uint32 gid=13;
uint32 jobid=14;
string jobname=15;
uint32 lft=16;
string partition=17;
string nodes=18;
uint32 priority=19;
uint32 qosid=20;
uint32 req_cpus=21;
uint32 req_mem=22;
uint32 requid=23;
uint32 resvid=24;
uint32 show_full=25;
int64 start=26;
uint32 state=27;
// repeated slurmdb_stats_t stats=28;
// List steps;
int64 submit=28;
uint32 suspended=29;
uint32 sys_cpu_sec=30;
uint32 sys_cpu_usec=31;
uint32 timelimit=32;
uint32 tot_cpu_sec=33;
uint32 tot_cpu_usec=34;
uint32 track_steps=35;
uint32 uid=36;
string user=37;
uint32 user_cpu_sec=38;
uint32 user_cpu_usec=39;
string wckey=40;
uint32 wckeyid=41;
}
message slurmdb_stats_t{
double act_cpufreq =1;
double cpu_ave=2;
double consumed_energy=3;
uint32 cpu_min=4;
uint32 cpu_min_nodeid=5;
uint32 cpu_min_taskid=6;
double disk_read_ave=7;
double disk_read_max=8;
uint32 disk_read_max_nodeid=9;
uint32 disk_read_max_taskid=10;
double disk_write_ave=11;
double disk_write_max=12;
uint32 disk_write_max_nodeid=13;
uint32 disk_write_max_taskid=14;
double pages_ave=15;
uint32 pages_max=16;
uint32 pages_max_nodeid=17;
uint32 pages_max_taskid=18;
double rss_ave=19;
uint32 rss_max=20;
uint32 rss_max_nodeid=21;
uint32 rss_max_taskid=22;
double vsize_ave=23;
uint32 vsize_max=24;
uint32 vsize_max_nodeid=25;
uint32 vsize_max_taskid=26;
}

View File

@ -1,96 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "idl/static.proto";
message QosReq{
SlurmVersion slurmVersion = 1;
string name=2;
}
message QosResp{
repeated Slurmdb_qos_rec slurmdb_qos_rec = 1;
}
message DeleteQosReq{
SlurmVersion slurmVersion = 1;
string names=2;
}
message DeleteQosResp {
string result =1;
}
message AddQosReq {
SlurmVersion slurmVersion = 1;
Slurmdb_qos_rec slurmdb_qos_rec=2;
}
message AddQosResp {
string result =1;
}
message Qos_info_msg {
uint32 Record_count = 1;
repeated Slurmdb_qos_rec slurmdb_qos_rec = 2;
}
message Slurmdb_qos_rec{
string Description=1;
uint32 Id=2;
uint32 Flags =3; /* flags for various things to enforce or
override other limits */
uint32 Grace_time =4; /* preemption grace time */
uint64 Grp_cpu_mins =5; /* max number of cpu minutes all jobs
* running under this qos can run for */
uint64 Grp_cpu_run_mins=6; /* max number of cpu minutes all jobs
* running under this qos can
* having running at one time */
uint32 Grp_cpus =7; /* max number of cpus this qos
can allocate at one time */
uint32 Grp_jobs=8; /* max number of jobs this qos can run
* at one time */
uint32 Grp_mem =9; /* max amount of memory this qos
can allocate at one time */
uint32 Grp_nodes=10; /* max number of nodes this qos
can allocate at once */
uint32 Grp_submit_jobs=11; /* max number of jobs this qos can submit at
* one time */
uint32 Grp_wall =12; /* total time in hours this qos can run for */
uint64 Max_cpu_mins_pj=13; /* max number of cpu mins a job can
* use with this qos */
uint64 Max_cpu_run_mins_pu=14; /* max number of cpu mins a user can
* allocate at a given time when
* using this qos (Not yet valid option) */
uint32 Max_cpus_pj =15; /* max number of cpus a job can
* allocate with this qos */
uint32 Max_cpus_pu=16; /* max number of cpus a user can
* allocate with this qos at one time */
uint32 Max_jobs_pu =17; /* max number of jobs a user can
* run with this qos at one time */
uint32 Max_nodes_pj =18; /* max number of nodes a job can
* allocate with this qos at one time */
uint32 Max_nodes_pu=19; /* max number of nodes a user can
* allocate with this qos at one time */
uint32 Max_submit_jobs_pu=20; /* max number of jobs a user can
submit with this qos at once */
uint32 Max_wall_pj =21; /* longest time this
* qos can run a job */
string Name =22;
//bitstr_t *preempt_bitstr; /* other qos' this qos can preempt */
repeated string preempt_list = 23; /* List preempt_list; list of char *'s only used to add or
* change the other qos' this can preempt,
* when doing a get use the preempt_bitstr */
uint32 preempt_mode=24; /* See PREEMPT_MODE_* in slurm/slurm.h */
uint32 priority=25; /* ranged int needs to be a unint for
* heterogeneous systems */
//assoc_mgr_qos_usage_t *usage; /* For internal use only, DON'T PACK */
double usage_factor=26; /* double, factor to apply to usage in this qos */
double usage_thres=27; /* double, percent of effective usage of an
association when breached will deny
pending and new jobs */
}

View File

@ -1,75 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "google/protobuf/timestamp.proto";
import "idl/static.proto";
import "idl/slurmdb_coord.proto";
import "idl/slurmdb_wckey.proto";
import "idl/slurmdb_assoc.proto";
message UserInfoList{
repeated UserInfo userInfos = 1 ;
}
message UserInfo{
int32 adminLevel = 1 ;
repeated AssociationInfo association_list= 2 ;
repeated CoordInfo coord_list = 3 ;
string default_acct = 4 ;
string default_wckey = 5 ;
string name = 6 ;
string oldName = 7 ;
int32 uid = 8 ;
repeated WckeyInfo wckey_list = 9 ;
}
message ListUsersReq{
SlurmVersion slurm_version = 1;
}
message ListUsersResp {
repeated UserInfo user_infos =1;
}
message GetUserReq{
SlurmVersion slurm_version = 1;
string user_name = 2;
}
message GetUserResp {
repeated UserInfo user_info = 1;
}
message AddUserReq{
SlurmVersion slurm_version = 1;
string accounts=2;
string admin_level=3;
string clusters=4;
string default_account=5;
string default_qos=6;
string default_wckey=7;
string fair_share=8;
string max_cpu_mins=9;
string max_cpus=10;
string max_jobs=11;
string max_nodes=12;
string max_submit_jobs=13;
string max_wall=14;
string names=15;
string partitions=16;
string qos_level=17;
}
message AddUserResp {
string result =1;
}
message DeleteUserReq{
SlurmVersion slurm_version = 1;
string names=2;
}
message DeleteUserResp {
string result =1;
}

View File

@ -1,34 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
import "google/protobuf/timestamp.proto";
import "idl/static.proto";
import "idl/slurmdb_accounting.proto";
message WckeyInfo{
repeated AccountingInfo accounting_list = 1 ;
string cluster= 2 ;
int32 id = 3 ;
int32 is_def = 4 ;
string name = 5 ;
int32 uid = 6 ;
string user = 7 ;
}
message ListWckeysReq{
SlurmVersion slurm_version = 1;
}
message ListWckeysResp {
repeated WckeyInfo wckey_infos =1;
}
message GetWckeyReq{
SlurmVersion slurm_version = 1;
string wckey = 2;
}
message GetWckeyResp {
repeated WckeyInfo wckey_info = 1;
}

View File

@ -1,12 +0,0 @@
syntax = "proto3";
package slurm;
option go_package = "/slurmpb";
// slurm version
enum SlurmVersion {
// 0 - tianhe hpc
tianhe = 0;
// 1 - shenwei hpc
shenwei = 1;
}

View File

@ -1,30 +0,0 @@
package main
import (
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
slurmserver "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/config"
"code.gitlink.org.cn/JCCE/PCM.git/common/global"
"code.gitlink.org.cn/JCCE/PCM.git/common/server"
"go.uber.org/zap"
"google.golang.org/grpc"
)
func main() {
// 初始化配置以及数据库
config.InitConfig()
// 新建一个zap logger实例
logger, _ := zap.NewDevelopment()
// logger.Sugar().Fatal 直接可以少几行判错的代码
logger.Sugar().Fatal(server.RunGRPCServer(&server.GRPCConfig{
Name: "pcm_slurm",
Addr: global.S.SlurmInfo.Address,
RegisterFunc: func(g *grpc.Server) {
slurmpb.RegisterSlurmServiceServer(g, &slurmserver.Server{})
},
Logger: logger,
}))
}

View File

@ -1,3 +0,0 @@
package rest
//TODO

View File

@ -1,342 +0,0 @@
package server
import (
slurmpb "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"context"
"github.com/golang/glog"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Server struct {
slurmpb.UnimplementedSlurmServiceServer
}
// ListUsers return all slurm users
func (s *Server) ListUsers(ctx context.Context, req *slurmpb.ListUsersReq) (*slurmpb.ListUsersResp, error) {
resp, err := ListUsers(ctx, req)
if err != nil {
glog.Errorf("ListSlurmUsers error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetUser return specific slurm user
func (s *Server) GetUser(ctx context.Context, req *slurmpb.GetUserReq) (*slurmpb.GetUserResp, error) {
resp, err := GetUser(ctx, req)
if err != nil {
glog.Errorf("GetSlurmUser error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// AddUser add slurm user
func (s *Server) AddUser(ctx context.Context, req *slurmpb.AddUserReq) (*slurmpb.AddUserResp, error) {
resp, err := AddUser(ctx, req)
if err != nil {
glog.Errorf("AddSlurmUser error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// DeleteUser delete specific slurm user
func (s *Server) DeleteUser(ctx context.Context, req *slurmpb.DeleteUserReq) (*slurmpb.DeleteUserResp, error) {
resp, err := DeleteUser(ctx, req)
if err != nil {
glog.Errorf("DeleteSlurmUser error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListAssociations return all slurm associations
func (s *Server) ListAssociations(ctx context.Context, req *slurmpb.ListAssociationsReq) (*slurmpb.ListAssociationsResp, error) {
resp, err := ListAssociations(ctx, req)
if err != nil {
glog.Errorf("ListSlurmAssociations error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetAssociation return specific slurm associations
func (s *Server) GetAssociation(ctx context.Context, req *slurmpb.GetAssociationReq) (*slurmpb.GetAssociationResp, error) {
resp, err := GetAssociation(ctx, req)
if err != nil {
glog.Errorf("GetSlurmAssociations error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListAccounts return all slurm accounts
func (s *Server) ListAccounts(ctx context.Context, req *slurmpb.ListAccountsReq) (*slurmpb.ListAccountsResp, error) {
resp, err := ListAccounts(ctx, req)
if err != nil {
glog.Errorf("ListSlurmAccounts error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetAccount return specific slurm account
func (s *Server) GetAccount(ctx context.Context, req *slurmpb.GetAccountReq) (*slurmpb.GetAccountResp, error) {
resp, err := GetAccount(ctx, req)
if err != nil {
glog.Errorf("GetSlurmAccount error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// AddAccount return result
func (s *Server) AddAccount(ctx context.Context, req *slurmpb.AddAccountReq) (*slurmpb.AddAccountResp, error) {
resp, err := AddAccount(ctx, req)
if err != nil {
glog.Errorf("Add error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// DeleteAccount return result
func (s *Server) DeleteAccount(ctx context.Context, req *slurmpb.DeleteAccountReq) (*slurmpb.DeleteAccountResp, error) {
resp, err := DeleteAccount(ctx, req)
if err != nil {
glog.Errorf("Delete error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListQoss return all slurm qos
func (s *Server) GetQos(ctx context.Context, req *slurmpb.QosReq) (*slurmpb.QosResp, error) {
resp, err := GetQos(ctx, req)
if err != nil {
glog.Errorf("ListSlurmQoss error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListWckeys return all slurm wckeys
func (s *Server) ListWckeys(ctx context.Context, req *slurmpb.ListWckeysReq) (*slurmpb.ListWckeysResp, error) {
resp, err := ListWckeys(ctx, req)
if err != nil {
glog.Errorf("ListSlurmWckeys error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetWckey return specific slurm wckey
func (s *Server) GetWckey(ctx context.Context, req *slurmpb.GetWckeyReq) (*slurmpb.GetWckeyResp, error) {
resp, err := GetWckey(ctx, req)
if err != nil {
glog.Errorf("GetSlurmWckey error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListUsers return all slurm Clusters
func (s *Server) ListClusters(ctx context.Context, req *slurmpb.ListClustersReq) (*slurmpb.ListClustersResp, error) {
resp, err := ListClusters(ctx, req)
if err != nil {
glog.Errorf("ListSlurmUsers error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetUser return specific slurm user
func (s *Server) GetCluster(ctx context.Context, req *slurmpb.GetClusterReq) (*slurmpb.GetClusterResp, error) {
resp, err := GetCluster(ctx, req)
if err != nil {
glog.Errorf("GetSlurmUser error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// DeleteUser delete specific slurm user
func (s *Server) DeleteCluster(ctx context.Context, req *slurmpb.DeleteClusterReq) (*slurmpb.DeleteClusterResp, error) {
resp, err := DeleteCluster(ctx, req)
if err != nil {
glog.Errorf("DeleteSlurmUser error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// AddCluster add slurm user
func (s *Server) AddCluster(ctx context.Context, req *slurmpb.AddClusterReq) (*slurmpb.AddClusterResp, error) {
resp, err := AddCluster(ctx, req)
if err != nil {
glog.Errorf("AddSlurmCluster error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetNode return specific slurm user
func (s *Server) GetNode(ctx context.Context, req *slurmpb.GetNodeReq) (*slurmpb.GetNodeResp, error) {
resp, err := GetNode(ctx, req)
if err != nil {
glog.Errorf("GetSlurmUser error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListUsers return all slurm Clusters
func (s *Server) ListNodes(ctx context.Context, req *slurmpb.ListNodesReq) (*slurmpb.ListNodesResp, error) {
resp, err := ListNodes(ctx, req)
if err != nil {
glog.Errorf("ListSlurmNodes error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListUsers return all slurm Clusters
func (s *Server) ListPartitions(ctx context.Context, req *slurmpb.ListPartitionsReq) (*slurmpb.ListPartitionsResp, error) {
resp, err := ListPartitions(ctx, req)
if err != nil {
glog.Errorf("ListPartitions error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetNode return specific slurm user
func (s *Server) GetPartition(ctx context.Context, req *slurmpb.GetPartitionReq) (*slurmpb.GetPartitionResp, error) {
resp, err := GetPartition(ctx, req)
if err != nil {
glog.Errorf("GetPartition error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// GetReservation return specific slurm user
func (s *Server) GetReservation(ctx context.Context, req *slurmpb.GetReservationReq) (*slurmpb.GetReservationResp, error) {
resp, err := GetReservation(ctx, req)
if err != nil {
glog.Errorf("GetPartition error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListUsers return all slurm Clusters
func (s *Server) ListReservations(ctx context.Context, req *slurmpb.ListReservationsReq) (*slurmpb.ListReservationsResp, error) {
resp, err := ListReservations(ctx, req)
if err != nil {
glog.Errorf("ListReservations error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) GetAllJobs(ctx context.Context, req *slurmpb.JobInfoMsgReq) (*slurmpb.JobInfoMsgResp, error) {
resp, err := GetAllJobs(ctx, req)
if err != nil {
glog.Errorf("GetAllJobs error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) GetJob(ctx context.Context, req *slurmpb.JobInfoMsgReq) (*slurmpb.JobInfoMsgResp, error) {
resp, err := GetJob(ctx, req)
if err != nil {
glog.Errorf("GetJob error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) SubmitJob(ctx context.Context, req *slurmpb.SubmitJobReq) (*slurmpb.SubmitJobResp, error) {
resp, err := SubmitJob(ctx, req)
if err != nil {
glog.Errorf("SubmitJob error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) DeleteJob(ctx context.Context, req *slurmpb.DeleteJobReq) (*slurmpb.DeleteJobResp, error) {
resp, err := DeleteJob(ctx, req)
if err != nil {
glog.Errorf("DeleteJob error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) UpdateJob(ctx context.Context, req *slurmpb.UpdateJobReq) (*slurmpb.UpdateJobResp, error) {
resp, err := UpdateJob(ctx, req)
if err != nil {
glog.Errorf("UpdateJob error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) GetDiag(ctx context.Context, req *slurmpb.DiagReq) (*slurmpb.DiagResp, error) {
resp, err := GetDiag(ctx, req)
if err != nil {
glog.Errorf("GetDiag error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) GetSlurmdbJobs(ctx context.Context, req *slurmpb.SlurmDbJobReq) (*slurmpb.SlurmDbJobResp, error) {
resp, err := GetSlurmdbJobs(ctx, req)
if err != nil {
glog.Errorf("GetSlurmdbJobs error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) GetSlurmdbJobById(ctx context.Context, req *slurmpb.SlurmDbJobReq) (*slurmpb.SlurmDbJobResp, error) {
resp, err := GetSlurmdbJobById(ctx, req)
if err != nil {
glog.Errorf("GetSlurmdbJobById error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) DeleteQos(ctx context.Context, req *slurmpb.DeleteQosReq) (*slurmpb.DeleteQosResp, error) {
resp, err := DeleteQos(ctx, req)
if err != nil {
glog.Errorf("DeleteQos error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) AddQos(ctx context.Context, req *slurmpb.AddQosReq) (*slurmpb.AddQosResp, error) {
resp, err := AddQos(ctx, req)
if err != nil {
glog.Errorf("AddQos error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
func (s *Server) GetQosByName(ctx context.Context, req *slurmpb.QosReq) (*slurmpb.QosResp, error) {
resp, err := GetQosByName(ctx, req)
if err != nil {
glog.Errorf("GetQosByName error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}

View File

@ -1,313 +0,0 @@
package server
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
slurmer "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/common"
"context"
)
func ListUsers(ctx context.Context, req *pbslurm.ListUsersReq) (*pbslurm.ListUsersResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListUsers(ctx, req)
return resp, nil
}
func GetUser(ctx context.Context, req *pbslurm.GetUserReq) (*pbslurm.GetUserResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetUser(ctx, req)
return resp, nil
}
func AddUser(ctx context.Context, req *pbslurm.AddUserReq) (*pbslurm.AddUserResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.AddUser(ctx, req)
return resp, nil
}
func DeleteUser(ctx context.Context, req *pbslurm.DeleteUserReq) (*pbslurm.DeleteUserResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.DeleteUser(ctx, req)
return resp, nil
}
func ListAssociations(ctx context.Context, req *pbslurm.ListAssociationsReq) (*pbslurm.ListAssociationsResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListAssociations(ctx, req)
return resp, nil
}
func GetAssociation(ctx context.Context, req *pbslurm.GetAssociationReq) (*pbslurm.GetAssociationResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetAssociation(ctx, req)
return resp, nil
}
func ListAccounts(ctx context.Context, req *pbslurm.ListAccountsReq) (*pbslurm.ListAccountsResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListAccounts(ctx, req)
return resp, nil
}
func GetAccount(ctx context.Context, req *pbslurm.GetAccountReq) (*pbslurm.GetAccountResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetAccount(ctx, req)
return resp, nil
}
func AddAccount(ctx context.Context, req *pbslurm.AddAccountReq) (*pbslurm.AddAccountResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.AddAccount(ctx, req)
return resp, nil
}
func DeleteAccount(ctx context.Context, req *pbslurm.DeleteAccountReq) (*pbslurm.DeleteAccountResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.DeleteAccount(ctx, req)
return resp, nil
}
func GetQos(ctx context.Context, req *pbslurm.QosReq) (*pbslurm.QosResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetQos(ctx, req)
return resp, nil
}
func ListWckeys(ctx context.Context, req *pbslurm.ListWckeysReq) (*pbslurm.ListWckeysResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListWckeys(ctx, req)
return resp, nil
}
func GetWckey(ctx context.Context, req *pbslurm.GetWckeyReq) (*pbslurm.GetWckeyResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetWckey(ctx, req)
return resp, nil
}
func ListClusters(ctx context.Context, req *pbslurm.ListClustersReq) (*pbslurm.ListClustersResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListClusters(ctx, req)
return resp, nil
}
func GetCluster(ctx context.Context, req *pbslurm.GetClusterReq) (*pbslurm.GetClusterResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetCluster(ctx, req)
return resp, nil
}
func DeleteCluster(ctx context.Context, req *pbslurm.DeleteClusterReq) (*pbslurm.DeleteClusterResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.DeleteCluster(ctx, req)
return resp, nil
}
func AddCluster(ctx context.Context, req *pbslurm.AddClusterReq) (*pbslurm.AddClusterResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.AddCluster(ctx, req)
return resp, nil
}
func ListNodes(ctx context.Context, req *pbslurm.ListNodesReq) (*pbslurm.ListNodesResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListNodes(ctx, req)
return resp, nil
}
func GetNode(ctx context.Context, req *pbslurm.GetNodeReq) (*pbslurm.GetNodeResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetNode(ctx, req)
return resp, nil
}
func ListPartitions(ctx context.Context, req *pbslurm.ListPartitionsReq) (*pbslurm.ListPartitionsResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListPartitions(ctx, req)
return resp, nil
}
func GetPartition(ctx context.Context, req *pbslurm.GetPartitionReq) (*pbslurm.GetPartitionResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetPartition(ctx, req)
return resp, nil
}
func GetReservation(ctx context.Context, req *pbslurm.GetReservationReq) (*pbslurm.GetReservationResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetReservation(ctx, req)
return resp, nil
}
func ListReservations(ctx context.Context, req *pbslurm.ListReservationsReq) (*pbslurm.ListReservationsResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.ListReservations(ctx, req)
return resp, nil
}
func GetAllJobs(ctx context.Context, req *pbslurm.JobInfoMsgReq) (*pbslurm.JobInfoMsgResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetAllJobs(ctx, req)
return resp, nil
}
func GetJob(ctx context.Context, req *pbslurm.JobInfoMsgReq) (*pbslurm.JobInfoMsgResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetJob(ctx, req)
return resp, nil
}
func SubmitJob(ctx context.Context, req *pbslurm.SubmitJobReq) (*pbslurm.SubmitJobResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.SubmitJob(ctx, req)
return resp, nil
}
func DeleteJob(ctx context.Context, req *pbslurm.DeleteJobReq) (*pbslurm.DeleteJobResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.DeleteJob(ctx, req)
return resp, nil
}
func UpdateJob(ctx context.Context, req *pbslurm.UpdateJobReq) (*pbslurm.UpdateJobResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.UpdateJob(ctx, req)
return resp, nil
}
func GetDiag(ctx context.Context, req *pbslurm.DiagReq) (*pbslurm.DiagResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetDiag(ctx, req)
return resp, nil
}
func GetSlurmdbJobs(ctx context.Context, req *pbslurm.SlurmDbJobReq) (*pbslurm.SlurmDbJobResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetSlurmdbJobs(ctx, req)
return resp, nil
}
func GetSlurmdbJobById(ctx context.Context, req *pbslurm.SlurmDbJobReq) (*pbslurm.SlurmDbJobResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetSlurmdbJobById(ctx, req)
return resp, nil
}
func DeleteQos(ctx context.Context, req *pbslurm.DeleteQosReq) (*pbslurm.DeleteQosResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.DeleteQos(ctx, req)
return resp, nil
}
func AddQos(ctx context.Context, req *pbslurm.AddQosReq) (*pbslurm.AddQosResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.AddQos(ctx, req)
return resp, nil
}
func GetQosByName(ctx context.Context, req *pbslurm.QosReq) (*pbslurm.QosResp, error) {
slurm, _ := slurmer.SelectSlurmVersion(req.SlurmVersion)
if slurm == nil {
return nil, nil
}
resp, _ := slurm.GetQosByName(ctx, req)
return resp, nil
}

View File

@ -1,130 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"code.gitlink.org.cn/JCCE/PCM.git/common/ssh"
"context"
"strings"
)
func (slurmStruct SlurmStruct) ListAccounts(ctx context.Context, req *pbslurm.ListAccountsReq) (*pbslurm.ListAccountsResp, error) {
acctList := tianhe.GetAcctInfo()
resp := pbslurm.ListAccountsResp{}
for _, acct := range acctList.AcctInfoList {
//AcctInfoResult := pbslurm.AccountInfo{}
//AcctInfoResult.Name = Acct.Name
acctInfoResult := acct
resp.AccountInfos = append(resp.AccountInfos, &acctInfoResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) GetAccount(ctx context.Context, req *pbslurm.GetAccountReq) (*pbslurm.GetAccountResp, error) {
acctList := tianhe.GetAcctInfo()
resp := pbslurm.GetAccountResp{}
for _, acct := range acctList.AcctInfoList {
acctInfoResult := acct
if strings.Contains(acct.Name, req.AccountName) {
resp.AccountInfos = append(resp.AccountInfos, &acctInfoResult)
}
}
return &resp, nil
}
func (slurmStruct SlurmStruct) AddAccount(ctx context.Context, req *pbslurm.AddAccountReq) (*pbslurm.AddAccountResp, error) {
cmd := "/usr/local/bin/sacctmgr add account "
cmd = cmd + req.Names
if len(req.Clusters) != 0 {
cmd = cmd + " Clusters=" + req.Clusters
}
if len(req.DefaultQos) != 0 {
cmd = cmd + " DefaultQOS=" + req.DefaultQos
}
if len(req.Description) != 0 {
cmd = cmd + " Description=\"" + req.Description + "\""
}
if len(req.FairShare) != 0 {
cmd = cmd + " Fairshare=" + req.FairShare
}
if len(req.GrpCpuMins) != 0 {
cmd = cmd + " GrpCPUMins=" + req.GrpCpuMins
}
if len(req.GrpCpus) != 0 {
cmd = cmd + " GrpCPUs=" + req.GrpCpus
}
if len(req.GrpJobs) != 0 {
cmd = cmd + " GrpJobs=" + req.GrpJobs
}
if len(req.GrpMemory) != 0 {
cmd = cmd + " GrpMemory=" + req.GrpMemory
}
if len(req.GrpNodes) != 0 {
cmd = cmd + " GrpNodes=" + req.GrpNodes
}
if len(req.GrpSubmitJobs) != 0 {
cmd = cmd + " GrpSubmitJob=" + req.GrpSubmitJobs
}
if len(req.GrpWall) != 0 {
cmd = cmd + " GrpWall=" + req.GrpWall
}
if len(req.MaxCpuMins) != 0 {
cmd = cmd + " MaxCPUMins=" + req.MaxCpuMins
}
if len(req.MaxCpus) != 0 {
cmd = cmd + " MaxCPUs=" + req.MaxCpus
}
if len(req.MaxJobs) != 0 {
cmd = cmd + " MaxJobs=" + req.MaxJobs
}
if len(req.MaxNodes) != 0 {
cmd = cmd + " MaxNodes=" + req.MaxNodes
}
if len(req.MaxSubmitJobs) != 0 {
cmd = cmd + " MaxSubmitJobs=" + req.MaxSubmitJobs
}
if len(req.MaxWall) != 0 {
cmd = cmd + " MaxWall=" + req.MaxWall
}
if len(req.Organization) != 0 {
cmd = cmd + " Organization=" + req.Organization
}
if len(req.Parent) != 0 {
cmd = cmd + " Parent=" + req.Parent
}
if len(req.QosLevel) != 0 {
cmd = cmd + " QosLevel=" + req.QosLevel
}
cmd = cmd + " -i"
result := ssh.ExecCommand(cmd)
resp := pbslurm.AddAccountResp{}
resp.Result = result
return &resp, nil
}
func (slurmStruct SlurmStruct) DeleteAccount(ctx context.Context, req *pbslurm.DeleteAccountReq) (*pbslurm.DeleteAccountResp, error) {
cmd := "/usr/local/bin/sacctmgr delete account "
cmd = cmd + req.Names
cmd = cmd + " -i"
result := ssh.ExecCommand(cmd)
resp := pbslurm.DeleteAccountResp{}
resp.Result = result
return &resp, nil
}

View File

@ -1,38 +0,0 @@
package slurmer
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
"strings"
)
func (slurmStruct SlurmStruct) ListAssociations(ctx context.Context, req *pbslurm.ListAssociationsReq) (*pbslurm.ListAssociationsResp, error) {
assocList := tianhe.GetAssociationInfos()
resp := pbslurm.ListAssociationsResp{}
for _, assoc := range assocList.AssocInfoList {
assocResult := assoc
resp.AssocInfos = append(resp.AssocInfos, &assocResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) GetAssociation(ctx context.Context, req *pbslurm.GetAssociationReq) (*pbslurm.GetAssociationResp, error) {
assocList := tianhe.GetAssociationInfos()
resp := pbslurm.GetAssociationResp{}
for _, assoc := range assocList.AssocInfoList {
if (len(req.Cluster) != 0 || len(req.User) != 0 || len(req.Account) != 0 || len(req.Partition) != 0) && strings.Contains(assoc.Cluster, req.Cluster) && strings.Contains(assoc.Acct, req.Account) && strings.Contains(assoc.User, req.User) && strings.Contains(assoc.Partition, req.Partition) {
assocResult := assoc
resp.AssocInfos = append(resp.AssocInfos, &assocResult)
}
}
return &resp, nil
}

View File

@ -1,97 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"code.gitlink.org.cn/JCCE/PCM.git/common/ssh"
"context"
"strings"
)
func (slurmStruct SlurmStruct) ListClusters(ctx context.Context, req *pbslurm.ListClustersReq) (*pbslurm.ListClustersResp, error) {
clusterList := tianhe.GetClusterInfo()
resp := pbslurm.ListClustersResp{}
for _, cluster := range clusterList.ClusterInfoList {
clusterInfoResult := pbslurm.ClusterInfo{}
clusterInfoResult = cluster
resp.ClusterInfos = append(resp.ClusterInfos, &clusterInfoResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) DeleteCluster(ctx context.Context, req *pbslurm.DeleteClusterReq) (*pbslurm.DeleteClusterResp, error) {
cmd := "usr/local/bin/sacctmgr delete cluster"
cmd = cmd + req.Names
cmd = cmd + "-i"
result := ssh.ExecCommand(cmd)
//var go_cluster_buffer ClusterInfoMsg
resp := pbslurm.DeleteClusterResp{}
resp.Result = result
return &resp, nil
}
func (slurmStruct SlurmStruct) AddCluster(ctx context.Context, req *pbslurm.AddClusterReq) (*pbslurm.AddClusterResp, error) {
cmd := "/usr/local/bin/sacctmgr add cluster "
cmd = cmd + req.Name
if len(req.Nodes) != 0 {
cmd = cmd + " Nodes=" + req.Nodes
}
if len(req.Classification) != 0 {
cmd = cmd + " Classification=" + req.Classification
}
if len(req.ControlHost) != 0 {
cmd = cmd + " ControlHost=\"" + req.ControlHost + "\""
}
if len(req.ControlPort) != 0 {
cmd = cmd + " ControlPort=" + req.ControlPort
}
if len(req.CpuCount) != 0 {
cmd = cmd + " CpuCount=" + req.CpuCount
}
if len(req.Dimensions) != 0 {
cmd = cmd + " Dimensions=" + req.Dimensions
}
if len(req.DimSize) != 0 {
cmd = cmd + " DimSize=" + req.DimSize
}
if len(req.Flags) != 0 {
cmd = cmd + " Flags=" + req.Flags
}
if len(req.PluginIdSelect) != 0 {
cmd = cmd + " GrpNodes=" + req.PluginIdSelect
}
if len(req.RpcVersion) != 0 {
cmd = cmd + " RpcVersion=" + req.RpcVersion
}
cmd = cmd + " -i"
result := ssh.ExecCommand(cmd)
resp := pbslurm.AddClusterResp{}
resp.Result = result
return &resp, nil
}
func (slurmStruct SlurmStruct) GetCluster(ctx context.Context, req *pbslurm.GetClusterReq) (*pbslurm.GetClusterResp, error) {
clusterList := tianhe.GetClusterInfo()
resp := pbslurm.GetClusterResp{}
for _, cluster := range clusterList.ClusterInfoList {
clusterInfoResult := cluster
if strings.Contains(cluster.Name, req.ClusterName) {
resp.ClusterInfos = append(resp.ClusterInfos, &clusterInfoResult)
}
}
return &resp, nil
}

View File

@ -1,16 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
)
func (slurmStruct SlurmStruct) GetDiag(ctx context.Context, req *pbslurm.DiagReq) (*pbslurm.DiagResp, error) {
stats := tianhe.Get_diag()
var resp = pbslurm.DiagResp{}
resp.StatsInfoResponseMsg = &stats
return &resp, nil
}

View File

@ -1,30 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
)
func (slurmStruct SlurmStruct) GetAllJobs(ctx context.Context, req *pbslurm.JobInfoMsgReq) (*pbslurm.JobInfoMsgResp, error) {
job_info_msg := tianhe.Get_all_jobs()
var resp = pbslurm.JobInfoMsgResp{}
resp.JobInfoMsg = &job_info_msg
return &resp, nil
}
func (slurmStruct SlurmStruct) GetJob(ctx context.Context, req *pbslurm.JobInfoMsgReq) (*pbslurm.JobInfoMsgResp, error) {
job_info_msg := tianhe.Get_job(req.JobId)
var resp = pbslurm.JobInfoMsgResp{}
resp.JobInfoMsg = &job_info_msg
return &resp, nil
}
func (slurmStruct SlurmStruct) DeleteJob(ctx context.Context, req *pbslurm.DeleteJobReq) (*pbslurm.DeleteJobResp, error) {
errorCode := tianhe.Delete_job(req.JobId)
var resp = pbslurm.DeleteJobResp{}
resp.ErrorCode = errorCode
return &resp, nil
}

View File

@ -1,23 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
)
func (slurmStruct SlurmStruct) GetSlurmdbJobs(ctx context.Context, req *pbslurm.SlurmDbJobReq) (*pbslurm.SlurmDbJobResp, error) {
slurmdbJobs := tianhe.GetAllSlurmdbJobs()
var resp = pbslurm.SlurmDbJobResp{}
resp.SlurmdbJobRec = slurmdbJobs
return &resp, nil
}
func (slurmStruct SlurmStruct) GetSlurmdbJobById(ctx context.Context, req *pbslurm.SlurmDbJobReq) (*pbslurm.SlurmDbJobResp, error) {
slurmdbjob := tianhe.GetSlurmdbJobById(int(req.JobId))
var resp = pbslurm.SlurmDbJobResp{}
resp.SlurmdbJobRec = slurmdbjob
return &resp, nil
}

View File

@ -1,27 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
)
func (slurmStruct SlurmStruct) SubmitJob(ctx context.Context, req *pbslurm.SubmitJobReq) (*pbslurm.SubmitJobResp, error) {
submit_response_msg := tianhe.Submit_job(req.Data)
var resp = pbslurm.SubmitJobResp{}
submitResponseMsg := pbslurm.SubmitResponseMsg{}
submitResponseMsg.JobId = submit_response_msg.JobId
submitResponseMsg.StepId = submit_response_msg.StepId
submitResponseMsg.ErrorCode = submit_response_msg.ErrorCode
resp.SubmitResponseMsg = append(resp.SubmitResponseMsg, &submitResponseMsg)
return &resp, nil
}
func (slurmStruct SlurmStruct) UpdateJob(ctx context.Context, req *pbslurm.UpdateJobReq) (*pbslurm.UpdateJobResp, error) {
errorCode := tianhe.Update_job(req.Data, req.JobId)
var resp = pbslurm.UpdateJobResp{}
resp.ErrorCode = errorCode
return &resp, nil
}

View File

@ -1,53 +0,0 @@
package slurmer
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
"strings"
)
func (slurmStruct SlurmStruct) ListNodes(ctx context.Context, req *pbslurm.ListNodesReq) (*pbslurm.ListNodesResp, error) {
nodeList := tianhe.Get_all_nodes()
var resp = pbslurm.ListNodesResp{}
for _, node := range nodeList.NodeInfoList {
nodeInfoResult := pbslurm.NodeInfo{}
nodeInfoResult.Cpus = uint32(node.Cpus)
nodeInfoResult.Boards = uint32(node.Boards)
nodeInfoResult.RealMemory = node.RealMemory
nodeInfoResult.Sockets = uint32(node.Sockets)
nodeInfoResult.Threads = uint32(node.Threads)
resp.NodeInfos = append(resp.NodeInfos, &nodeInfoResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) GetNode(ctx context.Context, req *pbslurm.GetNodeReq) (*pbslurm.GetNodeResp, error) {
NodeList := tianhe.GetNodeInfo()
resp := pbslurm.GetNodeResp{}
for _, node := range NodeList.NodeInfoList {
nodeInfoResult := node
if strings.Contains(node.Name, req.NodeName) {
resp.NodeInfos = append(resp.NodeInfos, &nodeInfoResult)
}
}
return &resp, nil
}
/*func (slurmStruct SlurmStruct) GetNodeByName(ctx context.Context, req *pbnode.NodeInfoMsgReq) (*pbnode.NodeInfoMsgResp, error) {
node := Get_node_info(req.NodeName)
var resp = pbnode.NodeInfoMsgResp{}
for _, node := range node.Node_list {
nodeInfoResult := pbnode.Node_Info{}
nodeInfoResult.Cpus = uint32(node.Cpus)
nodeInfoResult.Boards = uint32(node.Boards)
nodeInfoResult.RealMemory = node.RealMemory
nodeInfoResult.Sockets = uint32(node.Sockets)
nodeInfoResult.Threads = uint32(node.Threads)
resp.NodeList = append(resp.NodeList, &nodeInfoResult)
}
return &resp, nil
}*/

View File

@ -1,31 +0,0 @@
package slurmer
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
"strings"
)
func (slurmStruct SlurmStruct) ListPartitions(ctx context.Context, req *pbslurm.ListPartitionsReq) (*pbslurm.ListPartitionsResp, error) {
partitionList := tianhe.Get_partitions()
var resp = pbslurm.ListPartitionsResp{}
for _, partition := range partitionList.PartitionInfoList {
partitionInfoResult := partition
resp.PartitionList = append(resp.PartitionList, &partitionInfoResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) GetPartition(ctx context.Context, req *pbslurm.GetPartitionReq) (*pbslurm.GetPartitionResp, error) {
PartitionList := tianhe.GetPartitionsInfo()
resp := pbslurm.GetPartitionResp{}
for _, partition := range PartitionList.PartitionInfoList {
partitionInfoResult := partition
if strings.Contains(partition.Name, req.PartitionName) {
resp.PartitionInfos = append(resp.PartitionInfos, &partitionInfoResult)
}
}
return &resp, nil
}

View File

@ -1,31 +0,0 @@
package slurmer
/*
//#cgo LDFLAGS: -lslurm
#include<stdlib.h>
#include<slurm/slurm.h>
#include<slurm/slurm_errno.h>
// int ping_result;
// ping_result = slurm_ping(int ping)
int slurm_ping(int controller){
int ping_result;
ping_result = slurm_ping(controller);
return ping_result;
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"context"
)
func (slurmStruct SlurmStruct) GetPingResult(ctx context.Context, req *pbslurm.PingInfoMsgReq) (*pbslurm.PingInfoMsgResp, error) {
cgoIntA := C.int(req.Controller)
Ping_result := C.slurm_ping(cgoIntA)
//C.free(unsafe.Pointer(cgoIntA))
var resp = pbslurm.PingInfoMsgResp{}
resp.PingResult = int32(Ping_result)
return &resp, nil
}

View File

@ -1,60 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"code.gitlink.org.cn/JCCE/PCM.git/common/ssh"
"context"
)
func (slurmStruct SlurmStruct) GetQos(ctx context.Context, req *pbslurm.QosReq) (*pbslurm.QosResp, error) {
qoslist := tianhe.Get_Qos()
var resp = pbslurm.QosResp{}
resp.SlurmdbQosRec = qoslist
return &resp, nil
}
func (slurmStruct SlurmStruct) DeleteQos(ctx context.Context, req *pbslurm.DeleteQosReq) (*pbslurm.DeleteQosResp, error) {
cmd := "/usr/local/bin/sacctmgr delete qos "
cmd = cmd + req.Names
cmd = cmd + " -i"
result := ssh.ExecCommand(cmd)
resp := pbslurm.DeleteQosResp{}
resp.Result = result
return &resp, nil
}
func (slurmStruct SlurmStruct) GetQosByName(ctx context.Context, req *pbslurm.QosReq) (*pbslurm.QosResp, error) {
qos := tianhe.GetQosByName(req.Name)
var resp = pbslurm.QosResp{}
slurmdbRosRec := []*pbslurm.SlurmdbQosRec{}
slurmdbRosRec = append(slurmdbRosRec, &qos)
resp.SlurmdbQosRec = slurmdbRosRec
return &resp, nil
}
func (slurmStruct SlurmStruct) AddQos(ctx context.Context, req *pbslurm.AddQosReq) (*pbslurm.AddQosResp, error) {
cmd := "/usr/local/bin/sacctmgr add qos "
cmd = cmd + req.SlurmdbQosRec.Name
if len(req.SlurmdbQosRec.Description) != 0 {
cmd = cmd + " Description=" + req.SlurmdbQosRec.Description
}
if len(req.SlurmdbQosRec.Name) != 0 {
cmd = cmd + " Name=" + req.SlurmdbQosRec.Name
}
cmd = cmd + " -i"
result := ssh.ExecCommand(cmd)
resp := pbslurm.AddQosResp{}
resp.Result = result
return &resp, nil
}

View File

@ -1,67 +0,0 @@
package slurmer
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/service/tianhe"
"context"
"strings"
)
func (slurmStruct SlurmStruct) ListReservations(ctx context.Context, req *pbslurm.ListReservationsReq) (*pbslurm.ListReservationsResp, error) {
reservationList := tianhe.Get_all_reservation()
var resp = pbslurm.ListReservationsResp{}
for _, reservation := range reservationList.ReservationList {
reservationInfoResult := reservation
resp.ReservationList = append(resp.ReservationList, &reservationInfoResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) GetReservation(ctx context.Context, req *pbslurm.GetReservationReq) (*pbslurm.GetReservationResp, error) {
ReservationList := tianhe.GetReservationsInfo()
resp := pbslurm.GetReservationResp{}
for _, reservation := range ReservationList.ReservationList {
reservationInfoResult := reservation
if strings.Contains(reservation.Name, req.ReservationName) {
resp.ReservationInfos = append(resp.ReservationInfos, &reservationInfoResult)
}
}
return &resp, nil
}
/*func (slurmStruct SlurmStruct) GetReservationByName(ctx context.Context, req *pbslurm.ReservationInfoMsgReq) (*pbslurm.ReservationInfoMsgResp, error) {
reservation := Get_reservation_info(req.ReservationName)
var resp = pbslurm.ReservationInfoMsgResp{}
for _, reservation := range reservation.Reservation_list {
reservationInfoResult := pbslurm.Reservation_Info{}
reservationInfoResult.Name = reservation.Name
/*nodeInfoResult.Boards = uint32(node.Boards)
nodeInfoResult.RealMemory = node.Real_memory
nodeInfoResult.Sockets = uint32(node.Sockets)
nodeInfoResult.Threads = uint32(node.Threads)*
resp.ReservationList = append(resp.ReservationList, &reservationInfoResult)
}
return &resp, nil
}
func Get_reservation_info(name string) ReserveInfoMsg {
go_reservation_buffer := Get_all_reservation()
//partitionList := list.New()
for i := range go_reservation_buffer.ReservationList {
//遍历nodeList集合
reservation := go_reservation_buffer.ReservationList[i]
fmt.Println("reservationName: " + reservation.Name)
//当集合中的名字等于传过来的值
if name == reservation.Name {
/*partitionList.PushFront(partition.Name)
partitionList.PushFront(partition.Nodes)*
} else {
}
//fmt.Println(partition.Node_inx)
}
return go_reservation_buffer
}*/

View File

@ -1,54 +0,0 @@
package slurmer
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"context"
)
type Slurmer interface {
ListUsers(ctx context.Context, req *pbslurm.ListUsersReq) (resp *pbslurm.ListUsersResp, err error) //list slurm users
GetUser(ctx context.Context, req *pbslurm.GetUserReq) (resp *pbslurm.GetUserResp, err error) //get specific slurm user
AddUser(ctx context.Context, req *pbslurm.AddUserReq) (resp *pbslurm.AddUserResp, err error) //add slurm user
DeleteUser(ctx context.Context, req *pbslurm.DeleteUserReq) (resp *pbslurm.DeleteUserResp, err error) //delete slurm user
ListAssociations(ctx context.Context, req *pbslurm.ListAssociationsReq) (resp *pbslurm.ListAssociationsResp, err error) //list slurm associations
GetAssociation(ctx context.Context, req *pbslurm.GetAssociationReq) (resp *pbslurm.GetAssociationResp, err error) //get specific slurm associations
ListAccounts(ctx context.Context, req *pbslurm.ListAccountsReq) (resp *pbslurm.ListAccountsResp, err error) //list slurm accounts
GetAccount(ctx context.Context, req *pbslurm.GetAccountReq) (resp *pbslurm.GetAccountResp, err error) //get specific slurm account
AddAccount(ctx context.Context, req *pbslurm.AddAccountReq) (resp *pbslurm.AddAccountResp, err error) //add slurm account
DeleteAccount(ctx context.Context, req *pbslurm.DeleteAccountReq) (resp *pbslurm.DeleteAccountResp, err error) //delete slurm account
GetQos(ctx context.Context, req *pbslurm.QosReq) (resp *pbslurm.QosResp, err error) //list slurm qoss
ListWckeys(ctx context.Context, req *pbslurm.ListWckeysReq) (resp *pbslurm.ListWckeysResp, err error) //list slurm wckeys
GetWckey(ctx context.Context, req *pbslurm.GetWckeyReq) (resp *pbslurm.GetWckeyResp, err error) //list slurm wckeys
ListClusters(ctx context.Context, req *pbslurm.ListClustersReq) (resp *pbslurm.ListClustersResp, err error)
GetCluster(ctx context.Context, req *pbslurm.GetClusterReq) (resp *pbslurm.GetClusterResp, err error)
DeleteCluster(ctx context.Context, req *pbslurm.DeleteClusterReq) (resp *pbslurm.DeleteClusterResp, err error)
AddCluster(ctx context.Context, req *pbslurm.AddClusterReq) (resp *pbslurm.AddClusterResp, err error)
ListNodes(ctx context.Context, req *pbslurm.ListNodesReq) (resp *pbslurm.ListNodesResp, err error)
GetNode(ctx context.Context, req *pbslurm.GetNodeReq) (resp *pbslurm.GetNodeResp, err error)
ListPartitions(ctx context.Context, req *pbslurm.ListPartitionsReq) (resp *pbslurm.ListPartitionsResp, err error)
GetPartition(ctx context.Context, req *pbslurm.GetPartitionReq) (resp *pbslurm.GetPartitionResp, err error)
ListReservations(ctx context.Context, req *pbslurm.ListReservationsReq) (resp *pbslurm.ListReservationsResp, err error)
GetReservation(ctx context.Context, req *pbslurm.GetReservationReq) (resp *pbslurm.GetReservationResp, err error)
GetAllJobs(ctx context.Context, req *pbslurm.JobInfoMsgReq) (resp *pbslurm.JobInfoMsgResp, err error)
GetJob(ctx context.Context, req *pbslurm.JobInfoMsgReq) (resp *pbslurm.JobInfoMsgResp, err error)
SubmitJob(ctx context.Context, req *pbslurm.SubmitJobReq) (resp *pbslurm.SubmitJobResp, err error)
DeleteJob(ctx context.Context, req *pbslurm.DeleteJobReq) (resp *pbslurm.DeleteJobResp, err error)
UpdateJob(ctx context.Context, req *pbslurm.UpdateJobReq) (resp *pbslurm.UpdateJobResp, err error)
GetDiag(ctx context.Context, req *pbslurm.DiagReq) (resp *pbslurm.DiagResp, err error)
GetSlurmdbJobs(ctx context.Context, req *pbslurm.SlurmDbJobReq) (resp *pbslurm.SlurmDbJobResp, err error)
GetSlurmdbJobById(ctx context.Context, req *pbslurm.SlurmDbJobReq) (resp *pbslurm.SlurmDbJobResp, err error)
DeleteQos(ctx context.Context, req *pbslurm.DeleteQosReq) (resp *pbslurm.DeleteQosResp, err error)
GetQosByName(ctx context.Context, req *pbslurm.QosReq) (resp *pbslurm.QosResp, err error)
AddQos(ctx context.Context, req *pbslurm.AddQosReq) (resp *pbslurm.AddQosResp, err error)
}
func SelectSlurmVersion(slurmVersion pbslurm.SlurmVersion) (slurmer Slurmer, err error) {
switch slurmVersion {
case pbslurm.SlurmVersion_tianhe:
return SelectTianhe()
case pbslurm.SlurmVersion_shenwei:
print("no adaptor for shenwei right now")
}
return
}

View File

@ -1,12 +0,0 @@
package slurmer
type SlurmStruct struct {
version string
}
func SelectTianhe() (Slurmer, error) {
return &SlurmStruct{
version: "2.6.9.1",
}, nil
}

View File

@ -1,195 +0,0 @@
package slurmer
/*
#cgo LDFLAGS: -lslurmdb
#include <stdio.h>
#include <slurm/slurm.h>
#include <slurm/slurmdb.h>
#include <memory.h>
#include <malloc.h>
typedef struct user_info_msg {
uint32_t record_count;
slurmdb_user_rec_t *user_array;
} user_info_msg_t;
typedef struct slurmdb_user_rec{
uint16_t admin_level;
List assoc_list;
List coord_accts;
char *default_acct;
char *default_wckey;
char *name;
char *old_name;
uint32_t uid;
List wckey_list;
} slurmdb_user_rec_pcm;
struct user_info_msg get_user_info() {
struct user_info_msg userinfo;
List userList = NULL;
slurmdb_user_cond_t *user_cond = NULL;
void *db_conn;
db_conn = slurmdb_connection_get();
userList = slurmdb_users_get(db_conn, user_cond);
slurmdb_connection_close(&db_conn);
slurmdb_user_rec_t *rec = NULL;
ListIterator itr = slurm_list_iterator_create(userList);
int i = 0;
uint32_t length;
length = slurm_list_count(userList);
userinfo.record_count = length;
userinfo.user_array = malloc(length * sizeof(slurmdb_user_rec_t));
while ((rec = slurm_list_next(itr))) {
userinfo.user_array[i] = *rec;
i++;
}
return userinfo;
}
struct slurmdb_user_rec *user_from_list(struct user_info_msg *list, int i) {
return (struct slurmdb_user_rec *) &list->user_array[i];
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
ssh "code.gitlink.org.cn/JCCE/PCM.git/common/ssh"
"context"
"strings"
)
type UserInfoMsg struct {
LastUpdate int64
RecordCount uint32
UserInfoList []pbslurm.UserInfo
}
func UserDescriptorConvertCToGo(cStruct *C.struct_slurmdb_user_rec) pbslurm.UserInfo {
var goStruct pbslurm.UserInfo
goStruct.Name = C.GoString(cStruct.name)
return goStruct
}
func GetUserInfo() UserInfoMsg {
var goUserBuffer UserInfoMsg
cUserBuffer := C.get_user_info()
goUserBuffer.RecordCount = uint32(cUserBuffer.record_count)
goUserBuffer.UserInfoList = make([]pbslurm.UserInfo, cUserBuffer.record_count, cUserBuffer.record_count)
for i := uint32(0); i < goUserBuffer.RecordCount; i++ {
user := C.user_from_list(&cUserBuffer, C.int(i))
goUser := UserDescriptorConvertCToGo(user)
goUserBuffer.UserInfoList[i] = goUser
}
return goUserBuffer
}
func (slurmStruct SlurmStruct) ListUsers(ctx context.Context, req *pbslurm.ListUsersReq) (*pbslurm.ListUsersResp, error) {
userList := GetUserInfo()
resp := pbslurm.ListUsersResp{}
for _, user := range userList.UserInfoList {
userInfoResult := user
//userInfoResult.Name = user.Name
resp.UserInfos = append(resp.UserInfos, &userInfoResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) GetUser(ctx context.Context, req *pbslurm.GetUserReq) (*pbslurm.GetUserResp, error) {
userList := GetUserInfo()
resp := pbslurm.GetUserResp{}
for _, user := range userList.UserInfoList {
if strings.Contains(user.Name, req.UserName) {
userInfoResult := user
resp.UserInfo = append(resp.UserInfo, &userInfoResult)
}
}
return &resp, nil
}
func (slurmStruct SlurmStruct) AddUser(ctx context.Context, req *pbslurm.AddUserReq) (*pbslurm.AddUserResp, error) {
cmd := "/usr/local/bin/sacctmgr add user "
cmd = cmd + req.Names
if len(req.Accounts) != 0 {
cmd = cmd + " Accounts=" + req.Accounts
}
if len(req.AdminLevel) != 0 {
cmd = cmd + " AdminLevel=" + req.AdminLevel
}
if len(req.Clusters) != 0 {
cmd = cmd + " Clusters=" + req.Clusters
}
if len(req.DefaultAccount) != 0 {
cmd = cmd + " DefaultAccount=" + req.DefaultAccount
}
if len(req.DefaultQos) != 0 {
cmd = cmd + " DefaultQOS=" + req.DefaultQos
}
if len(req.DefaultWckey) != 0 {
cmd = cmd + " DefaultWCKey=" + req.DefaultWckey
}
if len(req.FairShare) != 0 {
cmd = cmd + " Fairshare=" + req.FairShare
}
if len(req.MaxCpuMins) != 0 {
cmd = cmd + " MaxCPUMins=" + req.MaxCpuMins
}
if len(req.MaxCpus) != 0 {
cmd = cmd + " MaxCPUs=" + req.MaxCpus
}
if len(req.MaxJobs) != 0 {
cmd = cmd + " MaxJobs=" + req.MaxJobs
}
if len(req.MaxNodes) != 0 {
cmd = cmd + " MaxNodes=" + req.MaxNodes
}
if len(req.MaxSubmitJobs) != 0 {
cmd = cmd + " MaxSubmitJobs=" + req.MaxSubmitJobs
}
if len(req.MaxWall) != 0 {
cmd = cmd + " MaxWall=" + req.MaxWall
}
if len(req.Partitions) != 0 {
cmd = cmd + " Partitions=" + req.Partitions
}
if len(req.QosLevel) != 0 {
cmd = cmd + " QosLevel=" + req.QosLevel
}
cmd = cmd + " -i"
result := ssh.ExecCommand(cmd)
resp := pbslurm.AddUserResp{}
resp.Result = result
return &resp, nil
}
func (slurmStruct SlurmStruct) DeleteUser(ctx context.Context, req *pbslurm.DeleteUserReq) (*pbslurm.DeleteUserResp, error) {
cmd := "/usr/local/bin/sacctmgr delete user "
cmd = cmd + req.Names
cmd = cmd + " -i"
result := ssh.ExecCommand(cmd)
resp := pbslurm.DeleteUserResp{}
resp.Result = result
return &resp, nil
}

View File

@ -1,119 +0,0 @@
package slurmer
/*
#cgo LDFLAGS: -lslurmdb
#include <stdio.h>
#include <slurm/slurm.h>
#include <slurm/slurmdb.h>
#include <memory.h>
#include <malloc.h>
typedef struct wckey_info_msg {
uint32_t record_count;
slurmdb_wckey_rec_t *wckey_array;
} wckey_info_msg_t;
typedef struct slurmdb_wckey_rec{
uint16_t admin_level;
List assoc_list;
List coord_accts;
char *default_acct;
char *default_wckey;
char *name;
char *old_name;
uint32_t uid;
List wckey_list;
} slurmdb_wckey_rec_pcm;
struct wckey_info_msg get_wckey_info() {
struct wckey_info_msg wckeyinfo;
List wckeyList = NULL;
slurmdb_wckey_cond_t *wckey_cond = NULL;
void *db_conn;
db_conn = slurmdb_connection_get();
wckeyList = slurmdb_wckeys_get(db_conn, wckey_cond);
slurmdb_connection_close(&db_conn);
slurmdb_wckey_rec_t *rec = NULL;
ListIterator itr = slurm_list_iterator_create(wckeyList);
int i = 0;
uint32_t length;
length = slurm_list_count(wckeyList);
wckeyinfo.record_count = length;
wckeyinfo.wckey_array = malloc(length * sizeof(slurmdb_wckey_rec_t));
while ((rec = slurm_list_next(itr))) {
wckeyinfo.wckey_array[i] = *rec;
i++;
}
return wckeyinfo;
}
struct slurmdb_wckey_rec *wckey_from_list(struct wckey_info_msg *list, int i) {
return (struct slurmdb_wckey_rec *) &list->wckey_array[i];
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"context"
)
type WckeyInfoMsg struct {
LastUpdate int64
RecordCount uint32
WckeyInfoList []pbslurm.WckeyInfo
}
func WckeyDescriptorConvertCToGo(cStruct *C.struct_slurmdb_wckey_rec) pbslurm.WckeyInfo {
var goStruct pbslurm.WckeyInfo
goStruct.Name = C.GoString(cStruct.name)
return goStruct
}
func GetWckeyInfo() WckeyInfoMsg {
var goWckeyBuffer WckeyInfoMsg
cWckeyBuffer := C.get_wckey_info()
goWckeyBuffer.RecordCount = uint32(cWckeyBuffer.record_count)
goWckeyBuffer.WckeyInfoList = make([]pbslurm.WckeyInfo, cWckeyBuffer.record_count, cWckeyBuffer.record_count)
for i := uint32(0); i < goWckeyBuffer.RecordCount; i++ {
wckey := C.wckey_from_list(&cWckeyBuffer, C.int(i))
goWckey := WckeyDescriptorConvertCToGo(wckey)
goWckeyBuffer.WckeyInfoList[i] = goWckey
}
return goWckeyBuffer
}
func (slurmStruct SlurmStruct) ListWckeys(ctx context.Context, req *pbslurm.ListWckeysReq) (*pbslurm.ListWckeysResp, error) {
wckeyList := GetWckeyInfo()
resp := pbslurm.ListWckeysResp{}
for _, wckey := range wckeyList.WckeyInfoList {
wckeyInfoResult := wckey
//wckeyInfoResult.Name = wckey.Name
resp.WckeyInfos = append(resp.WckeyInfos, &wckeyInfoResult)
}
return &resp, nil
}
func (slurmStruct SlurmStruct) GetWckey(ctx context.Context, req *pbslurm.GetWckeyReq) (*pbslurm.GetWckeyResp, error) {
wckeyList := GetWckeyInfo()
resp := pbslurm.GetWckeyResp{}
for _, wckey := range wckeyList.WckeyInfoList {
//wckeyInfoResult := pbslurm.WckeyInfo{}
//todo add filter logic
wckeyInfoResult := wckey
//wckeyInfoResult.Name = wckey.Name
resp.WckeyInfo = append(resp.WckeyInfo, &wckeyInfoResult)
}
return &resp, nil
}

View File

@ -1,82 +0,0 @@
package tianhe
/*
#cgo LDFLAGS: -lslurmdb
#include <stdio.h>
#include <slurm/slurm.h>
#include <slurm/slurmdb.h>
#include <memory.h>
#include <malloc.h>
typedef struct account_info_msg {
uint32_t record_count;
slurmdb_account_rec_t *account_array;
} account_info_msg_t;
typedef struct slurmdb_account_rec{
List assoc_list;
List coord_accts;
char *description;
char *name;
char *organization;
} slurmdb_account_rec_pcm;
struct account_info_msg get_account_info() {
struct account_info_msg accountinfo;
List accountList = NULL;
slurmdb_account_cond_t *account_cond = NULL;
void *db_conn;
db_conn = slurmdb_connection_get();
accountList = slurmdb_accounts_get(db_conn, account_cond);
slurmdb_connection_close(&db_conn);
slurmdb_account_rec_t *rec = NULL;
ListIterator itr = slurm_list_iterator_create(accountList);
int i = 0;
uint32_t length;
length = slurm_list_count(accountList);
accountinfo.record_count = length;
accountinfo.account_array = malloc(length * sizeof(slurmdb_account_rec_t));
while ((rec = slurm_list_next(itr))) {
accountinfo.account_array[i] = *rec;
i++;
}
return accountinfo;
}
struct slurmdb_account_rec *account_from_list(struct account_info_msg *list, int i) {
return (struct slurmdb_account_rec *) &list->account_array[i];
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
)
type AcctInfoMsg struct {
LastUpdate int64
RecordCount uint32
AcctInfoList []pbslurm.AccountInfo
}
func AcctDescriptorConvertCToGo(cStruct *C.struct_slurmdb_account_rec) pbslurm.AccountInfo {
var goStruct pbslurm.AccountInfo
goStruct.Name = C.GoString(cStruct.name)
return goStruct
}
func GetAcctInfo() AcctInfoMsg {
var goAcctBuffer AcctInfoMsg
cAcctBuffer := C.get_account_info()
goAcctBuffer.RecordCount = uint32(cAcctBuffer.record_count)
goAcctBuffer.AcctInfoList = make([]pbslurm.AccountInfo, cAcctBuffer.record_count, cAcctBuffer.record_count)
for i := uint32(0); i < goAcctBuffer.RecordCount; i++ {
Acct := C.account_from_list(&cAcctBuffer, C.int(i))
goAcct := AcctDescriptorConvertCToGo(Acct)
goAcctBuffer.AcctInfoList[i] = goAcct
}
return goAcctBuffer
}

View File

@ -1,145 +0,0 @@
package tianhe
/*
#cgo LDFLAGS: -lslurmdb
#include <stdio.h>
#include <slurm/slurm.h>
#include <slurm/slurmdb.h>
#include <memory.h>
#include <malloc.h>
typedef struct assoc_info_msg {
uint32_t record_count;
slurmdb_association_rec_t *assoc_array;
} assoc_info_msg_t;
typedef struct list_assoc_req {
uint32_t slurm_version;
char *cluster;
char *account;
char *user;
char *partition;
} list_assoc_req_t;
typedef struct slurmdb_association_rec{
List accounting_list;
char *acct;
char *cluster;
uint32_t def_qos_id;
uint64_t grp_cpu_mins;
uint64_t grp_cpu_run_mins;
uint32_t grp_cpus;
uint32_t grp_jobs;
uint32_t grp_mem;
uint32_t grp_nodes;
uint32_t grp_submit_jobs;
uint32_t grp_wall;
uint32_t id;
uint16_t is_def;
uint32_t lft;
uint64_t max_cpu_mins_pj;
uint64_t max_cpu_run_mins;
uint32_t max_cpus_pj;
uint32_t max_jobs;
uint32_t max_nodes_pj;
uint32_t max_submit_jobs;
uint32_t max_wall_pj;
char *parent_acct;
uint32_t parent_id;
char *partition;
List qos_list;
uint32_t rgt;
uint32_t shares_raw;
uint32_t uid;
assoc_mgr_association_usage_t *usage;
char *user;
} slurmdb_association_rec_pcm;
struct assoc_info_msg get_assoc_infos() {
struct assoc_info_msg associnfo;
List assocList = NULL;
slurmdb_association_cond_t *assoc_cond = NULL;
void *db_conn;
db_conn = slurmdb_connection_get();
assocList = slurmdb_associations_get(db_conn, assoc_cond);
slurmdb_connection_close(&db_conn);
slurmdb_association_rec_t *rec = NULL;
ListIterator itr = slurm_list_iterator_create(assocList);
int i = 0;
uint32_t length;
length = slurm_list_count(assocList);
associnfo.record_count = length;
associnfo.assoc_array = malloc(length * sizeof(slurmdb_association_rec_t));
while ((rec = slurm_list_next(itr))) {
associnfo.assoc_array[i] = *rec;
i++;
}
return associnfo;
}
struct slurmdb_association_rec *assoc_from_list(struct assoc_info_msg *list, int i) {
return (struct slurmdb_association_rec *) &list->assoc_array[i];
}
*/
import "C"
import pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
type AssocInfoMsg struct {
LastUpdate int64
RecordCount uint32
AssocInfoList []pbslurm.AssociationInfo
}
func AssocDescriptorConvertCToGo(cStruct *C.struct_slurmdb_association_rec) pbslurm.AssociationInfo {
var goStruct pbslurm.AssociationInfo
//goStruct.AccountingList = cStruct.accounting_list
goStruct.Acct = C.GoString(cStruct.acct)
goStruct.Cluster = C.GoString(cStruct.cluster)
goStruct.DefQosId = int32(cStruct.def_qos_id)
goStruct.GrpCpuMins = int64(cStruct.grp_cpu_mins)
goStruct.GrpGpuRunMins = int64(cStruct.grp_cpu_run_mins)
goStruct.GrpCpus = int32(cStruct.grp_cpus)
goStruct.GrpJobs = int32(cStruct.grp_jobs)
goStruct.GrpMem = int32(cStruct.grp_mem)
goStruct.GrpNodes = int32(cStruct.grp_nodes)
goStruct.GrpSubmitJobs = int32(cStruct.grp_submit_jobs)
goStruct.GrpWall = int32(cStruct.grp_wall)
goStruct.Id = int32(cStruct.id)
goStruct.IsDef = int32(cStruct.is_def)
goStruct.Lft = int32(cStruct.lft)
goStruct.MaxCpuMinsPj = int64(cStruct.max_cpu_mins_pj)
goStruct.MaxCpuRunMins = int64(cStruct.max_cpu_run_mins)
goStruct.MaxCpusPj = int32(cStruct.max_cpus_pj)
goStruct.MaxJobs = int32(cStruct.max_jobs)
goStruct.MaxNodesPj = int32(cStruct.max_nodes_pj)
goStruct.MaxSubmitJobs = int32(cStruct.max_submit_jobs)
goStruct.MaxWallPj = int32(cStruct.max_wall_pj)
goStruct.ParentAcct = C.GoString(cStruct.parent_acct)
goStruct.ParentId = int32(cStruct.parent_id)
goStruct.Partition = C.GoString(cStruct.partition)
//goStruct.QosList = cStruct.qos_list
goStruct.Rgt = int32(cStruct.rgt)
goStruct.SharesRaw = int32(cStruct.shares_raw)
goStruct.Uid = int32(cStruct.uid)
//goStruct.AssocUsage = cStruct.usage
goStruct.User = C.GoString(cStruct.user)
return goStruct
}
// GetAssociationInfos list info for all associations
func GetAssociationInfos() AssocInfoMsg {
var goAssocBuffer AssocInfoMsg
cAssocBuffer := C.get_assoc_infos()
goAssocBuffer.RecordCount = uint32(cAssocBuffer.record_count)
goAssocBuffer.AssocInfoList = make([]pbslurm.AssociationInfo, cAssocBuffer.record_count, cAssocBuffer.record_count)
for i := uint32(0); i < goAssocBuffer.RecordCount; i++ {
assoc := C.assoc_from_list(&cAssocBuffer, C.int(i))
goAssociation := AssocDescriptorConvertCToGo(assoc)
goAssocBuffer.AssocInfoList[i] = goAssociation
}
return goAssocBuffer
}

View File

@ -1,78 +0,0 @@
package tianhe
/*
#cgo LDFLAGS: -lslurmdb
#include <stdio.h>
#include <slurm/slurm.h>
#include <slurm/slurmdb.h>
#include <memory.h>
#include <malloc.h>
typedef struct cluster_info_msg {
uint32_t record_count;
slurmdb_cluster_rec_t *cluster_array;
} cluster_info_msg_t;
typedef struct slurmdb_cluster_rec{
char *name;
} slurmdb_cluster_rec_pcm;
struct cluster_info_msg get_cluster_info() {
struct cluster_info_msg clusterinfo;
List clusterList = NULL;
slurmdb_cluster_cond_t *cluster_cond = NULL;
void *db_conn;
db_conn = slurmdb_connection_get();
clusterList = slurmdb_clusters_get(db_conn, cluster_cond);
slurmdb_connection_close(&db_conn);
slurmdb_cluster_rec_t *rec = NULL;
ListIterator itr = slurm_list_iterator_create(clusterList);
int i = 0;
uint32_t length;
length = slurm_list_count(clusterList);
clusterinfo.record_count = length;
clusterinfo.cluster_array = malloc(length * sizeof(slurmdb_cluster_rec_t));
while ((rec = slurm_list_next(itr))) {
clusterinfo.cluster_array[i] = *rec;
i++;
}
return clusterinfo;
}
struct slurmdb_cluster_rec *cluster_from_list(struct cluster_info_msg *list, int i) {
return (struct slurmdb_cluster_rec *) &list->cluster_array[i];
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
)
type ClusterInfoMsg struct {
Last_update int64
Record_count uint32
ClusterInfoList []pbslurm.ClusterInfo
}
func Cluster_descriptor_convert_c_to_go(c_struct *C.struct_slurmdb_cluster_rec) pbslurm.ClusterInfo {
var go_struct pbslurm.ClusterInfo
go_struct.Name = C.GoString(c_struct.name)
return go_struct
}
func GetClusterInfo() ClusterInfoMsg {
var go_cluster_buffer ClusterInfoMsg
c_cluster_buffer := C.get_cluster_info()
go_cluster_buffer.Record_count = uint32(c_cluster_buffer.record_count)
go_cluster_buffer.ClusterInfoList = make([]pbslurm.ClusterInfo, c_cluster_buffer.record_count, c_cluster_buffer.record_count)
for i := uint32(0); i < go_cluster_buffer.Record_count; i++ {
cluster := C.cluster_from_list(&c_cluster_buffer, C.int(i))
go_cluster := Cluster_descriptor_convert_c_to_go(cluster)
go_cluster_buffer.ClusterInfoList[i] = go_cluster
}
return go_cluster_buffer
}

View File

@ -1,134 +0,0 @@
package tianhe
/*
#cgo LDFLAGS: -lslurm
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include<slurm/slurm.h>
#include <slurm/slurmdb.h>
#include<slurm/slurm_errno.h>
inline uint8_t uint8_ptr(uint8_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
inline int8_t int8_ptr(int8_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
inline uint16_t uint16_ptr(uint16_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
inline int16_t int16_ptr(int16_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
inline uint32_t uint32_ptr(uint32_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
inline int32_t int32_ptr(int32_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
inline uint64_t uint64_ptr(uint64_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
inline int64_t int64_ptr(int16_t* pointer) {
if (NULL == pointer) {
return -1;}
return *pointer;
}
*/
import "C"
import pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
func Job_info_convert_c_to_go(c_struct *C.struct_job_info) pbslurm.JobInfo {
var go_struct pbslurm.JobInfo
go_struct.Account = C.GoString(c_struct.account)
go_struct.AllocNode = C.GoString(c_struct.alloc_node)
go_struct.AllocSid = uint32(c_struct.alloc_sid)
go_struct.ArrayJobId = uint32(c_struct.array_job_id)
go_struct.ArrayTaskId = uint32(c_struct.array_task_id)
go_struct.AssocId = uint32(c_struct.assoc_id)
go_struct.BatchFlag = uint32(c_struct.batch_flag)
go_struct.BatchHost = C.GoString(c_struct.batch_host)
go_struct.BoardsPerNode = uint32(c_struct.boards_per_node)
go_struct.BatchScript = C.GoString(c_struct.batch_script)
go_struct.Command = C.GoString(c_struct.command)
go_struct.Comment = C.GoString(c_struct.comment)
go_struct.Contiguous = uint32(c_struct.contiguous)
go_struct.CoresPerSocket = uint32(c_struct.cores_per_socket)
go_struct.CpusPerTask = uint32(c_struct.cpus_per_task)
go_struct.Dependency = C.GoString(c_struct.dependency)
go_struct.DerivedEc = uint32(c_struct.derived_ec)
go_struct.EligibleTime = int64(c_struct.eligible_time)
go_struct.EndTime = int64(c_struct.end_time)
go_struct.ExcNodes = C.GoString(c_struct.exc_nodes)
go_struct.ExcNodeInx = int32(C.int32_ptr(c_struct.exc_node_inx))
go_struct.ExitCode = uint32(c_struct.exit_code)
go_struct.Features = C.GoString(c_struct.features)
go_struct.GroupId = uint32(c_struct.group_id)
go_struct.Gres = C.GoString(c_struct.gres)
go_struct.JobId = uint32(c_struct.job_id)
go_struct.JobState = uint32(c_struct.job_state)
go_struct.Licenses = C.GoString(c_struct.licenses)
go_struct.MaxCpus = uint32(c_struct.max_cpus)
go_struct.MaxNodes = uint32(c_struct.max_nodes)
go_struct.Name = C.GoString(c_struct.name)
go_struct.Network = C.GoString(c_struct.network)
go_struct.Nodes = C.GoString(c_struct.nodes)
go_struct.Nice = uint32(c_struct.nice)
go_struct.NodeInx = int32(C.int32_ptr(c_struct.node_inx))
go_struct.NtasksPerCore = uint32(c_struct.ntasks_per_core)
go_struct.NtasksPerNode = uint32(c_struct.ntasks_per_node)
go_struct.NtasksPerSocket = uint32(c_struct.ntasks_per_socket)
go_struct.NtasksPerBoard = uint32(c_struct.ntasks_per_board)
go_struct.NumCpus = uint32(c_struct.num_cpus)
go_struct.NumNodes = uint32(c_struct.num_nodes)
go_struct.Partition = C.GoString(c_struct.partition)
go_struct.PnMinMemory = uint32(c_struct.pn_min_memory)
go_struct.PnMinCpus = uint32(c_struct.pn_min_cpus)
go_struct.PnMinTmpDisk = uint32(c_struct.pn_min_tmp_disk)
go_struct.PreemptTime = int64(c_struct.preempt_time)
go_struct.PreSusTime = int64(c_struct.pre_sus_time)
go_struct.Priority = uint32(c_struct.priority)
go_struct.Profile = uint32(c_struct.profile)
go_struct.Qos = C.GoString(c_struct.qos)
go_struct.ReqNodes = C.GoString(c_struct.req_nodes)
go_struct.ReqNodeInx = int32(C.int32_ptr(c_struct.req_node_inx))
go_struct.ReqSwitch = uint32(c_struct.req_switch)
go_struct.Requeue = uint32(c_struct.requeue)
go_struct.ResizeTime = int64(c_struct.resize_time)
go_struct.RestartCnt = uint32(c_struct.restart_cnt)
go_struct.ResvName = C.GoString(c_struct.resv_name)
go_struct.Shared = uint32(c_struct.shared)
go_struct.ShowFlags = uint32(c_struct.show_flags)
go_struct.SocketsPerBoard = uint32(c_struct.sockets_per_board)
go_struct.SocketsPerNode = uint32(c_struct.sockets_per_node)
go_struct.StartTime = int64(c_struct.start_time)
go_struct.StateDesc = C.GoString(c_struct.state_desc)
go_struct.StateReason = uint32(c_struct.state_reason)
go_struct.SubmitTime = int64(c_struct.submit_time)
go_struct.SuspendTime = int64(c_struct.suspend_time)
go_struct.TimeLimit = uint32(c_struct.time_limit)
go_struct.TimeMin = uint32(c_struct.time_min)
go_struct.ThreadsPerCore = uint32(c_struct.threads_per_core)
go_struct.UserId = uint32(c_struct.user_id)
go_struct.Wait4Switch = uint32(c_struct.wait4switch)
go_struct.Wckey = C.GoString(c_struct.wckey)
go_struct.WorkDir = C.GoString(c_struct.work_dir)
return go_struct
}

View File

@ -1,76 +0,0 @@
package tianhe
/*
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include<slurm/slurm.h>
#include<slurm/slurm_errno.h>
#include <signal.h>
stats_info_response_msg_t *getStats(){
stats_info_response_msg_t *buf;
stats_info_request_msg_t req;
int rc;
req.command_id = STAT_COMMAND_GET;
rc = slurm_get_statistics(&buf, (stats_info_request_msg_t *)&req);
if (rc != SLURM_SUCCESS) {
slurm_perror("slurm_get_statistics");
return NULL;
}
//slurm_free_stats_info_request_msg(&req);
return buf;
}
*/
import "C"
import pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
func Get_diag() pbslurm.StatsInfoResponseMsg {
var go_stats_buffer pbslurm.StatsInfoResponseMsg
c_stats_buffer := C.getStats()
if c_stats_buffer == nil {
return go_stats_buffer
}
go_stats_buffer = Stats_convert_c_to_go(c_stats_buffer)
//C.slurm_free_stats_response_msg(c_stats_buffer)
return go_stats_buffer
}
func Stats_convert_c_to_go(c_struct *C.stats_info_response_msg_t) pbslurm.StatsInfoResponseMsg {
var go_struct pbslurm.StatsInfoResponseMsg
go_struct.AgentQueueSize = uint32(c_struct.agent_queue_size)
go_struct.BfActive = uint32(c_struct.bf_active)
go_struct.BfBackfilledJobs = uint32(c_struct.bf_backfilled_jobs)
go_struct.BfCycleCounter = uint32(c_struct.bf_cycle_counter)
go_struct.BfCycleLast = uint32(c_struct.bf_cycle_last)
go_struct.BfCycleMax = uint32(c_struct.bf_cycle_max)
go_struct.BfCycleSum = uint32(c_struct.bf_cycle_sum)
go_struct.BfDepthSum = uint32(c_struct.bf_depth_sum)
go_struct.BfDepthTrySum = uint32(c_struct.bf_depth_try_sum)
go_struct.BfLastBackfilledJobs = uint32(c_struct.bf_last_backfilled_jobs)
go_struct.BfLastDepth = uint32(c_struct.bf_last_depth)
go_struct.BfLastDepthTry = uint32(c_struct.bf_last_depth_try)
go_struct.BfQueueLen = uint32(c_struct.bf_queue_len)
go_struct.BfQueueLenSum = uint32(c_struct.bf_queue_len_sum)
go_struct.BfWhenLastCycle = int64(c_struct.bf_when_last_cycle)
go_struct.JobsCompleted = uint32(c_struct.jobs_completed)
go_struct.JobsCanceled = uint32(c_struct.jobs_canceled)
go_struct.JobsFailed = uint32(c_struct.jobs_failed)
go_struct.JobsStarted = uint32(c_struct.jobs_started)
go_struct.JobsSubmitted = uint32(c_struct.jobs_submitted)
go_struct.PartsPacked = uint32(c_struct.parts_packed)
go_struct.ReqTime = int64(c_struct.req_time)
go_struct.ReqTimeStart = int64(c_struct.req_time_start)
go_struct.ScheduleCycleDepth = uint32(c_struct.schedule_cycle_depth)
go_struct.ScheduleCycleCounter = uint32(c_struct.schedule_cycle_counter)
go_struct.ScheduleCycleLast = uint32(c_struct.schedule_cycle_last)
go_struct.ScheduleCycleMax = uint32(c_struct.schedule_cycle_max)
go_struct.ScheduleCycleSum = uint32(c_struct.schedule_cycle_sum)
go_struct.ScheduleQueueLen = uint32(c_struct.schedule_queue_len)
go_struct.ServerThreadCount = uint32(c_struct.server_thread_count)
return go_struct
}

View File

@ -1,116 +0,0 @@
package tianhe
/*
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include<slurm/slurm.h>
#include<slurm/slurm_errno.h>
#include <signal.h>
struct job_info_msg *get_job_info(){
struct job_info_msg* job_buffer;
if(slurm_load_jobs ((time_t) NULL,
&job_buffer, SHOW_ALL)) {
return NULL;
}
return job_buffer;
}
struct job_info* job_from_list(struct job_info_msg *list, int i){
return &list->job_array[i];
}
struct job_info_msg *get_single_job_info(uint32_t id){
struct job_info_msg* job_buffer;
if( slurm_load_job (&job_buffer, id, SHOW_DETAIL)) {
return NULL;
}
return job_buffer;
}
int delete_job(uint32_t id) {
int error_code = 0;
error_code = slurm_kill_job (id, SIGKILL, 0);
if (error_code) {
char msg[64];
sprintf(msg, "slurm_kill_job(%.12s)",id);
slurm_perror (msg);
return error_code;
}
return (error_code);
}
//static time_t last_update_time = (time_t) NULL;
//int error_code;
//job_info_msg_t * job_info_msg_ptr = NULL;
//
//error_code = slurm_load_jobs (last_update_time, &job_info_msg_ptr, 1);
//if (error_code) {
// slurm_perror ("slurm_load_jobs");
// return (error_code);
//}
//
//slurm_print_job_info_msg ( stdout, job_info_msg_ptr, 1 ) ;
//
//slurm_free_job_info_msg ( job_info_msg_ptr ) ;
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
)
func Get_all_jobs() pbslurm.JobInfoMsg {
var go_job_buffer pbslurm.JobInfoMsg
c_job_buffer := C.get_job_info()
if c_job_buffer == nil {
go_job_buffer.LastUpdate = int64(0)
go_job_buffer.RecordCount = uint32(0)
go_job_buffer.JobList = nil
return go_job_buffer
}
go_job_buffer.LastUpdate = int64(c_job_buffer.last_update)
go_job_buffer.RecordCount = uint32(c_job_buffer.record_count)
for i := uint32(0); i < go_job_buffer.RecordCount; i++ {
job := C.job_from_list(c_job_buffer, C.int(i))
go_job := Job_info_convert_c_to_go(job)
go_job_buffer.JobList = append(go_job_buffer.JobList, &go_job)
//fmt.Println(Reason_to_string(go_job.Job_state))
//fmt.Println(state_to_string(uint32(go_job.Job_state)))
}
C.slurm_free_job_info_msg(c_job_buffer)
return go_job_buffer
}
func Delete_job(id uint32) int32 {
error_code := C.slurm_kill_job(C.uint32_t(id), C.SIGKILL, C.uint16_t(0))
return int32(error_code)
}
func Get_job(id uint32) pbslurm.JobInfoMsg {
var go_job_buffer pbslurm.JobInfoMsg
c_job_buffer := C.get_single_job_info(C.uint32_t(id))
if c_job_buffer == nil {
go_job_buffer.LastUpdate = int64(0)
go_job_buffer.RecordCount = uint32(0)
go_job_buffer.JobList = nil
return go_job_buffer
}
go_job_buffer.LastUpdate = int64(c_job_buffer.last_update)
go_job_buffer.RecordCount = uint32(c_job_buffer.record_count)
for i := uint32(0); i < go_job_buffer.RecordCount; i++ {
job := C.job_from_list(c_job_buffer, C.int(i))
go_job := Job_info_convert_c_to_go(job)
go_job_buffer.JobList = append(go_job_buffer.JobList, &go_job)
//fmt.Println(Reason_to_string(go_job.Job_state))
//fmt.Println(state_to_string(uint32(go_job.Job_state)))
}
C.slurm_free_job_info_msg(c_job_buffer)
return go_job_buffer
}

View File

@ -1,139 +0,0 @@
package tianhe
/*
#cgo LDFLAGS: -lslurmdb
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <slurm/slurm.h>
#include <slurm/slurmdb.h>
#include <slurm/slurm_errno.h>
#include <memory.h>
#include <malloc.h>
slurmdb_job_rec_t *get_all_slurmdb_job() {
slurmdb_job_cond_t *job_cond = NULL;
void *conn = slurmdb_connection_get();
List joblist = slurmdb_jobs_get(conn, job_cond);
uint16_t listsize = slurm_list_count(joblist);
//qosinfo.record_count = size;
slurmdb_job_rec_t *jobarray = malloc(listsize * sizeof(slurmdb_job_rec_t));
ListIterator itr = slurm_list_iterator_create(joblist);
slurmdb_job_rec_t *rec = NULL;
int i = 0;
while ((rec = slurm_list_next(itr))) {
jobarray[i] = *rec;
i++;
}
slurmdb_connection_close(&conn);
slurm_list_destroy(joblist);
//int arraysize = sizeof(jobarray);
//printf("%d\n", arraysize);
return jobarray;
}
slurmdb_job_rec_t *job_from_array(slurmdb_job_rec_t *job_rec_array, int i) {
return (slurmdb_job_rec_t *) &(job_rec_array[i]);
}
slurmdb_job_rec_t *job_from_array_by_id(slurmdb_job_rec_t *job_rec_array, int job_id) {
int i;
int arraysize = sizeof(job_rec_array);
for (i=0; i<arraysize; i++)
{
//printf("var: %d : %p : %d \n", var, &(job_rec_array[var]), (job_rec_array[var]).stats.cpu_min);
//printf("%d \n",(job_rec_array[i]).stats.cpu_min);
//printf("var: %d : %p : %d \n", var, &(job_rec_array[var]), (job_rec_array[var]).jobid);
if (job_id==(job_rec_array[i]).jobid)
{
break;
} else {
return NULL;
}
}
return (slurmdb_job_rec_t *) &(job_rec_array[i]);
}
int getLength(slurmdb_job_rec_t *job_rec_array) {
return sizeof(job_rec_array);
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
)
func GetAllSlurmdbJobs() []*pbslurm.SlurmdbJobRec {
slurmJobs := []*pbslurm.SlurmdbJobRec{}
jobarray := C.get_all_slurmdb_job()
size := uint32(C.getLength(jobarray))
for i := uint32(0); i < size; i++ {
c_job := C.job_from_array(jobarray, C.int(i))
go_job := Slurmdb_Job_convert_c_to_go(c_job)
slurmJobs = append(slurmJobs, &go_job)
}
return slurmJobs
}
func GetSlurmdbJobById(job_id int) []*pbslurm.SlurmdbJobRec {
slurmJobs := []*pbslurm.SlurmdbJobRec{}
jobarray := C.get_all_slurmdb_job()
c_job := C.job_from_array_by_id(jobarray, C.int(job_id))
if c_job == nil {
return slurmJobs
}
go_job := Slurmdb_Job_convert_c_to_go(c_job)
slurmJobs = append(slurmJobs, &go_job)
return slurmJobs
}
func Slurmdb_Job_convert_c_to_go(c_struct_job *C.slurmdb_job_rec_t) pbslurm.SlurmdbJobRec {
var go_struct pbslurm.SlurmdbJobRec
go_struct.Account = C.GoString(c_struct_job.account)
go_struct.Associd = uint32(c_struct_job.associd)
go_struct.AllocCpu = uint32(c_struct_job.alloc_cpus)
go_struct.AllocNodes = uint32(c_struct_job.alloc_nodes)
go_struct.Blockid = C.GoString(c_struct_job.blockid)
go_struct.Cluster = C.GoString(c_struct_job.cluster)
go_struct.DerivedEs = C.GoString(c_struct_job.derived_es)
go_struct.DerivedEc = uint32(c_struct_job.derived_ec)
go_struct.End = int64(c_struct_job.end)
go_struct.Elapsed = uint32(c_struct_job.elapsed)
go_struct.Eligible = int64(c_struct_job.eligible)
go_struct.Exitcode = uint32(c_struct_job.exitcode)
go_struct.Gid = uint32(c_struct_job.gid)
go_struct.Jobid = uint32(c_struct_job.jobid)
go_struct.Jobname = C.GoString(c_struct_job.jobname)
go_struct.Lft = uint32(c_struct_job.lft)
go_struct.Nodes = C.GoString(c_struct_job.nodes)
go_struct.Priority = uint32(c_struct_job.priority)
go_struct.Partition = C.GoString(c_struct_job.partition)
//go_struct.Qosid = c_struct_job
//go_struct.Requid = c_struct_job
//go_struct.ReqMem = c_struct_job
//go_struct.ReqCpus = c_struct_job
//go_struct.Resvid = c_struct_job
//go_struct.Stats = c_struct_job
//go_struct.Start = c_struct_job
//go_struct.ShowFull = c_struct_job
//go_struct.State = c_struct_job
//go_struct.Submit = c_struct_job
//var stats_adrs []*pbslurm.SlurmdbStatsT
//var stats pbslurm.SlurmdbStatsT
//stat.ActCpufreq = float64(c_struct_job.stats.act_cpufreq)
//stats.CpuMin = uint32((c_struct_job.stats).cpu_min)
//stat.CpuAve = float64(c_struct_job.stats.cpu_ave)
//stats_adrs = append(stats_adrs, &stats)
//go_struct.Stats = stats
return go_struct
}

View File

@ -1,435 +0,0 @@
package tianhe
/*
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include<slurm/slurm.h>
#include<slurm/slurm_errno.h>
struct submit_response_msg *submit_job(struct job_descriptor *desc)
{
struct submit_response_msg *resp_msg;
if (slurm_submit_batch_job(desc,
&resp_msg)) {
return NULL;
}
return resp_msg;
}
void free_submit_response_msg(struct submit_response_msg *msg)
{
slurm_free_submit_response_response_msg(msg);
}
int update_job (struct job_descriptor *msg) {
return slurm_update_job (msg);
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
"fmt"
"unsafe"
)
func Submit_job(go_struct *pbslurm.JobDescriptor) pbslurm.SubmitResponseMsg {
var c_struct C.struct_job_descriptor
C.slurm_init_job_desc_msg(&c_struct)
if go_struct.Account != "" {
account_s := C.CString(go_struct.Account)
defer C.free(unsafe.Pointer(account_s))
c_struct.account = account_s
}
if go_struct.AcctgFreq != "" {
acctg_freq_s := C.CString(go_struct.AcctgFreq)
defer C.free(unsafe.Pointer(acctg_freq_s))
c_struct.acctg_freq = acctg_freq_s
}
if go_struct.AllocNode != "" {
alloc_node_s := C.CString(go_struct.AllocNode)
defer C.free(unsafe.Pointer(alloc_node_s))
c_struct.alloc_node = alloc_node_s
}
if go_struct.AllocRespPort != 0 {
c_struct.alloc_resp_port = C.uint16_t(go_struct.AllocRespPort)
}
if go_struct.AllocSid != 0 {
c_struct.alloc_sid = C.uint32_t(go_struct.AllocSid)
}
if len(go_struct.Argv) > 0 {
c_struct.argc = C.uint32_t(len(go_struct.Argv))
cArray := C.malloc(C.size_t(C.size_t(len(go_struct.Argv)) * C.size_t(unsafe.Sizeof(uintptr(0)))))
a := (*[1<<30 - 1]*C.char)(cArray)
for i := 0; i < len(go_struct.Argv); i++ {
a[i] = C.CString(go_struct.Argv[i].String())
}
c_struct.argv = (**C.char)(cArray)
fmt.Printf("test\n")
}
if go_struct.ArrayInx != "" {
array_inx_s := C.CString(go_struct.ArrayInx)
defer C.free(unsafe.Pointer(array_inx_s))
c_struct.array_inx = array_inx_s
}
if go_struct.BeginTime != 0 {
c_struct.begin_time = C.int64_t(go_struct.BeginTime)
}
if go_struct.CkptInterval != 0 {
c_struct.ckpt_interval = C.uint16_t(go_struct.CkptInterval)
}
if go_struct.CkptDir != "" {
ckpt_dir_s := C.CString(go_struct.CkptDir)
defer C.free(unsafe.Pointer(ckpt_dir_s))
c_struct.ckpt_dir = ckpt_dir_s
}
if go_struct.Comment != "" {
comment_s := C.CString(go_struct.Comment)
defer C.free(unsafe.Pointer(comment_s))
c_struct.comment = comment_s
}
if go_struct.Contiguous != 0 {
c_struct.contiguous = C.uint16_t(go_struct.Contiguous)
}
if go_struct.CpuBind != "" {
cpu_bind_s := C.CString(go_struct.CpuBind)
defer C.free(unsafe.Pointer(cpu_bind_s))
c_struct.cpu_bind = cpu_bind_s
}
if go_struct.CpuBindType != 0 {
c_struct.cpu_bind_type = C.uint16_t(go_struct.CpuBindType)
}
if go_struct.Dependency != "" {
dependency_s := C.CString(go_struct.Dependency)
defer C.free(unsafe.Pointer(dependency_s))
c_struct.dependency = dependency_s
}
if go_struct.EndTime != 0 {
c_struct.end_time = C.int64_t(go_struct.EndTime)
}
if len(go_struct.Environment) > 0 {
c_struct.env_size = C.uint32_t(len(go_struct.Environment))
cArray := C.malloc(C.size_t(C.size_t(len(go_struct.Environment)) * C.size_t(unsafe.Sizeof(uintptr(0)))))
a := (*[1<<30 - 1]*C.char)(cArray)
for i := 0; i < len(go_struct.Environment); i++ {
a[i] = C.CString(go_struct.Environment[i].String())
defer C.free(unsafe.Pointer(a[i]))
}
c_struct.environment = (**C.char)(cArray)
} else {
c_struct.env_size = 1
cArray := C.malloc(C.size_t(C.size_t(1) * C.size_t(unsafe.Sizeof(uintptr(0)))))
a := (*[1<<30 - 1]*C.char)(cArray)
a[0] = C.CString("SLURM_GO_JOB=TRUE")
defer C.free(unsafe.Pointer(a[0]))
c_struct.environment = (**C.char)(cArray)
}
if go_struct.ExcNodes != "" {
exc_nodes_s := C.CString(go_struct.ExcNodes)
defer C.free(unsafe.Pointer(exc_nodes_s))
c_struct.exc_nodes = exc_nodes_s
}
if go_struct.Features != "" {
features_s := C.CString(go_struct.Features)
defer C.free(unsafe.Pointer(features_s))
c_struct.features = features_s
}
if go_struct.GroupId != 0 {
c_struct.group_id = C.uint32_t(go_struct.GroupId)
}
if go_struct.Immediate != 0 {
c_struct.immediate = C.uint16_t(go_struct.Immediate)
}
if go_struct.JobId != 0 {
c_struct.job_id = C.uint32_t(go_struct.JobId)
}
if go_struct.KillOnNodeFail != 0 {
c_struct.kill_on_node_fail = C.uint16_t(go_struct.KillOnNodeFail)
}
if go_struct.Licenses != "" {
licenses_s := C.CString(go_struct.Licenses)
defer C.free(unsafe.Pointer(licenses_s))
c_struct.licenses = licenses_s
}
if go_struct.MailType != 0 {
c_struct.mail_type = C.uint16_t(go_struct.MailType)
}
if go_struct.MailUser != "" {
mail_user_s := C.CString(go_struct.MailUser)
defer C.free(unsafe.Pointer(mail_user_s))
c_struct.mail_user = mail_user_s
}
if go_struct.MemBind != "" {
mem_bind_s := C.CString(go_struct.MemBind)
defer C.free(unsafe.Pointer(mem_bind_s))
c_struct.mem_bind = mem_bind_s
}
if go_struct.MemBindType != 0 {
c_struct.mem_bind_type = C.uint16_t(go_struct.MemBindType)
}
if go_struct.Name != "" {
name_s := C.CString(go_struct.Name)
defer C.free(unsafe.Pointer(name_s))
c_struct.name = name_s
}
if go_struct.Network != "" {
network_s := C.CString(go_struct.Network)
defer C.free(unsafe.Pointer(network_s))
c_struct.network = network_s
}
if go_struct.Nice != 0 {
c_struct.nice = C.uint16_t(go_struct.Nice)
}
if go_struct.NumTasks != 0 {
c_struct.num_tasks = C.uint32_t(go_struct.NumTasks)
}
if go_struct.OpenMode != 0 {
c_struct.open_mode = C.uint8_t(go_struct.OpenMode)
}
if go_struct.OtherPort != 0 {
c_struct.other_port = C.uint16_t(go_struct.OtherPort)
}
if go_struct.Overcommit != 0 {
c_struct.overcommit = C.uint8_t(go_struct.Overcommit)
}
if go_struct.Partition != "" {
partition_s := C.CString(go_struct.Partition)
defer C.free(unsafe.Pointer(partition_s))
c_struct.partition = partition_s
}
if go_struct.PlaneSize != 0 {
c_struct.plane_size = C.uint16_t(go_struct.PlaneSize)
}
if go_struct.Priority != 0 {
c_struct.priority = C.uint32_t(go_struct.Priority)
}
if go_struct.Profile != 0 {
c_struct.profile = C.uint32_t(go_struct.Profile)
}
if go_struct.Qos != "" {
qos_s := C.CString(go_struct.Qos)
defer C.free(unsafe.Pointer(qos_s))
c_struct.qos = qos_s
}
if go_struct.Reboot != 0 {
c_struct.reboot = C.uint16_t(go_struct.Reboot)
}
if go_struct.RespHost != "" {
resp_host_s := C.CString(go_struct.RespHost)
defer C.free(unsafe.Pointer(resp_host_s))
c_struct.resp_host = resp_host_s
}
if go_struct.ReqNodes != "" {
req_nodes_s := C.CString(go_struct.ReqNodes)
defer C.free(unsafe.Pointer(req_nodes_s))
c_struct.req_nodes = req_nodes_s
}
if go_struct.Requeue != 0 {
c_struct.requeue = C.uint16_t(go_struct.Requeue)
}
if go_struct.Reservation != "" {
reservation_s := C.CString(go_struct.Reservation)
defer C.free(unsafe.Pointer(reservation_s))
c_struct.reservation = reservation_s
}
if go_struct.Script != "" {
script_s := C.CString(go_struct.Script)
defer C.free(unsafe.Pointer(script_s))
c_struct.script = script_s
}
if go_struct.Shared != 0 {
c_struct.shared = C.uint16_t(go_struct.Shared)
}
if go_struct.SpankJobEnvSize != 0 {
c_struct.spank_job_env_size = C.uint32_t(go_struct.SpankJobEnvSize)
}
if go_struct.TaskDist != 0 {
c_struct.task_dist = C.uint16_t(go_struct.TaskDist)
}
if go_struct.TimeLimit != 0 {
c_struct.time_limit = C.uint32_t(go_struct.TimeLimit)
}
if go_struct.TimeMin != 0 {
c_struct.time_min = C.uint32_t(go_struct.TimeMin)
}
//if go_struct.User_id != 0 {
// c_struct.user_id = C.uint32_t(go_struct.User_id)
//}
c_struct.user_id = C.uint32_t(go_struct.UserId)
if go_struct.WaitAllNodes != 0 {
c_struct.wait_all_nodes = C.uint16_t(go_struct.WaitAllNodes)
}
if go_struct.WarnSignal != 0 {
c_struct.warn_signal = C.uint16_t(go_struct.WarnSignal)
}
if go_struct.WarnTime != 0 {
c_struct.warn_time = C.uint16_t(go_struct.WarnTime)
}
if go_struct.WorkDir != "" {
work_dir_s := C.CString(go_struct.WorkDir)
defer C.free(unsafe.Pointer(work_dir_s))
c_struct.work_dir = work_dir_s
}
if go_struct.CpusPerTask != 0 {
c_struct.cpus_per_task = C.uint16_t(go_struct.CpusPerTask)
}
if go_struct.MinCpus != 0 {
c_struct.min_cpus = C.uint32_t(go_struct.MinCpus)
}
if go_struct.MaxCpus != 0 {
c_struct.max_cpus = C.uint32_t(go_struct.MaxCpus)
}
if go_struct.MinNodes != 0 {
c_struct.min_nodes = C.uint32_t(go_struct.MinNodes)
}
if go_struct.MaxNodes != 0 {
c_struct.max_nodes = C.uint32_t(go_struct.MaxNodes)
}
if go_struct.BoardsPerNode != 0 {
c_struct.boards_per_node = C.uint16_t(go_struct.BoardsPerNode)
}
if go_struct.SocketsPerBoard != 0 {
c_struct.sockets_per_board = C.uint16_t(go_struct.SocketsPerBoard)
}
if go_struct.SocketsPerNode != 0 {
c_struct.sockets_per_node = C.uint16_t(go_struct.SocketsPerNode)
}
if go_struct.CoresPerSocket != 0 {
c_struct.cores_per_socket = C.uint16_t(go_struct.CoresPerSocket)
}
if go_struct.ThreadsPerCore != 0 {
c_struct.threads_per_core = C.uint16_t(go_struct.ThreadsPerCore)
}
if go_struct.NtasksPerNode != 0 {
c_struct.ntasks_per_node = C.uint16_t(go_struct.NtasksPerNode)
}
if go_struct.NtasksPerSocket != 0 {
c_struct.ntasks_per_socket = C.uint16_t(go_struct.NtasksPerSocket)
}
if go_struct.NtasksPerCore != 0 {
c_struct.ntasks_per_core = C.uint16_t(go_struct.NtasksPerCore)
}
if go_struct.NtasksPerBoard != 0 {
c_struct.ntasks_per_board = C.uint16_t(go_struct.NtasksPerBoard)
}
if go_struct.PnMinCpus != 0 {
c_struct.pn_min_cpus = C.uint16_t(go_struct.PnMinCpus)
}
if go_struct.PnMinMemory != 0 {
c_struct.pn_min_memory = C.uint32_t(go_struct.PnMinMemory)
}
if go_struct.PnMinTmpDisk != 0 {
c_struct.pn_min_tmp_disk = C.uint32_t(go_struct.PnMinTmpDisk)
}
if go_struct.ReqSwitch != 0 {
c_struct.req_switch = C.uint32_t(go_struct.ReqSwitch)
}
if go_struct.StdErr != "" {
std_err_s := C.CString(go_struct.StdErr)
defer C.free(unsafe.Pointer(std_err_s))
c_struct.std_err = std_err_s
}
if go_struct.StdIn != "" {
std_in_s := C.CString(go_struct.StdIn)
defer C.free(unsafe.Pointer(std_in_s))
c_struct.std_in = std_in_s
}
if go_struct.StdOut != "" {
std_out_s := C.CString(go_struct.StdOut)
defer C.free(unsafe.Pointer(std_out_s))
c_struct.std_out = std_out_s
}
if go_struct.Wait4Switch != 0 {
c_struct.wait4switch = C.uint32_t(go_struct.Wait4Switch)
}
if go_struct.Wckey != "" {
wckey_s := C.CString(go_struct.Wckey)
defer C.free(unsafe.Pointer(wckey_s))
c_struct.wckey = wckey_s
}
c_msg := C.submit_job(&c_struct)
defer C.free_submit_response_msg(c_msg)
if c_msg == nil {
go_msg := pbslurm.SubmitResponseMsg{}
go_msg.JobId = 1<<31 - 1
go_msg.ErrorCode = uint32(C.slurm_get_errno())
return go_msg
}
go_msg := submit_response_msg_convert_c_to_go(c_msg)
return go_msg
}
func Update_job(update_info *pbslurm.UpdateJobOptions, JobId uint32) int32 {
var c_struct C.struct_job_descriptor
C.slurm_init_job_desc_msg(&c_struct)
if update_info.Partition != "" {
partition_s := C.CString(update_info.Partition)
defer C.free(unsafe.Pointer(partition_s))
c_struct.partition = partition_s
}
if update_info.Qos != "" {
qos_s := C.CString(update_info.Qos)
defer C.free(unsafe.Pointer(qos_s))
c_struct.qos = qos_s
}
if update_info.NumTasks != 0 {
c_struct.num_tasks = C.uint32_t(update_info.NumTasks)
}
if update_info.NtasksPerCore != 0 {
c_struct.ntasks_per_core = C.uint16_t(update_info.NtasksPerCore)
}
if update_info.NtasksPerNode != 0 {
c_struct.ntasks_per_node = C.uint16_t(update_info.NtasksPerNode)
}
if update_info.NtasksPerSocket != 0 {
c_struct.ntasks_per_socket = C.uint16_t(update_info.NtasksPerSocket)
}
if update_info.MaxNodes != 0 {
c_struct.max_nodes = C.uint32_t(update_info.MaxNodes)
}
if update_info.MinNodes != 0 {
c_struct.min_nodes = C.uint32_t(update_info.MinNodes)
}
job_list := Get_job(JobId)
if job_list.JobList == nil {
return -1
}
job := job_list.JobList[0]
if job.JobState != C.JOB_PENDING {
return int32(C.ESLURM_JOB_NOT_PENDING)
}
c_struct.job_id = C.uint32_t(JobId)
err := C.update_job(&c_struct)
return int32(err)
}
func submit_response_msg_convert_c_to_go(c_struct *C.struct_submit_response_msg) pbslurm.SubmitResponseMsg {
var go_struct pbslurm.SubmitResponseMsg
go_struct.JobId = uint32(c_struct.job_id)
go_struct.StepId = uint32(c_struct.step_id)
go_struct.ErrorCode = uint32(c_struct.error_code)
return go_struct
}

View File

@ -1,111 +0,0 @@
package tianhe
/*
#include<stdlib.h>
#include<slurm/slurm.h>
#include<slurm/slurm_errno.h>
struct node_info_msg *get_node_info(){
struct node_info_msg* node_buffer;
if(slurm_load_node ((time_t) NULL,
&node_buffer, SHOW_ALL))
return NULL;
return node_buffer;
}
struct node_info_msg *get_single_node_info(char* name){
struct node_info_msg* node_buffer;
if( slurm_load_node_single (&node_buffer, name, SHOW_DETAIL))
return NULL;
return node_buffer;
}
struct node_info* node_from_list(struct node_info_msg *list, int i){
return &list->node_array[i];
}
void free_node_buffer(void* buffer){
slurm_free_node_info_msg ((struct node_info_msg*)buffer);
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
)
type NodeInfoMsg struct {
LastUpdate int64
RecordCount uint32
ErrorCode uint32
NodeInfoList []pbslurm.NodeInfo
}
func Node_info_convert_c_to_go(c_struct *C.struct_node_info) pbslurm.NodeInfo {
var go_struct pbslurm.NodeInfo
go_struct.Arch = C.GoString(c_struct.arch)
go_struct.Boards = uint32(c_struct.boards)
go_struct.BootTime = int64(c_struct.boot_time)
go_struct.Cores = uint32(c_struct.cores)
go_struct.CpuLoad = uint32(c_struct.cpu_load)
go_struct.Cpus = uint32(c_struct.cpus)
go_struct.Features = C.GoString(c_struct.features)
go_struct.Gres = C.GoString(c_struct.gres)
go_struct.Name = C.GoString(c_struct.name)
go_struct.NodeAddr = C.GoString(c_struct.node_addr)
go_struct.NodeHostname = C.GoString(c_struct.node_hostname)
go_struct.NodeState = uint32(c_struct.node_state)
go_struct.Os = C.GoString(c_struct.os)
go_struct.RealMemory = uint64(c_struct.real_memory)
go_struct.Reason = C.GoString(c_struct.reason)
go_struct.ReasonTime = int64(c_struct.reason_time)
go_struct.ReasonUid = uint32(c_struct.reason_uid)
go_struct.SlurmdStartTime = int64(c_struct.slurmd_start_time)
go_struct.Sockets = uint32(c_struct.sockets)
go_struct.Threads = uint32(c_struct.threads)
go_struct.TmpDisk = uint32(c_struct.tmp_disk)
go_struct.Weight = uint32(c_struct.weight)
return go_struct
}
func NodeDescriptorConvertCToGo(cStruct *C.struct_node_info) pbslurm.NodeInfo {
var goStruct pbslurm.NodeInfo
goStruct.Name = C.GoString(cStruct.name)
return goStruct
}
func GetNodeInfo() NodeInfoMsg {
var goNodeBuffer NodeInfoMsg
cNodeBuffer := C.get_node_info()
goNodeBuffer.RecordCount = uint32(cNodeBuffer.record_count)
goNodeBuffer.NodeInfoList = make([]pbslurm.NodeInfo, cNodeBuffer.record_count, cNodeBuffer.record_count)
for i := uint32(0); i < goNodeBuffer.RecordCount; i++ {
Node := C.node_from_list(cNodeBuffer, C.int(i))
goNode := NodeDescriptorConvertCToGo(Node)
goNodeBuffer.NodeInfoList[i] = goNode
}
return goNodeBuffer
}
func Get_all_nodes() NodeInfoMsg {
var go_node_buffer NodeInfoMsg
c_node_buffer := C.get_node_info()
if c_node_buffer == nil {
go_node_buffer.LastUpdate = int64(0)
go_node_buffer.RecordCount = uint32(0)
go_node_buffer.ErrorCode = uint32(C.slurm_get_errno())
return go_node_buffer
}
go_node_buffer.LastUpdate = int64(c_node_buffer.last_update)
go_node_buffer.RecordCount = uint32(c_node_buffer.record_count)
go_node_buffer.NodeInfoList = make([]pbslurm.NodeInfo, c_node_buffer.record_count, c_node_buffer.record_count)
for i := uint32(0); i < go_node_buffer.RecordCount; i++ {
node := C.node_from_list(c_node_buffer, C.int(i))
go_node := Node_info_convert_c_to_go(node)
go_node_buffer.NodeInfoList[i] = go_node
}
C.slurm_free_node_info_msg(c_node_buffer)
return go_node_buffer
}

View File

@ -1,109 +0,0 @@
package tianhe
/*
//#cgo LDFLAGS: -lslurm
#include<stdlib.h>
#include<slurm/slurm.h>
struct partition_info_msg *get_partition_info(){
struct partition_info_msg* partition_buffer;
if( slurm_load_partitions ((time_t) NULL,
&partition_buffer, SHOW_ALL))
return NULL;
return partition_buffer;
}
struct partition_info* partition_from_list(struct partition_info_msg *list, int i){
return &list->partition_array[i];
}
void free_partition_buffer(void* buffer){
slurm_free_partition_info_msg ((struct partition_info_msg*)buffer);
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
)
func Partition_info_convert_c_to_go(c_struct *C.struct_partition_info) pbslurm.PartitionInfo {
var go_struct pbslurm.PartitionInfo
go_struct.AllowAllocNodes = C.GoString(c_struct.allow_alloc_nodes)
go_struct.AllowGroups = C.GoString(c_struct.allow_groups)
go_struct.Alternate = C.GoString(c_struct.alternate)
go_struct.CrType = uint32(c_struct.cr_type)
go_struct.DefMemPerCpu = uint64(c_struct.def_mem_per_cpu)
go_struct.DefaultTime = uint32(c_struct.default_time)
go_struct.Flags = uint32(c_struct.flags)
go_struct.GraceTime = uint32(c_struct.grace_time)
go_struct.MaxCpusPerNode = uint32(c_struct.max_cpus_per_node)
go_struct.MaxMemPerCpu = uint64(c_struct.max_mem_per_cpu)
go_struct.MaxNodes = uint32(c_struct.max_nodes)
go_struct.MaxShare = uint32(c_struct.max_share)
go_struct.MaxTime = uint32(c_struct.max_time)
go_struct.MinNodes = uint32(c_struct.min_nodes)
go_struct.Name = C.GoString(c_struct.name)
//go_struct.Node_inx = int32(C.int32_ptr(c_struct.node_inx))
/*t := C.find_node_inx(c_struct.node_inx)
fmt.Printf("%d", t)
go_struct.Node_inx = make([]int32, t, t)
for i := int32(0); i < int32(t); i++ {
go_struct.Node_inx[i] = int32(C.int32_ptr(c_struct.node_inx, C.int(i)))
}*/
go_struct.Nodes = C.GoString(c_struct.nodes)
go_struct.PreemptMode = uint32(c_struct.preempt_mode)
go_struct.StateUp = uint32(c_struct.state_up)
go_struct.TotalCpus = uint32(c_struct.total_cpus)
go_struct.TotalNodes = uint32(c_struct.total_nodes)
return go_struct
}
type PartitionInfoMsg struct {
LastUpdate int64
RecordCount uint32
PartitionInfoList []pbslurm.PartitionInfo
}
func Get_partitions() PartitionInfoMsg {
var go_partition_buffer PartitionInfoMsg
c_partition_buffer := C.get_partition_info()
if c_partition_buffer == nil {
go_partition_buffer.LastUpdate = int64(0)
go_partition_buffer.RecordCount = uint32(0)
return go_partition_buffer
}
go_partition_buffer.LastUpdate = int64(c_partition_buffer.last_update)
go_partition_buffer.RecordCount = uint32(c_partition_buffer.record_count)
go_partition_buffer.PartitionInfoList = make([]pbslurm.PartitionInfo, c_partition_buffer.record_count, c_partition_buffer.record_count)
for i := uint32(0); i < go_partition_buffer.RecordCount; i++ {
partition := C.partition_from_list(c_partition_buffer, C.int(i))
go_partition := Partition_info_convert_c_to_go(partition)
go_partition_buffer.PartitionInfoList[i] = go_partition
}
C.slurm_free_partition_info_msg(c_partition_buffer)
return go_partition_buffer
}
func GetPartitionsInfo() PartitionInfoMsg {
var goPartitionBuffer PartitionInfoMsg
cPartitionBuffer := C.get_partition_info()
goPartitionBuffer.RecordCount = uint32(cPartitionBuffer.record_count)
goPartitionBuffer.PartitionInfoList = make([]pbslurm.PartitionInfo, cPartitionBuffer.record_count, cPartitionBuffer.record_count)
for i := uint32(0); i < goPartitionBuffer.RecordCount; i++ {
partition := C.partition_from_list(cPartitionBuffer, C.int(i))
goPartition := PartitionDescriptorConvertCToGo(partition)
goPartitionBuffer.PartitionInfoList[i] = goPartition
}
return goPartitionBuffer
}
func PartitionDescriptorConvertCToGo(cStruct *C.struct_partition_info) pbslurm.PartitionInfo {
var goStruct pbslurm.PartitionInfo
goStruct.Name = C.GoString(cStruct.name)
return goStruct
}

View File

@ -1,159 +0,0 @@
package tianhe
/*
#cgo LDFLAGS: -lslurmdb
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <slurm/slurm.h>
#include <slurm/slurmdb.h>
#include <slurm/slurm_errno.h>
#include <memory.h>
#include <malloc.h>
typedef struct slurmdb_qos_rec {
char *description;
uint32_t id;
uint32_t flags;
uint32_t grace_time;
uint64_t grp_cpu_mins;
uint64_t grp_cpu_run_mins;
uint32_t grp_cpus;
uint32_t grp_jobs;
uint32_t grp_mem;
uint32_t grp_nodes;
uint32_t grp_submit_jobs;
uint32_t grp_wall;
uint64_t max_cpu_mins_pj;
uint64_t max_cpu_run_mins_pu;
uint32_t max_cpus_pj;
uint32_t max_cpus_pu;
uint32_t max_jobs_pu;
uint32_t max_nodes_pj;
uint32_t max_nodes_pu;
uint32_t max_submit_jobs_pu;
uint32_t max_wall_pj;
char *name;
bitstr_t *preempt_bitstr;
List preempt_list;
uint16_t preempt_mode;
uint32_t priority;
assoc_mgr_qos_usage_t *usage;
double usage_factor;
double usage_thres;
} slurmdb_qos_rec_a;
typedef struct qos_info {
uint32_t record_count;
slurmdb_qos_rec_t *array;
} qos_info_t;
struct qos_info Get_qos_list() {
struct qos_info qosinfo;
slurmdb_qos_cond_t *qos_cond = NULL;
void *conn = slurmdb_connection_get();
List qoslist = slurmdb_qos_get(conn, qos_cond);
uint16_t size = slurm_list_count(qoslist);
qosinfo.record_count = size;
qosinfo.array = malloc(size * sizeof(slurmdb_qos_rec_t));
slurmdb_qos_rec_t *rec = NULL;
//slurmdb_init_qos_rec()
ListIterator itr = slurm_list_iterator_create(qoslist);
int i = 0;
while ((rec = slurm_list_next(itr))) {
qosinfo.array[i] = *rec;
i++;
}
slurmdb_connection_close(&conn);
slurm_list_destroy(qoslist);
return qosinfo;
}
slurmdb_qos_rec_t *qos_from_list(struct qos_info *qos_rec_t, int i) {
return (slurmdb_qos_rec_t *) &qos_rec_t->array[i];
}
slurmdb_qos_rec_t *qos_from_list_by_name(slurmdb_qos_rec_t *qos_rec_array, char* qos_name) {
int i;
int arraysize = sizeof(qos_rec_array);
for (i=0; i<arraysize; i++)
{
if (strcmp(qos_name, (qos_rec_array[i]).name) == 0)
{
break;
} else {
return NULL;
}
}
return (slurmdb_qos_rec_t *) &(qos_rec_array[i]);
}
*/
import "C"
import pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
func Get_Qos() []*pbslurm.SlurmdbQosRec {
var go_qos_buffer pbslurm.QosInfoMsg
c_qos_buffer := C.Get_qos_list()
go_qos_buffer.RecordCount = uint32(c_qos_buffer.record_count)
for i := uint32(0); i < go_qos_buffer.RecordCount; i++ {
qos := C.qos_from_list(&c_qos_buffer, C.int(i))
go_qos := Qos_convert_c_to_go(qos)
go_qos_buffer.SlurmdbQosRec = append(go_qos_buffer.SlurmdbQosRec, &go_qos)
}
return go_qos_buffer.SlurmdbQosRec
}
func GetQosByName(name string) pbslurm.SlurmdbQosRec {
qos := pbslurm.SlurmdbQosRec{}
qos_list := C.Get_qos_list()
c_qos := C.qos_from_list_by_name(qos_list.array, C.CString(name))
if c_qos == nil {
return qos
}
go_qos := Qos_convert_c_to_go(c_qos)
return go_qos
}
func Qos_convert_c_to_go(c_struct *C.slurmdb_qos_rec_t) pbslurm.SlurmdbQosRec {
var go_struct pbslurm.SlurmdbQosRec
go_struct.Description = C.GoString(c_struct.description)
go_struct.Flags = uint32(c_struct.flags)
go_struct.GrpCpus = uint32(c_struct.grp_cpus)
go_struct.GraceTime = uint32(c_struct.grace_time)
go_struct.GrpCpuMins = uint64(c_struct.grp_cpu_mins)
go_struct.GrpCpuRunMins = uint64(c_struct.grp_cpu_run_mins)
go_struct.GrpJobs = uint32(c_struct.grp_jobs)
go_struct.GrpMem = uint32(c_struct.grp_mem)
go_struct.GrpNodes = uint32(c_struct.grp_nodes)
go_struct.GrpSubmitJobs = uint32(c_struct.grp_submit_jobs)
go_struct.GrpWall = uint32(c_struct.grp_wall)
go_struct.Id = uint32(c_struct.id)
go_struct.MaxCpusPj = uint32(c_struct.max_cpus_pj)
go_struct.MaxCpuMinsPj = uint64(c_struct.max_cpu_mins_pj)
go_struct.MaxCpusPu = uint32(c_struct.max_cpus_pu)
go_struct.MaxJobsPu = uint32(c_struct.max_jobs_pu)
go_struct.MaxCpuRunMinsPu = uint64(c_struct.max_cpu_run_mins_pu)
go_struct.MaxNodesPj = uint32(c_struct.max_nodes_pj)
go_struct.MaxNodesPu = uint32(c_struct.max_nodes_pu)
go_struct.MaxSubmitJobsPu = uint32(c_struct.max_submit_jobs_pu)
go_struct.MaxWallPj = uint32(c_struct.max_wall_pj)
go_struct.Name = C.GoString(c_struct.name)
go_struct.Priority = uint32(c_struct.priority)
//go_struct.PreemptList = c_struct.preempt_list
go_struct.PreemptMode = uint32(c_struct.preempt_mode)
go_struct.UsageThres = float64(c_struct.usage_factor)
go_struct.UsageFactor = float64(c_struct.usage_thres)
return go_struct
}

View File

@ -1,101 +0,0 @@
package tianhe
/*
//#cgo LDFLAGS: -lslurm
#include<stdlib.h>
#include<slurm/slurm.h>
#include<slurm/slurm_errno.h>
struct reserve_info_msg *get_reserve_info(){
struct reserve_info_msg* reservation_buffer;
if(slurm_load_reservations ((time_t) NULL,
&reservation_buffer))
return NULL;
return reservation_buffer;
}
struct reserve_info* reservation_from_list(struct reserve_info_msg *list, int i){
return &list->reservation_array[i];
}
void free_reservation_buffer(void* buffer){
slurm_free_reservation_info_msg ((struct reserve_info_msg*)buffer);
}
*/
import "C"
import (
pbslurm "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_slurm/gen/idl"
)
type ReservationInfoMsg struct {
LastUpdate int64
RecordCount uint32
ReservationList []pbslurm.ReservationInfo
ErrorCode uint32
}
func Reservation_info_convert_c_to_go(c_struct *C.struct_reserve_info) pbslurm.ReservationInfo {
var go_struct pbslurm.ReservationInfo
go_struct.Accounts = C.GoString(c_struct.accounts)
go_struct.EndTime = int64(c_struct.end_time)
go_struct.Features = C.GoString(c_struct.features)
go_struct.Flags = uint32(c_struct.flags)
go_struct.Licenses = C.GoString(c_struct.licenses)
go_struct.Name = C.GoString(c_struct.name)
go_struct.Features = C.GoString(c_struct.features)
go_struct.NodeCnt = uint32(c_struct.node_cnt)
go_struct.CoreCnt = uint32(c_struct.core_cnt)
/*t := C.find_node_inx(c_struct.node_inx)
fmt.Printf("%d", t)
go_struct.Node_inx = make([]int32, t, t)
for i := int32(0); i < int32(t); i++ {
go_struct.Node_inx[i] = int32(C.int32_ptr(c_struct.node_inx, C.int(i)))
}*/
go_struct.NodeList = C.GoString(c_struct.node_list)
go_struct.Partition = C.GoString(c_struct.partition)
go_struct.StartTime = int64(c_struct.start_time)
//go_struct.clusters = C.GoString(c_struct.clusters)
return go_struct
}
func Get_all_reservation() ReservationInfoMsg {
var go_reservation_buffer ReservationInfoMsg
c_reservation_buffer := C.get_reserve_info()
if c_reservation_buffer == nil {
go_reservation_buffer.LastUpdate = int64(0)
go_reservation_buffer.RecordCount = uint32(0)
go_reservation_buffer.ErrorCode = uint32(C.slurm_get_errno())
return go_reservation_buffer
}
go_reservation_buffer.LastUpdate = int64(c_reservation_buffer.last_update)
go_reservation_buffer.RecordCount = uint32(c_reservation_buffer.record_count)
go_reservation_buffer.ReservationList = make([]pbslurm.ReservationInfo, c_reservation_buffer.record_count, c_reservation_buffer.record_count)
for i := uint32(0); i < go_reservation_buffer.RecordCount; i++ {
reservation := C.reservation_from_list(c_reservation_buffer, C.int(i))
go_reservation := Reservation_info_convert_c_to_go(reservation)
go_reservation_buffer.ReservationList[i] = go_reservation
}
C.slurm_free_reservation_info_msg(c_reservation_buffer)
return go_reservation_buffer
}
func GetReservationsInfo() ReservationInfoMsg {
var goReservationBuffer ReservationInfoMsg
cReservationBuffer := C.get_reserve_info()
goReservationBuffer.RecordCount = uint32(cReservationBuffer.record_count)
goReservationBuffer.ReservationList = make([]pbslurm.ReservationInfo, cReservationBuffer.record_count, cReservationBuffer.record_count)
for i := uint32(0); i < goReservationBuffer.RecordCount; i++ {
Reservation := C.reservation_from_list(cReservationBuffer, C.int(i))
goReservation := ReservationDescriptorConvertCToGo(Reservation)
goReservationBuffer.ReservationList[i] = goReservation
}
return goReservationBuffer
}
func ReservationDescriptorConvertCToGo(cStruct *C.struct_reserve_info) pbslurm.ReservationInfo {
var goStruct pbslurm.ReservationInfo
goStruct.Name = C.GoString(cStruct.name)
return goStruct
}

View File

@ -1,17 +0,0 @@
version: v1
plugins:
- name: go
out: gen
opt:
- paths=source_relative
- name: go-grpc
out: gen
opt:
- paths=source_relative
- name: grpc-gateway
out: gen
opt:
- paths=source_relative
- grpc_api_configuration=idl/ecs.yaml
- name: openapiv2
out: gen/openapiv2

View File

@ -1,13 +0,0 @@
version: v1
name: buf.build/JCCE/PCM
breaking:
use:
- FILE
lint:
use:
- DEFAULT
# ignore:
# - google/type/datetime.proto
deps:
- buf.build/googleapis/googleapis
- buf.build/grpc-ecosystem/grpc-gateway

File diff suppressed because it is too large Load Diff

View File

@ -1,841 +0,0 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: idl/ecs.proto
/*
Package ecspb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package ecspb
import (
"context"
"io"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// Suppress "imported and not used" errors
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = metadata.Join
func request_EcsService_CreateMultipleEcs_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreateEcsMultipleReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CreateMultipleEcs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_CreateMultipleEcs_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreateEcsMultipleReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.CreateMultipleEcs(ctx, &protoReq)
return msg, metadata, err
}
func request_EcsService_CreateEcs_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreateEcsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CreateEcs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_CreateEcs_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreateEcsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.CreateEcs(ctx, &protoReq)
return msg, metadata, err
}
func request_EcsService_DeleteEcs_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DeleteEcsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DeleteEcs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_DeleteEcs_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DeleteEcsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.DeleteEcs(ctx, &protoReq)
return msg, metadata, err
}
func request_EcsService_UpdateEcs_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq UpdateEcsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.UpdateEcs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_UpdateEcs_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq UpdateEcsReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.UpdateEcs(ctx, &protoReq)
return msg, metadata, err
}
var (
filter_EcsService_ListEcsDetail_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_EcsService_ListEcsDetail_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListDetailReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EcsService_ListEcsDetail_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ListEcsDetail(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_ListEcsDetail_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListDetailReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EcsService_ListEcsDetail_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ListEcsDetail(ctx, &protoReq)
return msg, metadata, err
}
var (
filter_EcsService_ListEcs_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_EcsService_ListEcs_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EcsService_ListEcs_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ListEcs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_ListEcs_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EcsService_ListEcs_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ListEcs(ctx, &protoReq)
return msg, metadata, err
}
func request_EcsService_ListEcsAll_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListAllReq
var metadata runtime.ServerMetadata
msg, err := client.ListEcsAll(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_ListEcsAll_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListAllReq
var metadata runtime.ServerMetadata
msg, err := server.ListEcsAll(ctx, &protoReq)
return msg, metadata, err
}
func request_EcsService_ActionEcs_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ActionReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ActionEcs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_ActionEcs_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ActionReq
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ActionEcs(ctx, &protoReq)
return msg, metadata, err
}
var (
filter_EcsService_ListEcsImages_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_EcsService_ListEcsImages_0(ctx context.Context, marshaler runtime.Marshaler, client EcsServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListImagesReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EcsService_ListEcsImages_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ListEcsImages(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_EcsService_ListEcsImages_0(ctx context.Context, marshaler runtime.Marshaler, server EcsServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListImagesReq
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EcsService_ListEcsImages_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ListEcsImages(ctx, &protoReq)
return msg, metadata, err
}
// RegisterEcsServiceHandlerServer registers the http handlers for service EcsService to "mux".
// UnaryRPC :call EcsServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterEcsServiceHandlerFromEndpoint instead.
func RegisterEcsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server EcsServiceServer) error {
mux.Handle("POST", pattern_EcsService_CreateMultipleEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/CreateMultipleEcs", runtime.WithHTTPPathPattern("/apis/ecs/createMultiple"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_CreateMultipleEcs_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_CreateMultipleEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_EcsService_CreateEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/CreateEcs", runtime.WithHTTPPathPattern("/apis/ecs/create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_CreateEcs_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_CreateEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_EcsService_DeleteEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/DeleteEcs", runtime.WithHTTPPathPattern("/apis/ecs/delete"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_DeleteEcs_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_DeleteEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PUT", pattern_EcsService_UpdateEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/UpdateEcs", runtime.WithHTTPPathPattern("/apis/ecs/update"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_UpdateEcs_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_UpdateEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcsDetail_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/ListEcsDetail", runtime.WithHTTPPathPattern("/apis/ecs/detail"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ListEcsDetail_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcsDetail_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/ListEcs", runtime.WithHTTPPathPattern("/apis/ecs"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ListEcs_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcsAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/ListEcsAll", runtime.WithHTTPPathPattern("/apis/ecs/all"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ListEcsAll_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcsAll_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_EcsService_ActionEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/ActionEcs", runtime.WithHTTPPathPattern("/apis/ecs/action"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ActionEcs_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ActionEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcsImages_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/ecs.EcsService/ListEcsImages", runtime.WithHTTPPathPattern("/apis/ecs/listImages"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ListEcsImages_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcsImages_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterEcsServiceHandlerFromEndpoint is same as RegisterEcsServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterEcsServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterEcsServiceHandler(ctx, mux, conn)
}
// RegisterEcsServiceHandler registers the http handlers for service EcsService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterEcsServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterEcsServiceHandlerClient(ctx, mux, NewEcsServiceClient(conn))
}
// RegisterEcsServiceHandlerClient registers the http handlers for service EcsService
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "EcsServiceClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "EcsServiceClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "EcsServiceClient" to call the correct interceptors.
func RegisterEcsServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client EcsServiceClient) error {
mux.Handle("POST", pattern_EcsService_CreateMultipleEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/CreateMultipleEcs", runtime.WithHTTPPathPattern("/apis/ecs/createMultiple"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_CreateMultipleEcs_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_CreateMultipleEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_EcsService_CreateEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/CreateEcs", runtime.WithHTTPPathPattern("/apis/ecs/create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_CreateEcs_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_CreateEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_EcsService_DeleteEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/DeleteEcs", runtime.WithHTTPPathPattern("/apis/ecs/delete"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_DeleteEcs_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_DeleteEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PUT", pattern_EcsService_UpdateEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/UpdateEcs", runtime.WithHTTPPathPattern("/apis/ecs/update"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_UpdateEcs_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_UpdateEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcsDetail_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/ListEcsDetail", runtime.WithHTTPPathPattern("/apis/ecs/detail"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ListEcsDetail_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcsDetail_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/ListEcs", runtime.WithHTTPPathPattern("/apis/ecs"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ListEcs_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcsAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/ListEcsAll", runtime.WithHTTPPathPattern("/apis/ecs/all"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ListEcsAll_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcsAll_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_EcsService_ActionEcs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/ActionEcs", runtime.WithHTTPPathPattern("/apis/ecs/action"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ActionEcs_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ActionEcs_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EcsService_ListEcsImages_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/ecs.EcsService/ListEcsImages", runtime.WithHTTPPathPattern("/apis/ecs/listImages"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ListEcsImages_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_EcsService_ListEcsImages_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_EcsService_CreateMultipleEcs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "createMultiple"}, ""))
pattern_EcsService_CreateEcs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "create"}, ""))
pattern_EcsService_DeleteEcs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "delete"}, ""))
pattern_EcsService_UpdateEcs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "update"}, ""))
pattern_EcsService_ListEcsDetail_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "detail"}, ""))
pattern_EcsService_ListEcs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"apis", "ecs"}, ""))
pattern_EcsService_ListEcsAll_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "all"}, ""))
pattern_EcsService_ActionEcs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "action"}, ""))
pattern_EcsService_ListEcsImages_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"apis", "ecs", "listImages"}, ""))
)
var (
forward_EcsService_CreateMultipleEcs_0 = runtime.ForwardResponseMessage
forward_EcsService_CreateEcs_0 = runtime.ForwardResponseMessage
forward_EcsService_DeleteEcs_0 = runtime.ForwardResponseMessage
forward_EcsService_UpdateEcs_0 = runtime.ForwardResponseMessage
forward_EcsService_ListEcsDetail_0 = runtime.ForwardResponseMessage
forward_EcsService_ListEcs_0 = runtime.ForwardResponseMessage
forward_EcsService_ListEcsAll_0 = runtime.ForwardResponseMessage
forward_EcsService_ActionEcs_0 = runtime.ForwardResponseMessage
forward_EcsService_ListEcsImages_0 = runtime.ForwardResponseMessage
)

View File

@ -1,411 +0,0 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc (unknown)
// source: idl/ecs.proto
package ecspb
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// EcsServiceClient is the client API for EcsService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type EcsServiceClient interface {
// 创建多家云ECS
CreateMultipleEcs(ctx context.Context, in *CreateEcsMultipleReq, opts ...grpc.CallOption) (*CreateEcsMultipleResp, error)
// 创建ECS
CreateEcs(ctx context.Context, in *CreateEcsReq, opts ...grpc.CallOption) (*CreateEcsResp, error)
// 删除ECS
DeleteEcs(ctx context.Context, in *DeleteEcsReq, opts ...grpc.CallOption) (*DeleteEcsResp, error)
// 修改ECS
UpdateEcs(ctx context.Context, in *UpdateEcsReq, opts ...grpc.CallOption) (*UpdateEcsResp, error)
// 查询ECS明细 - 支持云类型、区域、账户、分页等过滤条件
ListEcsDetail(ctx context.Context, in *ListDetailReq, opts ...grpc.CallOption) (*ListDetailResp, error)
// 查询ECS全量 - 根据云类型
ListEcs(ctx context.Context, in *ListReq, opts ...grpc.CallOption) (*ListResp, error)
// 查询所有云的ECS
ListEcsAll(ctx context.Context, in *ListAllReq, opts ...grpc.CallOption) (*ListResp, error)
// 操作ecs(start-stop-restart)
ActionEcs(ctx context.Context, in *ActionReq, opts ...grpc.CallOption) (*ActionResp, error)
// 查询ecs镜像
ListEcsImages(ctx context.Context, in *ListImagesReq, opts ...grpc.CallOption) (*ListImagesResp, error)
}
type ecsServiceClient struct {
cc grpc.ClientConnInterface
}
func NewEcsServiceClient(cc grpc.ClientConnInterface) EcsServiceClient {
return &ecsServiceClient{cc}
}
func (c *ecsServiceClient) CreateMultipleEcs(ctx context.Context, in *CreateEcsMultipleReq, opts ...grpc.CallOption) (*CreateEcsMultipleResp, error) {
out := new(CreateEcsMultipleResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/CreateMultipleEcs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) CreateEcs(ctx context.Context, in *CreateEcsReq, opts ...grpc.CallOption) (*CreateEcsResp, error) {
out := new(CreateEcsResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/CreateEcs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) DeleteEcs(ctx context.Context, in *DeleteEcsReq, opts ...grpc.CallOption) (*DeleteEcsResp, error) {
out := new(DeleteEcsResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/DeleteEcs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) UpdateEcs(ctx context.Context, in *UpdateEcsReq, opts ...grpc.CallOption) (*UpdateEcsResp, error) {
out := new(UpdateEcsResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/UpdateEcs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) ListEcsDetail(ctx context.Context, in *ListDetailReq, opts ...grpc.CallOption) (*ListDetailResp, error) {
out := new(ListDetailResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/ListEcsDetail", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) ListEcs(ctx context.Context, in *ListReq, opts ...grpc.CallOption) (*ListResp, error) {
out := new(ListResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/ListEcs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) ListEcsAll(ctx context.Context, in *ListAllReq, opts ...grpc.CallOption) (*ListResp, error) {
out := new(ListResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/ListEcsAll", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) ActionEcs(ctx context.Context, in *ActionReq, opts ...grpc.CallOption) (*ActionResp, error) {
out := new(ActionResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/ActionEcs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ecsServiceClient) ListEcsImages(ctx context.Context, in *ListImagesReq, opts ...grpc.CallOption) (*ListImagesResp, error) {
out := new(ListImagesResp)
err := c.cc.Invoke(ctx, "/ecs.EcsService/ListEcsImages", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// EcsServiceServer is the server API for EcsService service.
// All implementations must embed UnimplementedEcsServiceServer
// for forward compatibility
type EcsServiceServer interface {
// 创建多家云ECS
CreateMultipleEcs(context.Context, *CreateEcsMultipleReq) (*CreateEcsMultipleResp, error)
// 创建ECS
CreateEcs(context.Context, *CreateEcsReq) (*CreateEcsResp, error)
// 删除ECS
DeleteEcs(context.Context, *DeleteEcsReq) (*DeleteEcsResp, error)
// 修改ECS
UpdateEcs(context.Context, *UpdateEcsReq) (*UpdateEcsResp, error)
// 查询ECS明细 - 支持云类型、区域、账户、分页等过滤条件
ListEcsDetail(context.Context, *ListDetailReq) (*ListDetailResp, error)
// 查询ECS全量 - 根据云类型
ListEcs(context.Context, *ListReq) (*ListResp, error)
// 查询所有云的ECS
ListEcsAll(context.Context, *ListAllReq) (*ListResp, error)
// 操作ecs(start-stop-restart)
ActionEcs(context.Context, *ActionReq) (*ActionResp, error)
// 查询ecs镜像
ListEcsImages(context.Context, *ListImagesReq) (*ListImagesResp, error)
mustEmbedUnimplementedEcsServiceServer()
}
// UnimplementedEcsServiceServer must be embedded to have forward compatible implementations.
type UnimplementedEcsServiceServer struct {
}
func (UnimplementedEcsServiceServer) CreateMultipleEcs(context.Context, *CreateEcsMultipleReq) (*CreateEcsMultipleResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreateMultipleEcs not implemented")
}
func (UnimplementedEcsServiceServer) CreateEcs(context.Context, *CreateEcsReq) (*CreateEcsResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreateEcs not implemented")
}
func (UnimplementedEcsServiceServer) DeleteEcs(context.Context, *DeleteEcsReq) (*DeleteEcsResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method DeleteEcs not implemented")
}
func (UnimplementedEcsServiceServer) UpdateEcs(context.Context, *UpdateEcsReq) (*UpdateEcsResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method UpdateEcs not implemented")
}
func (UnimplementedEcsServiceServer) ListEcsDetail(context.Context, *ListDetailReq) (*ListDetailResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListEcsDetail not implemented")
}
func (UnimplementedEcsServiceServer) ListEcs(context.Context, *ListReq) (*ListResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListEcs not implemented")
}
func (UnimplementedEcsServiceServer) ListEcsAll(context.Context, *ListAllReq) (*ListResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListEcsAll not implemented")
}
func (UnimplementedEcsServiceServer) ActionEcs(context.Context, *ActionReq) (*ActionResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ActionEcs not implemented")
}
func (UnimplementedEcsServiceServer) ListEcsImages(context.Context, *ListImagesReq) (*ListImagesResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListEcsImages not implemented")
}
func (UnimplementedEcsServiceServer) mustEmbedUnimplementedEcsServiceServer() {}
// UnsafeEcsServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to EcsServiceServer will
// result in compilation errors.
type UnsafeEcsServiceServer interface {
mustEmbedUnimplementedEcsServiceServer()
}
func RegisterEcsServiceServer(s grpc.ServiceRegistrar, srv EcsServiceServer) {
s.RegisterService(&EcsService_ServiceDesc, srv)
}
func _EcsService_CreateMultipleEcs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateEcsMultipleReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).CreateMultipleEcs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/CreateMultipleEcs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).CreateMultipleEcs(ctx, req.(*CreateEcsMultipleReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_CreateEcs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateEcsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).CreateEcs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/CreateEcs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).CreateEcs(ctx, req.(*CreateEcsReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_DeleteEcs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteEcsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).DeleteEcs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/DeleteEcs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).DeleteEcs(ctx, req.(*DeleteEcsReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_UpdateEcs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateEcsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).UpdateEcs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/UpdateEcs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).UpdateEcs(ctx, req.(*UpdateEcsReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_ListEcsDetail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListDetailReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).ListEcsDetail(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/ListEcsDetail",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).ListEcsDetail(ctx, req.(*ListDetailReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_ListEcs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).ListEcs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/ListEcs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).ListEcs(ctx, req.(*ListReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_ListEcsAll_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListAllReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).ListEcsAll(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/ListEcsAll",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).ListEcsAll(ctx, req.(*ListAllReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_ActionEcs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ActionReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).ActionEcs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/ActionEcs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).ActionEcs(ctx, req.(*ActionReq))
}
return interceptor(ctx, in, info, handler)
}
func _EcsService_ListEcsImages_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListImagesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EcsServiceServer).ListEcsImages(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ecs.EcsService/ListEcsImages",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EcsServiceServer).ListEcsImages(ctx, req.(*ListImagesReq))
}
return interceptor(ctx, in, info, handler)
}
// EcsService_ServiceDesc is the grpc.ServiceDesc for EcsService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var EcsService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "ecs.EcsService",
HandlerType: (*EcsServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "CreateMultipleEcs",
Handler: _EcsService_CreateMultipleEcs_Handler,
},
{
MethodName: "CreateEcs",
Handler: _EcsService_CreateEcs_Handler,
},
{
MethodName: "DeleteEcs",
Handler: _EcsService_DeleteEcs_Handler,
},
{
MethodName: "UpdateEcs",
Handler: _EcsService_UpdateEcs_Handler,
},
{
MethodName: "ListEcsDetail",
Handler: _EcsService_ListEcsDetail_Handler,
},
{
MethodName: "ListEcs",
Handler: _EcsService_ListEcs_Handler,
},
{
MethodName: "ListEcsAll",
Handler: _EcsService_ListEcsAll_Handler,
},
{
MethodName: "ActionEcs",
Handler: _EcsService_ActionEcs_Handler,
},
{
MethodName: "ListEcsImages",
Handler: _EcsService_ListEcsImages_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "idl/ecs.proto",
}

View File

@ -1,578 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "idl/ecs.proto",
"version": "version not set"
},
"tags": [
{
"name": "EcsService"
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {},
"definitions": {
"ecsActionResp": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"accountName": {
"type": "string",
"title": "账户名称根据config.yaml中的配置默认为第一个配置的账户"
},
"ecses": {
"type": "array",
"items": {
"$ref": "#/definitions/ecsEcsInstance"
},
"title": "Ecs 机器集合"
},
"finished": {
"type": "boolean",
"title": "查询是否完成,如果为否-false则可以将下面三个分页参数填入到请求中继续查询"
},
"status": {
"type": "string",
"title": "vm状态"
}
}
},
"ecsActionType": {
"type": "string",
"enum": [
"start",
"stop",
"restart"
],
"default": "start",
"description": "- start: 启动\n - stop: 停止\n - restart: 重启",
"title": "虚拟机状态操作"
},
"ecsCloudProvider": {
"type": "string",
"enum": [
"ali",
"tencent",
"huawei",
"k8s",
"harvester"
],
"default": "ali",
"description": "- ali: 0 - 阿里云\n - tencent: 1 - 腾讯云\n - huawei: 2 - 华为云\n - k8s: 3 - K8S\n - harvester: 3 - Harvester",
"title": "云提供商"
},
"ecsCreateEcsMultipleResp": {
"type": "object",
"properties": {
"requestId": {
"type": "array",
"items": {
"type": "string"
},
"title": "请求ID"
},
"finished": {
"type": "boolean",
"title": "查询是否完成,如果为否-false则可以将下面三个分页参数填入到请求中继续查询"
}
},
"title": "创建多家云ECS返回值"
},
"ecsCreateEcsReq": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"accountName": {
"type": "string",
"title": "账号名称"
},
"regionId": {
"type": "integer",
"format": "int32",
"title": "地域,数据中心"
},
"imageId": {
"type": "string",
"title": "镜像id"
},
"instanceChargeType": {
"type": "string",
"title": "实例的付费方式"
},
"instanceType": {
"type": "string",
"title": "实例的资源规格"
},
"securityGroupId": {
"type": "string",
"title": "安全组id"
},
"vSwitchId": {
"type": "string",
"title": "交换机id"
},
"instanceName": {
"type": "string",
"title": "实例名称"
},
"description": {
"type": "string",
"title": "实例描述"
},
"zoneId": {
"type": "string",
"title": "可用区id"
},
"systemDisk": {
"$ref": "#/definitions/ecsSystemDisk"
},
"amount": {
"type": "integer",
"format": "int32",
"title": "创建ECS的数量"
},
"dryRun": {
"type": "string",
"title": "预检此次请求,为true时请求通过则返回 Request validation has been passed with DryRun flag set"
},
"category": {
"type": "string",
"title": "数据盘N的云盘种类。取值范围cloud_efficiency高效云盘cloud_ssdSSD云盘cloud_essdESSD云盘cloud普通云盘。"
},
"internetChargeType": {
"$ref": "#/definitions/ecsInternetChargeType"
},
"internetMaxBandwidthOut": {
"type": "integer",
"format": "int32",
"title": "公网入带宽最大值单位为Mbit/s。创建的实例如果参数InternetMaxBandwidthOut的值大于0则自动为实例分配公网IP。"
},
"vpcId": {
"type": "string",
"title": "vpc id 华为云必需"
},
"subnetId": {
"type": "string",
"title": "待创建云服务器所在的子网信息。需要指定vpcid对应VPC下已创建的子网subnet的网络IDUUID格式。华为云必需"
},
"namespace": {
"type": "string",
"title": "-------------harvester---------------\n命名空间"
},
"cpu": {
"type": "integer",
"format": "int32",
"title": "vCpu"
},
"memory": {
"type": "string",
"title": "memory"
},
"sshKey": {
"type": "string",
"title": "ssh_key"
},
"diskName": {
"type": "string",
"title": "diskName"
},
"diskType": {
"type": "string",
"title": "disk类型 disk,cd-rom"
},
"diskSize": {
"type": "string",
"title": "卷大小"
},
"bus": {
"type": "string",
"description": "bus 总线指示要模拟的磁盘设备的类型支持virtio, sata, scsi."
},
"networkName": {
"type": "string",
"title": "网络名称"
},
"networkModel": {
"type": "string",
"description": "network_model 网络模式支持e1000, e1000e, ne2k_pci, pcnet, rtl8139, virtio."
},
"network": {
"type": "string",
"title": "网络"
},
"networkType": {
"type": "string",
"title": "网络连接方法默认bridge"
},
"osType": {
"type": "string",
"title": "osType //系统类型"
},
"machineType": {
"type": "string",
"title": "machineType //机器类型 none、q35、pc"
},
"machineName": {
"type": "string",
"title": "machineName //主机名称,默认为虚拟机名称"
},
"userDataTemplate": {
"type": "string",
"title": "userDataTemplate //用户数据模板"
},
"networkDataTemplate": {
"type": "string",
"title": "networkDataTemplate //网络数据模板"
},
"vmTemplateName": {
"type": "string",
"title": "vmTemplateName //模板名称"
},
"vmTemplateVersion": {
"type": "string",
"title": "vmTemplateVersion //版本号"
}
},
"title": "创建ECS入参"
},
"ecsCreateEcsResp": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"accountName": {
"type": "string",
"title": "账户名称根据config.yaml中的配置默认为第一个配置的账户"
},
"regionId": {
"type": "integer",
"format": "int32",
"title": "区域Id参考 tenant.proto 中的各个云的区域"
},
"requestId": {
"type": "string",
"title": "请求ID"
},
"orderId": {
"type": "string",
"title": "订单id"
},
"tradePrice": {
"type": "number",
"format": "float",
"title": "订单成交价"
},
"instanceIdSets": {
"type": "array",
"items": {
"type": "string"
},
"title": "实例IDInstanceIdSet列表"
},
"finished": {
"type": "boolean",
"title": "查询是否完成,如果为否-false则可以将下面三个分页参数填入到请求中继续查询"
}
},
"title": "创建ECS返回值"
},
"ecsDeleteEcsResp": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"accountName": {
"type": "string",
"title": "账户名称根据config.yaml中的配置默认为第一个配置的账户"
},
"regionId": {
"type": "integer",
"format": "int32",
"title": "区域Id参考 tenant.proto 中的各个云的区域"
},
"requestId": {
"type": "string",
"title": "请求ID"
}
},
"title": "删除ECS返回值"
},
"ecsEcsInstance": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"accountName": {
"type": "string",
"title": "账号名称"
},
"instanceId": {
"type": "string",
"title": "实例id"
},
"instanceName": {
"type": "string",
"title": "实例名称"
},
"regionName": {
"type": "string",
"title": "地域,数据中心"
},
"publicIps": {
"type": "array",
"items": {
"type": "string"
},
"title": "公网ip"
},
"instanceType": {
"type": "string",
"title": "实例类型"
},
"cpu": {
"type": "string",
"title": "vcpu数"
},
"memory": {
"type": "string",
"title": "内存MB"
},
"description": {
"type": "string",
"title": "实例描述"
},
"status": {
"type": "string",
"title": "状态"
},
"creationTime": {
"type": "string",
"title": "创建时间ISO8601"
},
"expireTime": {
"type": "string",
"title": "过期时间"
},
"innerIps": {
"type": "array",
"items": {
"type": "string"
},
"title": "内网ip"
},
"vpcId": {
"type": "string",
"title": "vpc id"
},
"resourceGroupId": {
"type": "string",
"title": "资源组id"
},
"instanceChargeType": {
"type": "string",
"title": "收费类型"
},
"node": {
"type": "string",
"title": "-----------harvester---------\n虚拟机所在的节点"
},
"namespace": {
"type": "string",
"title": "namespace"
}
},
"title": "ECS 实例"
},
"ecsImage": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"accountName": {
"type": "string",
"title": "账户名称根据config.yaml中的配置默认为第一个配置的账户"
},
"status": {
"type": "string",
"title": "镜像状态"
},
"displayName": {
"type": "string",
"title": "镜像名称"
},
"namespace": {
"type": "string",
"title": "命名空间"
},
"id": {
"type": "string",
"title": "镜像id"
}
}
},
"ecsInternetChargeType": {
"type": "string",
"enum": [
"PayByBandwidth",
"PayByTraffic"
],
"default": "PayByBandwidth",
"description": "- PayByBandwidth: 按固定带宽计费。\n - PayByTraffic: (默认):按使用流量计费",
"title": "网络计费类型"
},
"ecsListDetailResp": {
"type": "object",
"properties": {
"ecses": {
"type": "array",
"items": {
"$ref": "#/definitions/ecsEcsInstance"
},
"title": "Ecs 机器集合"
},
"finished": {
"type": "boolean",
"title": "查询是否完成,如果为否-false则可以将下面三个分页参数填入到请求中继续查询"
},
"pageNumber": {
"type": "integer",
"format": "int32",
"title": "分页相关参数,页码"
},
"pageSize": {
"type": "integer",
"format": "int32",
"title": "分页相关参数,每页数量"
},
"nextToken": {
"type": "string",
"title": "分页相关参数下一页的token"
},
"requestId": {
"type": "string",
"title": "请求id出现问题后提供给云厂商排查问题"
}
},
"title": "查询ECS返回值"
},
"ecsListImagesResp": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"images": {
"type": "array",
"items": {
"$ref": "#/definitions/ecsImage"
},
"title": "镜像集合"
}
}
},
"ecsListResp": {
"type": "object",
"properties": {
"ecses": {
"type": "array",
"items": {
"$ref": "#/definitions/ecsEcsInstance"
},
"title": "Ecs 机器集合"
}
}
},
"ecsSystemDisk": {
"type": "object",
"properties": {
"size": {
"type": "string",
"title": "系统盘大小单位为GiB。取值范围20~500。该参数的取值必须大于或者等于max{20, ImageSize}。默认值max{40, 参数ImageId对应的镜像大小}"
},
"category": {
"type": "string",
"title": "系统盘类型。系统盘的云盘种类。取值范围cloud_efficiency高效云盘。cloud_ssdSSD云盘。cloud_essdESSD云盘。cloud普通云盘。"
},
"diskName": {
"type": "string",
"title": "系统盘名称"
},
"description": {
"type": "string",
"title": "系统盘描述"
},
"performanceLevel": {
"type": "string",
"title": "创建ESSD云盘作为系统盘使用时设置云盘的性能等级。取值范围PL0单盘最高随机读写IOPS 1万。PL1默认单盘最高随机读写IOPS 5万。PL2单盘最高随机读写IOPS 10万。PL3单盘最高随机读写IOPS 100万。"
},
"autoSnapshotPolicyId": {
"type": "string",
"title": "系统盘采用的自动快照策略ID。"
}
},
"title": "系统磁盘"
},
"ecsUpdateEcsResp": {
"type": "object",
"properties": {
"provider": {
"$ref": "#/definitions/ecsCloudProvider"
},
"accountName": {
"type": "string",
"title": "账户名称根据config.yaml中的配置默认为第一个配置的账户"
},
"regionId": {
"type": "integer",
"format": "int32",
"title": "区域Id参考 tenant.proto 中的各个云的区域"
},
"requestId": {
"type": "string",
"title": "请求ID"
}
},
"title": "更新ECS返回值"
},
"protobufAny": {
"type": "object",
"properties": {
"@type": {
"type": "string"
}
},
"additionalProperties": {}
},
"rpcStatus": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"details": {
"type": "array",
"items": {
"$ref": "#/definitions/protobufAny"
}
}
}
}
}
}

View File

@ -1,445 +0,0 @@
syntax = "proto3";
package ecs;
option go_package = "/ecspb";
//
enum CloudProvider {
// 0 -
ali = 0;
// 1 -
tencent = 1;
// 2 -
huawei = 2;
// 3 - K8S
k8s = 3;
// 3 - Harvester
harvester = 4;
}
//ECS
message EcsInstance {
//
CloudProvider provider = 1;
//
string account_name = 2;
// id
string instance_id = 3;
//
string instance_name = 4;
//
string region_name = 5;
// ip
repeated string public_ips = 6;
//
string instance_type = 7;
// vcpu数
string cpu = 8;
// MB
string memory = 9;
//
string description = 10;
//
string status = 11;
// ISO8601
string creation_time = 12;
//
string expire_time = 13;
// ip
repeated string inner_ips = 14;
// vpc id
string vpc_id = 15;
// id
string resource_group_id = 16;
//
string instance_charge_type = 17;
// -----------harvester---------
//
string node = 18;
//namespace
string namespace = 20;
}
//
enum InternetChargeType {
//
PayByBandwidth = 0;
//使
PayByTraffic = 1;
}
//ECS入参
message CreateEcsMultipleReq {
repeated CreateEcsReq createEcsReqs = 1;
}
//ECS返回值
message CreateEcsMultipleResp {
// ID
repeated string request_id = 1;
// -false
bool finished = 2;
}
//ECS入参
message CreateEcsReq {
//
CloudProvider provider = 1;
//
string account_name = 2;
//
int32 region_id = 3;
//id
string image_id = 4;
//
string instance_charge_type = 5;
//
string instance_type = 6;
// id
string security_group_id = 7;
//id
string v_switch_id = 8;
//
string instance_name = 9;
//
string description = 10;
//id
string zone_id = 11;
//
SystemDisk system_disk = 12;
//ECS的数量
int32 amount = 13;
//,true时请求通过 Request validation has been passed with DryRun flag set
string dry_run = 14;
//N的云盘种类cloud_efficiencycloud_ssdSSD云盘cloud_essdESSD云盘cloud
string category = 15;
//PayByBandwidthPayByTraffic使
InternetChargeType internet_charge_type = 16;
//Mbit/sInternetMaxBandwidthOut的值大于0IP
int32 internet_max_bandwidth_out = 17;
// vpc id
string vpc_id = 18;
//vpcid对应VPC下已创建的子网subnetIDUUID格式
string subnet_id = 19;
//-------------harvester---------------
//
string namespace = 20;
//vCpu
int32 cpu = 21;
//memory
string memory = 22;
//ssh_key
string ssh_key = 23;
//diskName
string disk_name = 24;
//disk类型 disk,cd-rom
string disk_type = 25;
//
string disk_size = 26;
//bus 线virtio, sata, scsi.
string bus = 27;
//
string network_name = 28;
//network_model e1000, e1000e, ne2k_pci, pcnet, rtl8139, virtio.
string network_model = 29;
//
string network = 30;
//bridge
string network_type = 31;
//osType //
string os_type = 32;
//machineType // noneq35pc
string machine_type = 33;
//machineName //
string machine_name = 34;
//userDataTemplate //
string user_data_template = 35;
//networkDataTemplate //
string network_data_template = 36;
//vmTemplateName //
string vm_template_name = 37;
//vmTemplateVersion //
string vm_template_version = 38;
}
//
message SystemDisk {
//GiB20~500max{20, ImageSize}max{40, ImageId对应的镜像大小}
string size = 1;
//cloud_efficiencycloud_ssdSSD云盘cloud_essdESSD云盘cloud
string category = 2;
//
string disk_name = 3;
//
string description = 4;
//ESSD云盘作为系统盘使用时PL0IOPS 1PL1IOPS 5PL2IOPS 10PL3IOPS 100
string performance_level = 5;
//ID
string auto_snapshot_policy_id = 6;
}
//ECS返回值
message CreateEcsResp {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
// ID
string request_id = 4;
// id
string order_id = 5;
//
float trade_price = 6;
//IDInstanceIdSet
repeated string instance_id_sets = 7;
// -false
bool finished = 8;
}
//ECS入参
message DeleteEcsReq {
//
CloudProvider provider = 1;
//
string account_name = 2;
//
int32 region_id = 3;
//trueAccessKey是否有效RAM用户的授权情况和是否填写了必需参数DRYRUN.SUCCESS
//false2XX HTTP状态码并直接查询资源状况
string dry_run = 4;
//Force是否强制释放****trueRunning
//falseStopped
string force = 5;
// true,false
string terminate_subscription = 6;
//ID数组以,i-8vb2nlubkow0fxbq2218,i-8vb2nlubkow0fxbq2216
string instance_ids = 7;
//IPIP资源
//true或falsefalse
string delete_publicip = 8;
//false
//true或falsefalse
string delete_volume = 9;
//----------------harvester----------------
//
string instance_name = 10;
//namespace
string namespace = 11;
//diskName,,
string disk_name = 12;
}
//ECS返回值
message DeleteEcsResp {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
// ID
string request_id = 4;
}
//ECS入参
message UpdateEcsReq {
//
CloudProvider provider = 1;
//
string account_name = 2;
//
int32 region_id = 3;
//id
string instance_ids = 4;
// StartingECS控制台重启或者调用API RebootInstance重启
string password = 5;
//
string host_name = 6;
//
string instance_name = 7;
//
string description = 8;
//ID不能重复,
string security_group_ids = 9;
//---------------harvester-----------------
//namespace
string namespace = 10;
//cpu
string cpu = 11;
//memory
string memory = 12;
//
bool is_restart = 13;
}
//ECS返回值
message UpdateEcsResp {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
// ID
string request_id = 4;
}
//ECS入参
message ListDetailReq {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
//
int32 page_number = 4;
//
int32 page_size = 5;
// token
string next_token = 6;
//--------harvester---------
//namespace
string namespace = 7;
}
//ECS返回值
message ListDetailResp {
// Ecs
repeated EcsInstance ecses = 1;
// -false
bool finished = 2;
//
int32 page_number = 3;
//
int32 page_size = 4;
// token
string next_token = 5;
// id
string request_id = 6;
}
//
enum ActionType {
//
start = 0;
//
stop = 1;
//
restart = 2;
}
message ActionReq {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
//
string namespace = 4;
//
string vm_name = 5 ;
//
ActionType action_type = 6 ;
}
message ActionResp {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Ecs
repeated EcsInstance ecses = 3;
// -false
bool finished = 4;
//vm状态
string status = 5;
}
message ListReq {
//
CloudProvider provider = 1;
}
message ListResp {
// Ecs
repeated EcsInstance ecses = 1;
}
message ListAllReq{}
message ListImagesReq {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
//
string namespace= 4;
//
int32 page_number = 5;
//
int32 page_size = 6;
}
message Image {
//
CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
//
string status = 3 ;
//
string display_name= 4;
//
string namespace= 5;
//id
string id= 6;
}
message ListImagesResp {
//
CloudProvider provider = 1;
//
repeated Image images = 2;
}
// ECS类产品接口
// - ECS
// - CVM
// - ECS
// - EC2
service EcsService {
// ECS
rpc CreateMultipleEcs(CreateEcsMultipleReq) returns (CreateEcsMultipleResp);
// ECS
rpc CreateEcs(CreateEcsReq) returns (CreateEcsResp);
// ECS
rpc DeleteEcs(DeleteEcsReq) returns (DeleteEcsResp);
// ECS
rpc UpdateEcs(UpdateEcsReq) returns (UpdateEcsResp);
// ECS明细 -
rpc ListEcsDetail(ListDetailReq) returns (ListDetailResp);
// ECS全量 -
rpc ListEcs(ListReq) returns (ListResp);
// ECS
rpc ListEcsAll(ListAllReq) returns (ListResp);
//ecs(start-stop-restart)
rpc ActionEcs(ActionReq) returns (ActionResp);
//ecs镜像
rpc ListEcsImages(ListImagesReq) returns (ListImagesResp);
}

View File

@ -1,28 +0,0 @@
type: google.api.Service
config_version: 3
http:
rules:
- selector: ecs.EcsService.CreateMultipleEcs
post: "/apis/ecs/createMultiple"
body: "*"
- selector: ecs.EcsService.CreateEcs
post: "/apis/ecs/create"
body: "*"
- selector: ecs.EcsService.DeleteEcs
post: "/apis/ecs/delete"
body: "*"
- selector: ecs.EcsService.UpdateEcs
put: "/apis/ecs/update"
body: "*"
- selector: ecs.EcsService.ListEcsDetail
get: "/apis/ecs/detail"
- selector: ecs.EcsService.ListEcs
get: "/apis/ecs"
- selector: ecs.EcsService.ListEcsAll
get: "/apis/ecs/all"
- selector: ecs.EcsService.ActionEcs
post: "/apis/ecs/action"
body: "*"
- selector: ecs.EcsService.ListEcsImages
get: "/apis/ecs/listImages"

View File

@ -1,56 +0,0 @@
package main
import (
vmpb "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_vm/gen/idl"
vmserver "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_vm/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/config"
"code.gitlink.org.cn/JCCE/PCM.git/common/global"
"code.gitlink.org.cn/JCCE/PCM.git/common/server"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
"flag"
"github.com/golang/glog"
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/grpc"
"log"
)
func main() {
var configFile string
flag.StringVar(&configFile, "conf", "configs/tenanter.yaml", "tenanter.yaml")
flag.Parse()
defer glog.Flush()
if err := tenanter.LoadCloudConfigsFromFile(configFile); err != nil {
if !errors.Is(err, tenanter.ErrLoadTenanterFileEmpty) {
glog.Fatalf("LoadCloudConfigsFromFile error %+v", err)
}
glog.Warningf("LoadCloudConfigsFromFile empty file path %s", configFile)
}
// 初始化配置以及数据库
config.InitConfig()
// 新建一个zap logger实例
logger, err := zap.NewDevelopment()
if err != nil {
log.Fatalf("cannot create logger: %v", err)
}
if err != nil {
logger.Fatal("cannot open private key", zap.Error(err))
}
if err != nil {
logger.Fatal("cannot read private key", zap.Error(err))
}
if err != nil {
logger.Fatal("cannot parse private key", zap.Error(err))
}
// logger.Sugar().Fatal 直接可以少几行判错的代码
logger.Sugar().Fatal(server.RunGRPCServer(&server.GRPCConfig{
Name: "pcm_vm",
Addr: global.S.VmInfo.Address,
RegisterFunc: func(g *grpc.Server) {
vmpb.RegisterEcsServiceServer(g, &vmserver.Server{})
},
Logger: logger,
}))
}

View File

@ -1,103 +0,0 @@
package server
import (
"code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_vm/gen/idl"
"context"
"github.com/golang/glog"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Server struct {
ecspb.UnimplementedEcsServiceServer
}
// CreateMultipleEcs return create cloudy ecs
func (s *Server) CreateMultipleEcs(ctx context.Context, reqs *ecspb.CreateEcsMultipleReq) (*ecspb.CreateEcsMultipleResp, error) {
resp, err := CreateMultipleEcs(ctx, reqs)
if err != nil {
glog.Errorf("ListEcsDetail error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// CreateEcs return create ecs
func (s *Server) CreateEcs(ctx context.Context, req *ecspb.CreateEcsReq) (*ecspb.CreateEcsResp, error) {
resp, err := CreateEcs(ctx, req)
if err != nil {
glog.Errorf("ListEcsDetail error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// DeleteEcs return Delete ecs
func (s *Server) DeleteEcs(ctx context.Context, req *ecspb.DeleteEcsReq) (*ecspb.DeleteEcsResp, error) {
resp, err := DeleteEcs(ctx, req)
if err != nil {
glog.Errorf("ListEcsDetail error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// UpdateEcs return Update ecs
func (s *Server) UpdateEcs(ctx context.Context, req *ecspb.UpdateEcsReq) (*ecspb.UpdateEcsResp, error) {
resp, err := UpdateEcs(ctx, req)
if err != nil {
glog.Errorf("ListEcsDetail error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListEcsDetail return ecs detail
func (s *Server) ListEcsDetail(ctx context.Context, req *ecspb.ListDetailReq) (*ecspb.ListDetailResp, error) {
resp, err := ListDetail(ctx, req)
if err != nil {
glog.Errorf("ListEcsDetail error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListEcs return ecs list
func (s *Server) ListEcs(ctx context.Context, req *ecspb.ListReq) (*ecspb.ListResp, error) {
resp, err := List(ctx, req)
if err != nil {
glog.Errorf("ListEcs error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListEcsAll return all ecs
func (s *Server) ListEcsAll(ctx context.Context, req *ecspb.ListAllReq) (*ecspb.ListResp, error) {
resp, err := ListAll(ctx)
if err != nil {
glog.Errorf("ListEcsAll error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ActionEcs return ecs action
func (s *Server) ActionEcs(ctx context.Context, req *ecspb.ActionReq) (*ecspb.ActionResp, error) {
resp, err := ActionEcs(ctx, req)
if err != nil {
glog.Errorf("ActionEcs error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}
// ListEcsImages return ecs image list
func (s *Server) ListEcsImages(ctx context.Context, req *ecspb.ListImagesReq) (*ecspb.ListImagesResp, error) {
resp, err := ListImages(ctx, req)
if err != nil {
glog.Errorf("ListImages error %+v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
return resp, nil
}

View File

@ -1,264 +0,0 @@
package server
import (
pbecs "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_vm/gen/idl"
ecser "code.gitlink.org.cn/JCCE/PCM.git/adaptor/pcm_vm/service"
"code.gitlink.org.cn/JCCE/PCM.git/common/tenanter"
pbtenant "code.gitlink.org.cn/JCCE/PCM.git/tenant/gen/idl"
"context"
"sync"
"github.com/golang/glog"
"github.com/pkg/errors"
)
// CreateMultipleEcs 创建多云ECS
func CreateMultipleEcs(ctx context.Context, reqs *pbecs.CreateEcsMultipleReq) (*pbecs.CreateEcsMultipleResp, error) {
var (
wg sync.WaitGroup
requestIds = make([]string, 0)
)
wg.Add(len(reqs.GetCreateEcsReqs()))
c := make(chan string, len(reqs.GetCreateEcsReqs()))
for _, k := range reqs.GetCreateEcsReqs() {
k := k
go func() {
defer wg.Done()
resp, err := CreateEcs(ctx, k)
if err != nil {
glog.Errorf(k.Provider.String()+"CreateEcs error: %v", err)
c <- k.Provider.String()
return
}
c <- resp.GetRequestId()
}()
}
go func() {
defer close(c)
wg.Wait()
}()
for v := range c {
requestIds = append(requestIds, v)
}
isFinished := false
if len(requestIds) > 0 {
isFinished = true
}
return &pbecs.CreateEcsMultipleResp{
RequestId: requestIds,
Finished: isFinished,
}, nil
}
func CreateEcs(ctx context.Context, req *pbecs.CreateEcsReq) (*pbecs.CreateEcsResp, error) {
var (
ecs ecser.Ecser
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.Wrap(err, "get tenanters failed")
}
for _, tenanter := range tenanters {
if req.AccountName == "" || tenanter.AccountName() == req.AccountName {
if ecs, err = ecser.NewEcsClient(req.Provider, region, tenanter); err != nil {
return nil, errors.WithMessage(err, "NewEcsClient error")
}
break
}
}
return ecs.CreateEcs(ctx, req)
}
func DeleteEcs(ctx context.Context, req *pbecs.DeleteEcsReq) (*pbecs.DeleteEcsResp, error) {
var (
ecs ecser.Ecser
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.Wrap(err, "get tenanters failed")
}
for _, tenanter := range tenanters {
if req.AccountName == "" || tenanter.AccountName() == req.AccountName {
if ecs, err = ecser.NewEcsClient(req.Provider, region, tenanter); err != nil {
return nil, errors.WithMessage(err, "NewEcsClient error")
}
break
}
}
return ecs.DeleteEcs(ctx, req)
}
func UpdateEcs(ctx context.Context, req *pbecs.UpdateEcsReq) (*pbecs.UpdateEcsResp, error) {
var (
ecs ecser.Ecser
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.Wrap(err, "get tenanters failed")
}
for _, tenanter := range tenanters {
if req.AccountName == "" || tenanter.AccountName() == req.AccountName {
if ecs, err = ecser.NewEcsClient(req.Provider, region, tenanter); err != nil {
return nil, errors.WithMessage(err, "NewEcsClient error")
}
break
}
}
return ecs.UpdateEcs(ctx, req)
}
// ListDetail returns the detail of ecs instances
func ListDetail(ctx context.Context, req *pbecs.ListDetailReq) (*pbecs.ListDetailResp, error) {
var (
ecs ecser.Ecser
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
if err != nil {
return nil, errors.WithMessage(err, "getTenanters error")
}
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.WithMessagef(err, "provider %v regionId %v", req.Provider, req.RegionId)
}
for _, tenanter := range tenanters {
if req.AccountName == "" || tenanter.AccountName() == req.AccountName {
if ecs, err = ecser.NewEcsClient(req.Provider, region, tenanter); err != nil {
return nil, errors.WithMessage(err, "NewEcsClient error")
}
break
}
}
return ecs.ListDetail(ctx, req)
}
// List returns the list of ecs instances
func List(ctx context.Context, req *pbecs.ListReq) (*pbecs.ListResp, error) {
var (
wg sync.WaitGroup
mutex sync.Mutex
ecses []*pbecs.EcsInstance
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
if err != nil {
return nil, errors.WithMessage(err, "getTenanters error")
}
regions := tenanter.GetAllRegionIds(pbtenant.CloudProvider(req.Provider))
wg.Add(len(tenanters) * len(regions))
for _, t := range tenanters {
for _, region := range regions {
go func(tenant tenanter.Tenanter, region tenanter.Region) {
defer wg.Done()
ecs, err := ecser.NewEcsClient(req.Provider, region, tenant)
if err != nil {
glog.Errorf("New Ecs Client error %v", err)
return
}
request := &pbecs.ListDetailReq{
Provider: req.Provider,
AccountName: tenant.AccountName(),
RegionId: region.GetId(),
PageNumber: 1,
PageSize: 100,
NextToken: "",
}
for {
resp, err := ecs.ListDetail(ctx, request)
if err != nil {
glog.Errorf("ListDetail error %v", err)
return
}
mutex.Lock()
ecses = append(ecses, resp.Ecses...)
mutex.Unlock()
if resp.Finished {
break
}
request.PageNumber, request.PageSize, request.NextToken = resp.PageNumber, resp.PageSize, resp.NextToken
}
}(t, region)
}
}
wg.Wait()
return &pbecs.ListResp{Ecses: ecses}, nil
}
// ListAll returns all ecs instances
func ListAll(ctx context.Context) (*pbecs.ListResp, error) {
var (
wg sync.WaitGroup
mutex sync.Mutex
ecses []*pbecs.EcsInstance
)
wg.Add(len(pbecs.CloudProvider_name))
for k := range pbecs.CloudProvider_name {
go func(provider int32) {
defer wg.Done()
resp, err := List(ctx, &pbecs.ListReq{Provider: pbecs.CloudProvider(provider)})
if err != nil {
glog.Errorf("List error %v", err)
return
}
mutex.Lock()
ecses = append(ecses, resp.Ecses...)
mutex.Unlock()
}(k)
}
wg.Wait()
return &pbecs.ListResp{Ecses: ecses}, nil
}
func ActionEcs(ctx context.Context, req *pbecs.ActionReq) (*pbecs.ActionResp, error) {
var (
ecs ecser.Ecser
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.Wrap(err, "get tenanters failed")
}
for _, tenanter := range tenanters {
if req.AccountName == "" || tenanter.AccountName() == req.AccountName {
if ecs, err = ecser.NewEcsClient(req.Provider, region, tenanter); err != nil {
return nil, errors.WithMessage(err, "NewEcsClient error")
}
break
}
}
return ecs.ActionEcs(ctx, req)
}
func ListImages(ctx context.Context, req *pbecs.ListImagesReq) (*pbecs.ListImagesResp, error) {
var (
ecs ecser.Ecser
)
tenanters, err := tenanter.GetTenanters(pbtenant.CloudProvider(req.Provider))
region, err := tenanter.NewRegion(pbtenant.CloudProvider(req.Provider), req.RegionId)
if err != nil {
return nil, errors.Wrap(err, "get tenanters failed")
}
for _, tenanter := range tenanters {
if req.AccountName == "" || tenanter.AccountName() == req.AccountName {
if ecs, err = ecser.NewEcsClient(req.Provider, region, tenanter); err != nil {
return nil, errors.WithMessage(err, "NewEcsClient error")
}
break
}
}
return ecs.ListEcsImages(ctx, req)
}

Some files were not shown because too many files have changed in this diff Show More