Commit f9adc9ec authored by lujianqiang's avatar lujianqiang

fe_futuredge source directory

parent cc5e3732
......@@ -33,13 +33,27 @@ git checkout master
OpenXG-OTCloud
├── fe_kubesphere : Customized container platform for cloud, data center and edge management
├── fe_console : Micro cloud, dashboard, web interface, etc
├── fe_futuredge : , etc
└── fe_install : Online deployment tool
```
## Install dependencies
## Prepare the environment
OpenXG-otcloud relies on some third-party software or libraries, please install the dependencies when you first build the project, run by:
```
cp -rf fe_futuredge fe_kubesphere/pkg/kapis
```
## Build kubesphere
```
cd fe_kubesphere
bash -x build.sh
```
## Build console
```
cd fe_console
bash -x build.sh
```
package futuredge
import (
"fmt"
"kubesphere.io/api/application/v1alpha1"
tenantv1alpha2 "kubesphere.io/api/tenant/v1alpha2"
"kubesphere.io/kubesphere/pkg/models/openpitrix"
)
func (h *Handler) ValidateRepo(u string, request *v1alpha1.HelmRepoCredential) (*openpitrix.ValidateRepoResponse, error) {
repo, err := h.Openpitrix.ValidateRepo(u, request)
return repo, err
}
func (h *Handler) CreateRepo(repo *v1alpha1.HelmRepo) (*openpitrix.CreateRepoResponse, error) {
createRepo, err := h.Openpitrix.CreateRepo(repo)
return createRepo, err
}
//2. 定义一个handler的方法
func (h *Handler) Dosomething() {
//主要为了实现接口,去掉循环依赖
fmt.Println("")
}
func (h *Handler) CreateWorkspace(workspace *tenantv1alpha2.WorkspaceTemplate) (*tenantv1alpha2.WorkspaceTemplate, error) {
return h.tenant.CreateWorkspace(workspace)
}
{
"apiVersion":"tenant.kubesphere.io/v1alpha2",
"kind":"WorkspaceTemplate",
"metadata":{
"name":"tc-chartmuseum-repo",
"annotations":{
"kubesphere.io/alias-name":"tc-chartmuseum-repo",
"kubesphere.io/description":"默认的私有仓库",
"kubesphere.io/creator":"admin"
}
},
"spec":{
"template":{
"spec":{
"manager":"admin"
}
}
}
}
This diff is collapsed.
package dao
type MyConn struct {
//放指针
}
var MC MyConn
package futureinterface
import (
"fmt"
futuredge "kubesphere.io/kubesphere/pkg/kapis/futuredge/v1alpha1"
)
type FutureInterface struct {
Handler *futuredge.Handler
}
func (f *FutureInterface) Dosomething() {
fmt.Println("打印A")
}
func (f *FutureInterface) GetHandler() *futuredge.Handler {
f.Handler = futuredge.Myhandler
return f.Handler
}
package futuredge
import (
"encoding/json"
"errors"
"fmt"
"github.com/emicklei/go-restful"
restfulspec "github.com/emicklei/go-restful-openapi"
"github.com/go-openapi/loads"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"io/ioutil"
urlruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/apiserver/authorization/authorizer"
"kubesphere.io/kubesphere/pkg/apiserver/runtime"
"kubesphere.io/kubesphere/pkg/client/clientset/versioned"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/informers"
"kubesphere.io/kubesphere/pkg/models/iam/am"
"kubesphere.io/kubesphere/pkg/simple/client/auditing"
"kubesphere.io/kubesphere/pkg/simple/client/events"
"kubesphere.io/kubesphere/pkg/simple/client/logging"
monitoringclient "kubesphere.io/kubesphere/pkg/simple/client/monitoring"
openpitrixoptions "kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"kubesphere.io/kubesphere/pkg/version"
"log"
"sigs.k8s.io/controller-runtime/pkg/cache"
)
type SwaggerInfo struct {
ksInformers informers.InformerFactory
option *openpitrixoptions.Options
verclient versioned.Interface
k8sclient kubernetes.Interface
evtsClient events.Client
loggingClient logging.Client
auditingclient auditing.Client
am am.AccessManagementInterface
authorizer authorizer.Authorizer
monitoringclient monitoringclient.Interface
//resourceGetter *resourcev1alpha3.ResourceGetter
cache cache.Cache
//container *restful.Container
}
var Swagger = &SwaggerInfo{}
func (h *Handler) handlerGenerateSwagger(req *restful.Request, resp *restful.Response) {
swaggerSpec := generateSwaggerJSON()
err := validateSpec(swaggerSpec)
if err != nil {
klog.Warningf("Swagger specification has errors")
}
_, err = resp.Write(swaggerSpec)
if err != nil {
klog.Errorf("handlerGenerateSwagger write failed %v", err)
}
}
func giveswagger(factory informers.InformerFactory, options *openpitrixoptions.Options, verclient versioned.Interface, k8sclient kubernetes.Interface,
evtsClient events.Client, loggingClient logging.Client,
auditingclient auditing.Client, am am.AccessManagementInterface, authorizer authorizer.Authorizer,
monitoringclient monitoringclient.Interface, cache cache.Cache) *SwaggerInfo {
Swagger.ksInformers = factory
Swagger.option = options
Swagger.verclient = verclient
Swagger.k8sclient = k8sclient
Swagger.evtsClient = evtsClient
Swagger.loggingClient = loggingClient
Swagger.auditingclient = auditingclient
Swagger.am = am
Swagger.authorizer = authorizer
Swagger.monitoringclient = monitoringclient
Swagger.cache = cache
return Swagger
}
func validateSpec(apiSpec []byte) error {
swaggerDoc, err := loads.Analyzed(apiSpec, "")
if err != nil {
return err
}
// Attempts to report about all errors
validate.SetContinueOnErrors(true)
v := validate.NewSpecValidator(swaggerDoc.Schema(), strfmt.Default)
result, _ := v.Validate(swaggerDoc)
if result.HasWarnings() {
log.Printf("See warnings below:\n")
for _, desc := range result.Warnings {
log.Printf("- WARNING: %s\n", desc.Error())
}
}
if result.HasErrors() {
str := fmt.Sprintf("The swagger spec is invalid against swagger specification %s.\nSee errors below:\n", swaggerDoc.Version())
for _, desc := range result.Errors {
str += fmt.Sprintf("- %s\n", desc.Error())
}
log.Println(str)
return errors.New(str)
}
return nil
}
func generateSwaggerJSON() []byte {
contianer := runtime.Container
urlruntime.Must(AddToContainer(contianer, Swagger.ksInformers, Swagger.option,
Swagger.verclient, Swagger.k8sclient,
Swagger.evtsClient, Swagger.loggingClient, Swagger.auditingclient,
Swagger.am, Swagger.authorizer, Swagger.monitoringclient, Swagger.cache))
defer func(contianer *restful.Container, ws *restful.WebService) {
_ = contianer.Remove(ws)
}(contianer, contianer.RegisteredWebServices()[0])
config := restfulspec.Config{
WebServices: contianer.RegisteredWebServices(),
PostBuildSwaggerObjectHandler: enrichSwaggerObject}
swagger := restfulspec.BuildSwagger(config)
swagger.Info.Extensions = make(spec.Extensions)
swagger.Info.Extensions.Add("x-tagGroups", []struct {
Name string `json:"name"`
Tags []string `json:"tags"`
}{
{
Name: "Authentication",
Tags: []string{constants.AuthenticationTag},
},
{
Name: "Identity Management",
Tags: []string{
constants.UserTag,
},
},
{
Name: "Access Management",
Tags: []string{
constants.ClusterMemberTag,
constants.WorkspaceMemberTag,
constants.DevOpsProjectMemberTag,
constants.NamespaceMemberTag,
constants.GlobalRoleTag,
constants.ClusterRoleTag,
constants.WorkspaceRoleTag,
constants.DevOpsProjectRoleTag,
constants.NamespaceRoleTag,
},
},
{
Name: "Multi-tenancy",
Tags: []string{
constants.WorkspaceTag,
constants.NamespaceTag,
constants.UserResourceTag,
},
},
{
Name: "Multi-cluster",
Tags: []string{
constants.MultiClusterTag,
},
},
{
Name: "Resources",
Tags: []string{
constants.ClusterResourcesTag,
constants.NamespaceResourcesTag,
},
},
{
Name: "App Store",
Tags: []string{
constants.OpenpitrixAppInstanceTag,
constants.OpenpitrixAppTemplateTag,
constants.OpenpitrixCategoryTag,
constants.OpenpitrixAttachmentTag,
constants.OpenpitrixRepositoryTag,
constants.OpenpitrixManagementTag,
},
},
{
Name: "Other",
Tags: []string{
constants.RegistryTag,
constants.GitTag,
constants.ToolboxTag,
constants.TerminalTag,
},
},
{
Name: "DevOps",
Tags: []string{
constants.DevOpsProjectTag,
constants.DevOpsCredentialTag,
constants.DevOpsPipelineTag,
constants.DevOpsProjectMemberTag,
constants.DevOpsWebhookTag,
constants.DevOpsJenkinsfileTag,
constants.DevOpsScmTag,
constants.DevOpsJenkinsTag,
},
},
{
Name: "Monitoring",
Tags: []string{
constants.ClusterMetricsTag,
constants.NodeMetricsTag,
constants.NamespaceMetricsTag,
constants.WorkloadMetricsTag,
constants.PodMetricsTag,
constants.ContainerMetricsTag,
constants.WorkspaceMetricsTag,
constants.ComponentMetricsTag,
constants.ComponentStatusTag,
},
},
{
Name: "Logging",
Tags: []string{constants.LogQueryTag},
},
{
Name: "Events",
Tags: []string{constants.EventsQueryTag},
},
{
Name: "Auditing",
Tags: []string{constants.AuditingQueryTag},
},
{
Name: "Network",
Tags: []string{constants.NetworkTopologyTag},
},
})
data, _ := json.MarshalIndent(swagger, "", " ")
err := ioutil.WriteFile("/root/swagger.json", data, 0420)
if err != nil {
log.Println(err.Error())
}
log.Printf("successfully written to %s", "/root/swagger.json")
return data
}
func enrichSwaggerObject(swo *spec.Swagger) {
swo.Info = &spec.Info{
InfoProps: spec.InfoProps{
Title: "KubeSphere",
Description: "KubeSphere OpenAPI",
Version: version.Get().GitVersion,
Contact: &spec.ContactInfo{
ContactInfoProps: spec.ContactInfoProps{
Name: "KubeSphere",
URL: "https://kubesphere.io/",
Email: "kubesphere@yunify.com",
},
},
License: &spec.License{
LicenseProps: spec.LicenseProps{
Name: "Apache 2.0",
URL: "https://www.apache.org/licenses/LICENSE-2.0.html",
},
},
},
}
// setup security definitions
swo.SecurityDefinitions = map[string]*spec.SecurityScheme{
"jwt": spec.APIKeyAuth("Authorization", "header"),
}
swo.Security = []map[string][]string{{"jwt": []string{}}}
}
This diff is collapsed.
package models
import (
"github.com/go-openapi/strfmt"
)
type Shadow struct {
Instances []ShadowInstance `json:"instances"`
Ippools []HelmIPPool `json:"ippools"`
ChartPath string `json:"chart_path"`
ChartNode string `json:"chart_node"`
Conf string `json:"conf"`
}
type ShadowInstance struct {
Instance string `json:"name"`
Hostname string `json:"hostname"`
Nic []string `json:"nic"`
ExclusiveCpus string `json:"exclusive_cpus"`
Resources Resource `json:"resources"`
NumaNode string `json:"numa_node"`
HelmSriovInfo HelmSriov `json:"helmsriovinfo"`
}
type Resource struct {
Limits Limit `json:"limits"`
}
type Limit struct {
Memory string `json:"memory"`
Hugepages2mi string `json:"hugepages_2Mi"`
Hugepages1g string `json:"hugepages_1G"`
}
type HelmShadowResult struct {
Status int `json:"status"`
Message string `json:"message"`
Content string `json:"content"`
}
type ValidatePackageRequest struct {
// required, version package eg.[the wordpress-0.0.1.tgz will be encoded to bytes]
VersionPackage strfmt.Base64 `json:"version_package,omitempty"`
// optional, vmbased/helm
VersionType string `json:"version_type,omitempty"`
}
type ValidatePackageResponse struct {
Filename string `json:"filename,omitempty"`
Error string `json:"error,omitempty"`
ErrorDetails map[string]string `json:"error_details,omitempty"`
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Description string `json:"description,omitempty"`
VersionName string `json:"version_name,omitempty"`
}
type ChartVerifyPushResp struct {
Status int `json:"status"`
Message string `json:"message,omitempty"`
FileExist bool `json:"fileExist,omitempty"`
FileFalied bool `json:"filefalied,omitempty"`
Validate []ValidatePackageResponse `json:"validate,omitempty"`
}
package models
//前端交互数据结构
type ImageNameList struct {
Items []ImageName `json:"items"`
TotalItems int `json:"totalItems"`
}
type ImageName struct {
Name string `json:"name"`
}
type ImageJSON struct {
ImageTag string `json:"imagetag,omitempty"`
}
type ImageTagJSON struct {
ImageTagList []ImageJSON `json:"image_list"`
}
type ImageDeleteResp struct {
Status int `json:"status"`
}
type ImagePushResp struct {
Status int `json:"status"`
Message string `json:"message"`
}
type ImageVerifyPushResp struct {
Status int `json:"status"`
Message string `json:"message"`
SignatureMessage string `json:"signatureMessage,omitempty"`
ImageMessage string `json:"imageMessage,omitempty"`
}
package models
type FPGAListResponse struct {
FPGAList []FPGAResponse `json:"FPGAList"`
}
type FPGAResponse struct {
Bdf string `json:"BDF"`
ProductName string `json:"productName"`
Vendor string `json:"vendor"`
NUMANode string `json:"NUMANode"`
Speed string `json:"speed"`
Width string `json:"width"`
Driver string `json:"driver"`
Version string `json:"version"`
AntSpeed string `json:"antSpeed"`
CellType string `json:"cellType"`
AntInfo string `json:"antInfo"`
}
package models
type PubringListResp struct {
Items []PubringResp `json:"items"`
TotalItems int `json:"totalItems"`
}
type PubringResp struct {
Type string `json:"type"`
Trust string `json:"trust"`
Length string `json:"length"`
Algo string `json:"algo"`
KeyID string `json:"keyid"`
Date string `json:"date"`
Expires string `json:"expires"`
Dummy string `json:"dummy"`
Ownertrust string `json:"ownertrust"`
Uids []string `json:"uids"`
Subkeys [][]string `json:"subkeys"`
Fingerprint string `json:"fingerprint"`
}
type PubringListResult struct {
Items []Pubring `json:"items"`
TotalItems int `json:"totalItems"`
}
type Pubring struct {
Name string `json:"name"`
ID string `json:"id"`
Expire string `json:"expire"`
Fingerprint string `json:"fingerprint"`
}
type UploadFile struct {
Key string `json:"key"`
}
type Result struct {
Status int `json:"status"`
Message string `json:"message"`
}
type VerifyResult struct {
GoodSignature bool `json:"GoodSignature"`
Message string `json:"message"`
}
package models
type GpuListResponse struct {
GpuList []GpuResponse `json:"GpuList"`
}
type GpuResponse struct {
Bdf string `json:"BDF"`
ProductName string `json:"productName"`
Vendor string `json:"vendor"`
NUMANode string `json:"NUMANode"`
Speed string `json:"speed"`
Width string `json:"width"`
UUID string `json:"UUID"`
PodName string `json:"podName"`
PodNameSpace string `json:"podNameSpace"`
}
package models
import (
"time"
)
type HelmInfo struct {
HelmRepo
Status int `json:"status,omitempty"`
}
type ValidateRepoResponse struct {
// if validate error,return error code
ErrorCode int64 `json:"errorCode,omitempty"`
// validate repository ok or not
Ok bool `json:"ok,omitempty"`
}
type CreateRepoResponse struct {
// id of repository created
RepoID string `json:"repo_id,omitempty"`
}
type HelmRepo struct {
Name string
URL string
}
type HelmRepoSearch struct {
ChartName string
ChartVersion string
AppVersion string
Descripton string
}
type HistroyChart struct {
HistoryList []HelmRepoSearch
}
type HelmCategory struct {
CategoryID string `json:"category_id"`
CreateTime time.Time `json:"create_time"`
Locale string `json:"locale"`
Name string `json:"name"`
Status string `json:"status"`
}
type HelmApp struct {
AppID string `json:"app_id"`
AppVersionTypes string `json:"app_version_types"`
CategorySet []HelmCategory `json:"category_set"`
CreateTime time.Time `json:"create_time"`
Description string `json:"description"`
Icon string `json:"icon"`
Isv string `json:"isv"`
LatestAppVersion AppVersion `json:"latest_app_version"`
Name string `json:"name"`
Owner string `json:"owner"`
Status string `json:"status"`
StatusTime time.Time `json:"status_time"`
UpdateTime time.Time `json:"update_time"`
ClusterTotal int `json:"cluster_total"`
Private bool `json:"private"`
}
type HelmAppList struct {
Items []HelmApp `json:"items"`
TotalItems int `json:"totalItems"`
}
type AppVersionList struct {
Items []ChartVersion `json:"items"`
TotalItems int `json:"totalItems"`
}
type ChartVersion struct {
ApiVersion string `json:"apiVersion"`
AppVersion string `json:"appVersion"`
Created string `json:"created"`
Deprecated bool `json:"deprecated"`
Description string `json:"description"`
Digest string `json:"digest"`
Home string `json:"home"`
Icon string `json:"icon"`
Keywords []string `json:"keywords"`
Name string `json:"name"`
Sources []string `json:"sources"`
Urls []string `json:"urls"`
Version string `json:"version"`
AppID string `json:"app_id"`
}
type AppVersion struct {
Active bool `json:"active"`
AppID string `json:"app_id"`
CreateTime time.Time `json:"create_time"`
Maintainers string `json:"maintainers"`
Name string `json:"name"`
Owner string `json:"owner"`
PackageName string `json:"package_name"`
Sources string `json:"sources"`
Status string `json:"status"`
StatusTime time.Time `json:"status_time"`
UpdateTime time.Time `json:"update_time"`
VersionID string `json:"version_id"`
}
type HelmReq struct {
Instances []HelmSriov `json:"instances"`
Ippools []HelmIPPool `json:"ippools"`
Conf string `json:"conf"`
}
type HelmIPPool struct {
AreaKey string `json:"areaKey"`
Ipv4 []string `json:"ipv4"`
Ipv6 []string `json:"ipv6"`
}
type HelmInstall struct {
Namespace string `json:"namespace"`
ChartName string `json:"chart_name"`
Uuid []string `json:"uuid"`
Version string `json:"version"`
ChartRelease string `json:"chart_release"`
Conf string `json:"conf"`
}
type HelmUnInstall struct {
Namespace string `json:"namespace"`
ChartRelease string `json:"chart_release"`
}
type RespFail struct {
Error string `json:"error"`
}
type RespResult struct {
Message string `json:"message"`
Status int `json:"status"`
}
type HelmReleaseList struct {
Items []HelmRelease `json:"items"`
TotalItems int `json:"totalItems"`
}
type HelmRelease struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Revision string `json:"revision"`
Updated string `json:"updated"`
Status string `json:"status"`
Chart string `json:"chart"`
}
package models
//type HelmSriovList struct {
// HelmList []HelmSriov `json:"helmList"`
//}
type HelmSriov struct {
SriovList []Sriov `json:"sriov"`
UUID string `json:"uuid"`
}
type Sriov struct {
VfName string `json:"vfName"`
ResourceName string `json:"resourceName"`
Network NetworkInfo `json:"network"`
}
type NetworkInfo struct {
Name string `json:"name"`
AddressV4 string `json:"address_v4"`
GatewayV4 string `json:"gateway_v4"`
AddressV6 string `json:"address_v6"`
GatewayV6 string `json:"gateway_v6"`
}
type SriovConfigmap struct {
APIVersion string `json:"apiVersion"`
Data ConfigmapData `json:"data"`
}
type ConfigmapData struct {
ConfigJSON string `json:"config.json"`
}
type ConfigJSON struct {
ResourceList []SriovResource `json:"resourceList"`
}
type SriovResource struct {
ResourceName string `json:"resourceName"`
Selectors SriovResourceSelector `json:"selectors"`
}
type SriovResourceSelector struct {
Vendors []string `json:"vendors"`
Devices []string `json:"devices"`
Drivers []string `json:"drivers"`
}
type ResourceNameList []ResourceName
type ResourceName struct {
Name string `json:"name"`
Vendor []string `json:"vendor"`
Devices []string `json:"devices"`
Drivers []string `json:"drivers"`
Allocatable string `json:"allocatable"`
Capacity string `json:"capacity"`
}
package models
// InstanceJSON 前端交互数据结构
type InstanceJSON struct {
UUID string `json:"uuid,omitempty"`
Name string `json:"name,omitempty"`
NodeName string `json:"nodename,omitempty"`
CPUBind string `json:"cpubind,omitempty"`
Memory string `json:"memory,omitempty"`
HugePageSize string `json:"hugepagesize,omitempty"`
HugePages string `json:"hugepages,omitempty"`
Nic []string `json:"nic,omitempty"`
Acc []string `json:"acc,omitempty"`
Sriov []string `json:"sriov,omitempty"`
NumaNode string `json:"numanode,omitempty"`
Status string `json:"status,omitempty"`
}
type InstanceListJSON struct {
Items []InstanceJSON `json:"items"`
TotalItems int `json:"totalItems"`
}
//后台存取数据结构
type Instance struct {
UUID string
Name string
NodeName string
HugePageSize string
HugePages string
CPUBind string
Memory string
Nic []string
Acc []string
Sriov []string
Status string
NumaNode string
}
// EtcdNodeCerts etcd链接函数使用
type EtcdNodeCerts struct {
URL string
EtcdCert string
EtcdCertKey string
EtcdCa string
}
// ReturnResp string形式Message response
type ReturnResp struct {
Message string `json:"message"`
Status int `json:"status"`
}
// CheckExclReturnResp check确定性资源计算服务返回格式
type CheckExclReturnResp struct {
Message string `json:"message"`
Status int `json:"status"`
Service string `json:"service"`
}
type Nodes struct {
Nodes []string `json:"nodes"`
}
package models
type VFinfo struct {
Index string `json:"index"`
Name string `json:"name"`
PCI string `json:"pci"`
Usage bool `json:"usage"`
}
type SRIOVInfo struct {
OpenSriov bool `json:"openSriov"`
MaxVfNum int `json:"maxVfNum"`
VfNum int `json:"vfNum"`
UsedVfNum int `json:"usedVfNum"`
Vfsinfo []VFinfo `json:"vfsInfo"`
}
type VFInfoPage struct {
Items []VFinfo `json:"items"`
TotalItems int `json:"totalItems"`
}
type PortInfo struct {
PortName string `json:"portName"`
DeviceModel string `json:"deviceModel"`
MacAddr string `json:"macAddr"`
Speed string `json:"speed"`
Status string `json:"status"`
MTU string `json:"mtu"`
Driver string `json:"driver"`
Numa string `json:"numa"`
PciAddr string `json:"pciAddr"`
UsedByInstance bool `json:"usedByInstance"`
SupportSriov bool `json:"supportSriov"`
SriovInfo *SRIOVInfo `json:"sriovInfo"`
}
type PortResourceInfo struct {
PortName string `json:"portName" gorm:"column:portName"`
MacAddr string `json:"macAddr" gorm:"column:macAddr"`
Speed string `json:"speed" gorm:"column:speed"`
Mtu string `json:"mtu" gorm:"column:mtu"`
Driver string `json:"driver" gorm:"column:driver"`
PciAddr string `json:"pciAddr" gorm:"column:pciAddr"`
}
type VfResourceInfo struct {
Index string `json:"index" gorm:"column:index"`
Name string `json:"name" gorm:"column:name"`
Pci string `json:"pci" gorm:"column:pci"`
}
type VfsResourceInfo struct {
PortName string `json:"portName" gorm:"column:portName"`
MacAddr string `json:"macAddr" gorm:"column:macAddr"`
VfsInfo []VfResourceInfo `json:"vfsInfo" gorm:"column:vfsInfo"`
}
type NodePortsResource struct {
UsableNic []PortResourceInfo `json:"usableNic" gorm:"column:usableNic"`
UsableVf []VfsResourceInfo `json:"usableVf" gorm:"column:usableVf"`
}
//前端交互数据结构
type IppoolJSON struct {
Name string `json:"name"`
NodeName string `json:"nodeName"`
Cidr string `json:"cidr"`
}
type IppoolInfo struct {
Name string `json:"name"`
IPVersion string `json:"ipVersion"`
Cidr string `json:"cidr"`
IPInUse string `json:"ipInUse"`
}
type OneIppoolInfo struct {
Items IppoolInfo `json:"items"`
}
type IpversionIppoolsInfo struct {
Items []IppoolInfo `json:"items"`
}
type VfNumCheck struct {
NoVfUsed bool `json:"noVfUsed"`
GreaterThanUsed bool `json:"greaterThanUsed"`
LessThanSupport bool `json:"lessThanSupport"`
}
type PortsInfo struct {
PortsInfo []PortInfo `json:"portsInfo"`
}
type IppoolsInfo struct {
Items []IppoolInfo `json:"items"`
TotalItems int `json:"totalItems"`
}
type PortsInfoResponse struct {
Items []PortInfo `json:"items"`
}
type PortInfoResponse struct {
Items PortInfo `json:"items"`
}
type PortInfoItems struct {
Items PortInfo `json:"items"`
}
type VfNumCheckResponse struct {
Items VfNumCheck `json:"items"`
}
type ActionReturnResponse struct {
Message string `json:"message"`
Status string `json:"status"`
}
type AlertAction struct {
Status string `json:"status"`
Reason string `json:"reason"`
}
type ReturnAlertAction struct {
Status int `json:"status"`
Reason string `json:"reason"`
}
type CheckResponse struct {
Message string `json:"message"`
Status string `json:"status"`
}
type CheckReturnResponse struct {
Message string `json:"message"`
Status int `json:"status"`
}
type IppoolsInfoResponse struct {
IppoolsInfo
}
type IppoolInfoResponse struct {
Items IppoolInfo `json:"items"`
}
package models
type NodeJSON struct {
Nodes []string `json:"nodes,omitempty"`
}
type OSInfo struct {
Status int `json:"status"`
Message string `json:"message"`
OS struct {
Arch string `json:"arch"`
Release string `json:"release"`
} `json:"osinfo"`
}
type NodesInfo struct {
Nodes []NodeInfo `json:"nodes" gorm:"column:nodes"`
}
type NodeInfo struct {
Name string `json:"name" gorm:"column:name"`
Numa []struct {
Networkinterface int `json:"networkinterface" gorm:"column:networkinterface"`
Mem int `json:"mem" gorm:"column:mem"`
Largememory struct {
Hugepage1G int `json:"hugepage1G" gorm:"column:hugepage1G"`
Hugepage2M int `json:"hugepage2M" gorm:"column:hugepage2M"`
} `json:"largememory" gorm:"column:largememory"`
Name string `json:"name" gorm:"column:name"`
Sriov int `json:"sriov" gorm:"column:sriov"`
CPU int `json:"cpu" gorm:"column:cpu"`
} `json:"numa" gorm:"column:numa"`
}
type NodeRes struct {
Result struct {
Nodes []NodeInfo
} `json:"result" gorm:"column:result"`
}
type CPU struct {
Cores []string `json:"cores" gorm:"column:cores"`
CoresHT []string `json:"coresHT" gorm:"column:cores"`
}
type NodeNumaItems struct {
Items struct {
UsableNic []PortResourceInfo `json:"usableNic" gorm:"column:usableNic"`
UsableVf []VfsResourceInfo `json:"usableVf" gorm:"column:usableVf"`
CPUBind struct {
Cores []string `json:"cores" gorm:"column:cores"`
CoresHT []string `json:"coresHT" gorm:"column:coresHT"`
} `json:"cpuBind" gorm:"column:cpuBind"`
SmartNic []interface{} `json:"smartNic" gorm:"column:smartNic"`
} `json:"items" gorm:"column:items"`
}
type FortImageJSON struct {
Repo string `json:"repo"`
Tag string `json:"tag"`
}
type WriteNodeCPU struct {
NodeName string `json:"node"`
TcAllCpus string `json:"tc_all_cpus"`
TcReservedCpus string `json:"tc_reservd_cpus"`
TcSharedCpus string `json:"tc_shared_cpus"`
TcIsolCpus string `json:"tc_isol_cpus"`
}
type ClearNodeCPU struct {
NodeName string `json:"node"`
}
type WriteNodeCPUResp struct {
Status int `json:"status"`
}
type AlertJSON struct {
Enable string `json:"enable"`
}
type CheckNodeInfoRes struct {
Status string `json:"status"`
Result []NodeCheckRes `json:"result"`
}
type NodeCheckRes struct {
Name string `json:"name"`
ProduceName string `json:"produceName"`
CpuInfo string `json:"cpuInfo"`
CoresTotal int `json:"coresTotal"`
HyperThreading bool `json:"hyperThreading"`
MemoryTotal string `json:"memoryTotal"`
MemoryUse string `json:"memoryUse"`
Cores []Core `json:"cores"`
CoresHT []Core `json:"coresHT"`
MemoryBankTotal int `json:"memoryBankTotal"`
MemoryBankUse int `json:"memoryBankUse"`
LargeMemoryTotal LargeMemory `json:"largeMemoryTotal"`
LargeMemoryUse LargeMemory `json:"largeMemoryUse"`
}
type Core struct {
Pool string `json:"pool"`
Lock bool `json:"lock"`
Name string `json:"name"`
}
type LargeMemory struct {
Memory1G int `json:"1G"`
Memory2M int `json:"2M"`
}
type NumaCPUList struct {
Result []NumaCPU `json:"result"`
Status string `json:"status"`
}
type NumaCPU struct {
Name string `json:"name"`
Cores []Core `json:"cores"`
CoresHT []Core `json:"coresHT"`
}
type NumaVFInfo struct {
Index string `json:"index"`
Name string `json:"name"`
PCI string `json:"pci"`
Usage bool `json:"usage"`
Port string `json:"port"`
}
type NumaDetail struct {
EthList struct {
PortsName []string `json:"portsName"`
SriovList []NumaVFInfo `json:"sriov"`
} `json:"eth"`
FPGAList FPGAListResponse `json:"FPGA"`
GPUList GpuListResponse `json:"GPU"`
CoresTotal int `json:"coresTotal"`
MemoryTotal string `json:"memoryTotal"`
LargeMemoryTotal LargeMemory `json:"largeMemoryTotal"`
}
package models
type GetNTPDataReq struct {
Nodes []string `json:"nodes"`
Key string `json:"key"`
}
type GetNTPDataRes struct {
TimeZones []string `json:"timezone_list"`
ServerTime string `json:"server_time"`
MaxChange string `json:"maxchange"`
Ignore string `json:"ignore"`
TimeZone string `json:"timezone"`
NTPServer []string `json:"ntp_server"`
}
type GetNTPServerRes struct {
Code int `json:"code"`
Msg string `json:"msg"`
NTPServer []string `json:"ntp_server"`
NTPServerFlag string `json:"ntp_server_flag"`
OSTime string `json:"os_time"`
OSDate string `json:"os_date"`
MaxchangeOffsetTime string `json:"maxchange_offset_time"`
MaxchangeIgnore string `json:"maxchange_ignore"`
TimeZone string `json:"time_zone"`
}
type GetTimeZonesRes struct {
Code int `json:"code"`
Msg string `json:"msg"`
TimeZones []string `json:"timezones_list"`
}
type SetNTPDataReq struct {
Nodes []string `json:"nodes"`
NtpData NTPData `json:"ntpData"`
}
type NTPData struct {
TimeZone string `json:"timezone"`
MaxChange string `json:"maxchange"`
Ignore string `json:"ignore"`
NTPServer []string `json:"ntp_server"`
}
type SetNTPDataRes struct {
Status int `json:"status"`
Message string `json:"message"`
}
type SetNTPTimeReq struct {
Nodes []string `json:"nodes"`
ServerTime string `json:"server_time"`
}
type SetNTPTimeRpc struct {
ServerTime string `json:"server_time"`
}
package models
type SRIOVResource struct {
Items []SRIOVResourceCount `json:"items"`
Total int `json:"total"`
}
type SRIOVResourceCount struct {
ResourceName string `json:"resource_name"`
ResourceCount []ResourceCount `json:"sriov_num"`
}
type ResourceCount struct {
NodeName string `json:"node_name"`
Allocatable string `json:"allocatable"`
Capacity string `json:"capacity"`
}
package models
// CheckVerifyFileResp 前端交互数据结构
type CheckVerifyFileResp struct {
VerifyService string `json:"verify-service"`
Message string `json:"message"`
Status int `json:"status"`
}
type HelmUpdate struct {
}
type DockerImageUpdate struct {
}
type SwitchVerifyFileResp struct {
VerifyService string `json:"verify-service"`
Message string `json:"message"`
Status int `json:"status"`
}
package models
type Workspace struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Metadata struct {
Name string `json:"name"`
Annotations struct {
KubesphereIoAliasName string `json:"kubesphere.io/alias-name"`
KubesphereIoDescription string `json:"kubesphere.io/description"`
KubesphereIoCreator string `json:"kubesphere.io/creator"`
} `json:"annotations"`
} `json:"metadata"`
Spec struct {
Template struct {
Spec struct {
Manager string `json:"manager"`
} `json:"spec"`
} `json:"template"`
} `json:"spec"`
}
type Alert struct {
Status string `json:"status"`
Reason string `json:"reason"`
Enable string `json:"enable"`
}
This diff is collapsed.
This diff is collapsed.
package utils
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"sort"
"strings"
)
var RpcPort = "9988"
var RegistryHost = "registry.futureedge.lenovo.com"
type DefaultRes struct {
Status int `json:"status"`
Result []byte `json:"result"`
}
func Shellcmd(cmd string) (string, error) {
command := exec.Command("bash", "-c", cmd)
output, err := command.CombinedOutput()
if err != nil {
fmt.Println(err.Error())
return string(output), err
}
//返回string类型的output
return string(output), nil
}
//EncodeStruct :返回数据结构的封装
func EncodeStruct(b interface{}) []byte {
//1.创建空接口
//var value interface{}
//switch x := b.(type) {
//case models2.HelmInfo:
// value = b.(x)
//case models2.InstanceJSON:
// value = b.(models2.InstanceJSON)
//case models2.InstanceListJSON:
// value = b.(models2.InstanceListJSON)
//case models2.ResourceNameList:
// value = b.(models2.ResourceNameList)
//case models2.ResourceName:
// value = b.(models2.ResourceName)
//case models2.HelmAppList:
// value = b.(models2.HelmAppList)
//default:
// bytes, ok := b.([]byte)
// if !ok {
// value = DefaultRes{Status: 500, Result: []byte("执行出错")}
// } else {
// value = DefaultRes{Status: 200, Result: bytes}
// }
//
//}
//3.所有的类型进行断言,然后返回json个数的数据
encodestruct, err := json.MarshalIndent(b, "", " ")
if err != nil {
fmt.Println(err.Error())
}
return encodestruct
}
//如果某个文件不存在,那么使用os.Lstat就一定会返回error,只要判断error是否代表文件不存在即可
func FileExist(path string) bool {
_, err := os.Lstat(path)
return !os.IsNotExist(err)
}
//
func HTTPRequest(url, method string, reader io.Reader, headermap map[string]string) ([]byte, error) {
client := &http.Client{}
req, err := http.NewRequest(method, url, reader)
if err != nil {
fmt.Println(err)
return nil, err
}
for key, value := range headermap {
req.Header.Add(key, value)
}
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return nil, err
}
return body, err
}
func Sha256Hash(file string) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
defer f.Close()
chunkSize := 65536
buf := make([]byte, chunkSize)
h := sha256.New()
for {
n, err := f.Read(buf)
if err == io.EOF {
break
}
chunk := buf[0:n]
h.Write(chunk)
}
sum := h.Sum(nil)
//由于是十六进制表示,因此需要转换
hash := hex.EncodeToString(sum)
return hash, nil
}
//GetFileSize 获取文件大小
func GetFileSize(file string) (int64, error) {
f, err := os.Open(file)
if err != nil {
return 0, err
}
stat, err := f.Stat() //获取文件状态
if err != nil {
return 0, err
}
defer f.Close()
return stat.Size(), nil
}
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
return os.IsExist(err)
}
return true
}
//ParseImageAndTag parse image repo
func ParseImageAndTag(repo string) (string, string) {
arr := strings.Split(repo, ":")
return arr[0], arr[1]
}
func GetNodes() (nodes []string) {
var result []string
path := "/etc/hosts"
f, err := os.Open(path)
if err != nil {
// 打开文件失败
fmt.Println("打开文件失败")
return result
}
var data []byte
buf := make([]byte, 1024)
for {
// 将文件中读取的byte存储到buf中
n, err := f.Read(buf)
if err != nil && err != io.EOF {
fmt.Println(err)
return result
}
if n == 0 {
break
}
// 将读取到的结果追加到data切片中
data = append(data, buf[:n]...)
}
// 将data切片转为字符串
// fmt.Println(string(data))
defer func(f *os.File) {
err = f.Close()
if err != nil {
fmt.Println("err", err)
}
}(f)
content := string(data)
contentRowArr := strings.Split(content, "\n")
for _, row := range contentRowArr {
if len(row) == 0 {
break
}
if !strings.Contains(row, "localhost") {
spaceIndex := strings.Index(row, " ")
result = append(result, row[spaceIndex+1:])
}
}
return result
}
func RemoveDuplicatesInPlace(sli []string) []string {
// 如果有0或1个元素,则返回切片本身。
if len(sli) < 2 {
return sli
}
// 使切片升序排序
sort.SliceStable(sli, func(i, j int) bool { return sli[i] < sli[j] })
uniqPointer := 0
for i := 1; i < len(sli); i++ {
// 比较当前元素和唯一指针指向的元素
// 如果它们不相同,则将项写入唯一指针的右侧。
if sli[uniqPointer] != sli[i] {
uniqPointer++
sli[uniqPointer] = sli[i]
}
}
return sli[:uniqPointer+1]
}
package views
import (
"encoding/json"
"fmt"
tcmodles "kubesphere.io/kubesphere/pkg/kapis/futuredge/v1alpha1/models"
"kubesphere.io/kubesphere/pkg/kapis/futuredge/v1alpha1/utils"
"net/url"
"strings"
"sync"
)
var wgg sync.WaitGroup
var Tcnodes []string
var Running = false
func AlertInfo(nodeName string, ch chan string) {
targetURL := "http://" + nodeName + ":9988/alert/info"
fmt.Println("nodeName is:", nodeName)
params := url.Values{}
URL, _ := url.Parse(targetURL)
params.Set("node", nodeName)
URL.RawQuery = params.Encode()
urlPath := URL.String()
fmt.Println(URL.String())
data, err := utils.HTTPRequest(urlPath, "GET", nil, nil)
if err != nil {
fmt.Println("err is:", err)
ch <- fmt.Sprintf("%s", err)
} else {
ch <- string(data)
}
wgg.Done()
}
func InstallAlert(enable string) ([]byte, error) {
if Running {
info := fmt.Sprintf("{\"status\": \"2002\", \"reason\": \"%s\"}", "正在操作,不要重复进行该操作")
return []byte(info), nil
}
if len(Tcnodes) == 0 {
info := fmt.Sprintf("{\"status\": \"2003\", \"reason\": \"%s\"}", "没有可用的执行节点,请检查环境")
return []byte(info), nil
}
Running = true
fmt.Println("Tcnodes is:", Tcnodes)
tconodes := []string{}
for _, value := range Tcnodes {
tconodes = append(tconodes, strings.Split(value, "-")[0])
}
nodeName := tconodes[0]
targetURL := "http://" + nodeName + ":9988/alert/install"
fmt.Println("nodeName is:", nodeName)
params := url.Values{}
URL, _ := url.Parse(targetURL)
ss := strings.Join(tconodes, ",")
params.Set("nodes", ss)
params.Set("enable", enable)
params.Set("node", nodeName)
URL.RawQuery = params.Encode()
urlPath := URL.String()
fmt.Println(URL.String())
data, err := utils.HTTPRequest(urlPath, "GET", nil, nil)
var info string
if err != nil {
info = fmt.Sprintf("{\"status\": \"2004\", \"reason\": \"install for %s\"}", err)
Tcnodes = []string{}
Running = false
return []byte(info), nil
}
mapstatus := map[string]string{}
_ = json.Unmarshal(data, &mapstatus)
if mapstatus["status"] == "failed" {
Tcnodes = []string{}
Running = false
info = fmt.Sprintf("{\"status\": \"2005\", \"reason\": \"%s\"}", mapstatus["reason"])
return []byte(info), nil
}
targetURL = "http://" + nodeName + ":9988/alert/check"
_, err = utils.HTTPRequest(targetURL, "GET", nil, nil)
if err != nil {
info = fmt.Sprintf("{\"status\": \"2006\", \"reason\": \"check for %s\"}", err)
Tcnodes = []string{}
Running = false
return []byte(info), nil
}
Tcnodes = []string{}
Running = false
if mapstatus["status"] == "success" {
info = fmt.Sprintf("{\"status\": \"200\", \"reason\": \"%s\"}", mapstatus["reason"])
return []byte(info), nil
}
info = fmt.Sprintf("{\"status\": \"2007\", \"reason\": \"%s\"}", mapstatus["reason"])
return []byte(info), nil
}
func Alert(nodes []string) (tcmodles.Alert, error) {
var output tcmodles.Alert
if Running {
output.Status = "running"
output.Reason = "正在执行,请稍等"
return output, nil
}
var tcnodestrings []string
ch := make(chan string, len(nodes))
wgg.Add(len(nodes))
for _, nodeName := range nodes {
go AlertInfo(nodeName, ch)
}
wg.Wait()
for i := 0; i < len(nodes); i++ {
tcnodestrings = append(tcnodestrings, <-ch)
}
fmt.Println("tcnodestrings is :", tcnodestrings)
count := 0
mapstatus := map[string]string{}
for _, value := range tcnodestrings {
err := json.Unmarshal([]byte(value), &mapstatus)
if err != nil {
output.Status = "error"
output.Reason = err.Error()
return output, nil
}
fmt.Printf("value type is:%T, value is:%v", value, value)
if mapstatus["status"] == "alert-running" {
output.Status = "running"
output.Reason = "正在执行,请稍等"
return output, nil
} else if mapstatus["status"] == "alert-readying" {
count++
fmt.Println("count is:", count)
} else {
Tcnodes = append(Tcnodes, mapstatus["status"])
}
}
fmt.Println("Tcnodes is:", Tcnodes)
if count < len(nodes) {
var flag string
var status bool
for i := 0; i < len(Tcnodes); i++ {
if i == 0 {
flag = strings.Split(Tcnodes[i], "-")[1]
} else {
flagstatus := strings.Split(Tcnodes[i], "-")[1]
if flag != flagstatus {
status = true
}
}
}
if status {
Tcnodes = []string{}
output.Status = "error"
output.Reason = "环境中的yaml文件内容不一致,请查看环境是否正常"
return output, nil
}
Tcnodes = []string{}
output.Status = "ready"
output.Enable = flag
return output, nil
}
Tcnodes = []string{}
output.Status = "error"
output.Reason = "没有找到可执行安装的yaml文件,请查看环境是否正常"
return output, nil
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment