sync-change-2024.11.6

Signed-off-by: wbc6080 <wangbincheng4@huawei.com>
This commit is contained in:
wbc6080 2024-11-06 16:31:21 +08:00
parent 38ae52db4b
commit cf27165fab
195 changed files with 69221 additions and 2 deletions

View File

@ -1,2 +1,10 @@
# api
The canonical location of the KubeEdge API definition.
# API
Schema of the external API types that are served by KubeEdge.
# Purpose
This library is the canonical location of the KubeEdge API definition. It will be published separately to avoid diamond dependency problems for users who depend on multiple KubeEdge components.
On the other hand, this library also provides available CRD informers/listers/clientsets and KubeEdge API documentation for users.
# Where does it come from?
api is synced from https://github.com/kubeedge/kubeedge/tree/master/staging/src/github.com/kubeedge/api.
Code changes are made in that location, merged into KubeEdge and later synced here.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,15 @@
/*
Copyright The KubeEdge 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.
*/

View File

@ -0,0 +1,61 @@
#!/usr/bin/env bash
# Copyright 2024 The KubeEdge 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.
set -o errexit
set -o nounset
set -o pipefail
# Define root and output directories
KUBEEDGE_ROOT=$(unset CDPATH && cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)
OUTPUT_DIR="${KUBEEDGE_ROOT}/apidoc/generated"
# Install openapi-gen tool
if [ "$(which openapi-gen)" == "" ]; then
echo "Start to install openapi-gen tool"
GO111MODULE=on go install k8s.io/kube-openapi/cmd/openapi-gen
GOPATH="${GOPATH:-$(go env GOPATH)}"
export PATH=$PATH:$GOPATH/bin
fi
# Check and create output directory
if [[ ! -d "${OUTPUT_DIR}" ]]; then
mkdir -p "${OUTPUT_DIR}"
fi
# Run openapi-gen to generate files
echo "Generating with openapi-gen..."
openapi-gen \
--input-dirs "github.com/kubeedge/api/apis/apps/v1alpha1" \
--input-dirs "github.com/kubeedge/api/apis/policy/v1alpha1" \
--input-dirs "github.com/kubeedge/api/apis/devices/v1alpha2" \
--input-dirs "github.com/kubeedge/api/apis/devices/v1beta1" \
--input-dirs "github.com/kubeedge/api/apis/operations/v1alpha1" \
--input-dirs "github.com/kubeedge/api/apis/reliablesyncs/v1alpha1" \
--input-dirs "github.com/kubeedge/api/apis/rules/v1" \
--input-dirs "k8s.io/api/rbac/v1" \
--input-dirs "k8s.io/api/core/v1" \
--input-dirs "k8s.io/apimachinery/pkg/apis/meta/v1" \
--input-dirs "k8s.io/apimachinery/pkg/runtime" \
--input-dirs "k8s.io/apimachinery/pkg/version" \
--input-dirs "k8s.io/apimachinery/pkg/api/resource" \
--output-base "${KUBEEDGE_ROOT}/apidoc/generated"\
--output-package "openapi" \
--go-header-file "${KUBEEDGE_ROOT}/apidoc/tools/boilerplate/boilerplate.txt" \
--output-file-base "zz_generated.openapi"\
--v "9"
# Remove specific comments from generated files
find "${OUTPUT_DIR}" -name "zz_generated.openapi.go" -exec sed -i '/^\/\/go:build !ignore_autogenerated$/d' {} \;
find "${OUTPUT_DIR}" -name "zz_generated.openapi.go" -exec sed -i '/^\/\/ +build !ignore_autogenerated$/d' {} \;

View File

@ -0,0 +1,144 @@
/*
Copyright 2024 The KubeEdge 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 main
import (
"fmt"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/klog/v2"
"k8s.io/kube-openapi/pkg/common"
"k8s.io/kube-openapi/pkg/validation/spec"
generatedopenapi "github.com/kubeedge/api/apidoc/generated/openapi"
"github.com/kubeedge/api/apidoc/tools/lib"
appsv1alpha1 "github.com/kubeedge/api/apis/apps/v1alpha1"
devicesv1alpha2 "github.com/kubeedge/api/apis/devices/v1alpha2"
devicesv1beta1 "github.com/kubeedge/api/apis/devices/v1beta1"
operationsv1alpha1 "github.com/kubeedge/api/apis/operations/v1alpha1"
policyv1alpha1 "github.com/kubeedge/api/apis/policy/v1alpha1"
reliablesyncsv1alpha1 "github.com/kubeedge/api/apis/reliablesyncs/v1alpha1"
rulesv1 "github.com/kubeedge/api/apis/rules/v1"
)
func main() {
// Create a new Schema object
Scheme := runtime.NewScheme()
utilruntime.Must(scheme.AddToScheme(Scheme)) // add Kubernetes schemes
utilruntime.Must(appsv1alpha1.AddToScheme(Scheme))
utilruntime.Must(devicesv1alpha2.AddToScheme(Scheme))
utilruntime.Must(devicesv1beta1.AddToScheme(Scheme))
utilruntime.Must(operationsv1alpha1.AddToScheme(Scheme))
utilruntime.Must(policyv1alpha1.AddToScheme(Scheme))
utilruntime.Must(reliablesyncsv1alpha1.AddToScheme(Scheme))
utilruntime.Must(policyv1alpha1.AddToScheme(Scheme))
utilruntime.Must(rulesv1.AddToScheme(Scheme))
// Create a default REST mapper
mapper := meta.NewDefaultRESTMapper(nil)
// NodeGroup
mapper.AddSpecific(appsv1alpha1.SchemeGroupVersion.WithKind("EdgeApplication"),
appsv1alpha1.SchemeGroupVersion.WithResource("edgeapplications"),
appsv1alpha1.SchemeGroupVersion.WithResource("edgeapplication"), meta.RESTScopeRoot)
mapper.AddSpecific(appsv1alpha1.SchemeGroupVersion.WithKind("NodeGroup"),
appsv1alpha1.SchemeGroupVersion.WithResource("nodegroups"),
appsv1alpha1.SchemeGroupVersion.WithResource("nodegroup"), meta.RESTScopeRoot)
mapper.AddSpecific(devicesv1alpha2.SchemeGroupVersion.WithKind("Device"),
devicesv1alpha2.SchemeGroupVersion.WithResource("devices"),
devicesv1alpha2.SchemeGroupVersion.WithResource("device"), meta.RESTScopeNamespace)
mapper.AddSpecific(devicesv1alpha2.SchemeGroupVersion.WithKind("DeviceModel"),
devicesv1alpha2.SchemeGroupVersion.WithResource("devicemodels"),
devicesv1alpha2.SchemeGroupVersion.WithResource("devicemodel"), meta.RESTScopeNamespace)
mapper.AddSpecific(devicesv1beta1.SchemeGroupVersion.WithKind("DeviceModel"),
devicesv1beta1.SchemeGroupVersion.WithResource("devicemodels"),
devicesv1beta1.SchemeGroupVersion.WithResource("devicemodel"), meta.RESTScopeNamespace)
mapper.AddSpecific(devicesv1beta1.SchemeGroupVersion.WithKind("Device"),
devicesv1beta1.SchemeGroupVersion.WithResource("devices"),
devicesv1beta1.SchemeGroupVersion.WithResource("device"), meta.RESTScopeNamespace)
mapper.AddSpecific(operationsv1alpha1.SchemeGroupVersion.WithKind("ImagePrePullJob"),
operationsv1alpha1.SchemeGroupVersion.WithResource("imageprepulljobs"),
operationsv1alpha1.SchemeGroupVersion.WithResource("imageprepulljob"), meta.RESTScopeNamespace)
mapper.AddSpecific(operationsv1alpha1.SchemeGroupVersion.WithKind("NodeUpgradeJob"),
operationsv1alpha1.SchemeGroupVersion.WithResource("nodeupgradejobs"),
operationsv1alpha1.SchemeGroupVersion.WithResource("nodeupgradejob"), meta.RESTScopeNamespace)
mapper.AddSpecific(policyv1alpha1.SchemeGroupVersion.WithKind("ServiceAccountAccess"),
policyv1alpha1.SchemeGroupVersion.WithResource("serviceaccountaccesses"),
policyv1alpha1.SchemeGroupVersion.WithResource("serviceaccountaccess"), meta.RESTScopeNamespace)
mapper.AddSpecific(reliablesyncsv1alpha1.SchemeGroupVersion.WithKind("ClusterObjectSync"),
reliablesyncsv1alpha1.SchemeGroupVersion.WithResource("clusterobjectsyncs"),
reliablesyncsv1alpha1.SchemeGroupVersion.WithResource("clusterobjectsync"), meta.RESTScopeNamespace)
mapper.AddSpecific(reliablesyncsv1alpha1.SchemeGroupVersion.WithKind("ObjectSync"),
reliablesyncsv1alpha1.SchemeGroupVersion.WithResource("objectsyncs"),
reliablesyncsv1alpha1.SchemeGroupVersion.WithResource("objectsync"), meta.RESTScopeNamespace)
mapper.AddSpecific(rulesv1.SchemeGroupVersion.WithKind("Rule"),
rulesv1.SchemeGroupVersion.WithResource("rules"),
rulesv1.SchemeGroupVersion.WithResource("rule"), meta.RESTScopeRoot)
// Set OpenAPI spec information
spec, err := lib.RenderOpenAPISpec(lib.Config{
Info: spec.InfoProps{
Title: "Kubeedge OpenAPI",
Version: "unversioned",
Description: "KubeEdge is an open source system for extending native containerized application orchestration capabilities to hosts at Edge. For more information, please see https://github.com/Kubeedge/Kubeedge.",
License: &spec.License{
Name: "Apache 2.0", // License name
URL: "https://www.apache.org/licenses/LICENSE-2.0.html", // License URL
},
},
Scheme: Scheme, // Used Schema
Codecs: serializer.NewCodecFactory(Scheme), // Used codecs
OpenAPIDefinitions: []common.GetOpenAPIDefinitions{
generatedopenapi.GetOpenAPIDefinitions, // GetOpenAPI definitions function
},
Resources: []lib.ResourceWithNamespaceScoped{
// Define resources and their namespace scoped and resource mapping correspondingly
{GVR: appsv1alpha1.SchemeGroupVersion.WithResource("edgeapplications"), NamespaceScoped: true},
{GVR: appsv1alpha1.SchemeGroupVersion.WithResource("nodegroups"), NamespaceScoped: false},
{GVR: devicesv1beta1.SchemeGroupVersion.WithResource("devices"), NamespaceScoped: true},
{GVR: devicesv1beta1.SchemeGroupVersion.WithResource("devicemodels"), NamespaceScoped: true},
{GVR: devicesv1alpha2.SchemeGroupVersion.WithResource("devices"), NamespaceScoped: true},
{GVR: devicesv1alpha2.SchemeGroupVersion.WithResource("devicemodels"), NamespaceScoped: true},
{GVR: operationsv1alpha1.SchemeGroupVersion.WithResource("imageprepulljobs"), NamespaceScoped: false},
{GVR: operationsv1alpha1.SchemeGroupVersion.WithResource("nodeupgradejobs"), NamespaceScoped: false},
{GVR: policyv1alpha1.SchemeGroupVersion.WithResource("serviceaccountaccesses"), NamespaceScoped: true},
{GVR: reliablesyncsv1alpha1.SchemeGroupVersion.WithResource("clusterobjectsyncs"), NamespaceScoped: false},
{GVR: reliablesyncsv1alpha1.SchemeGroupVersion.WithResource("objectsyncs"), NamespaceScoped: true},
{GVR: rulesv1.SchemeGroupVersion.WithResource("rules"), NamespaceScoped: true},
},
Mapper: mapper,
})
if err != nil {
klog.Fatal(err.Error())
}
fmt.Println(spec) // Print generated OpenAPI spec
}

194
apidoc/tools/lib/render.go Normal file
View File

@ -0,0 +1,194 @@
/*
Copyright 2024 The KubeEdge 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 lib
import (
"encoding/json"
"fmt"
"net"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apiserver/pkg/endpoints/openapi"
"k8s.io/apiserver/pkg/registry/rest"
genericapiserver "k8s.io/apiserver/pkg/server"
genericoptions "k8s.io/apiserver/pkg/server/options"
"k8s.io/klog/v2"
"k8s.io/kube-openapi/pkg/builder"
"k8s.io/kube-openapi/pkg/common"
"k8s.io/kube-openapi/pkg/common/restfuladapter"
"k8s.io/kube-openapi/pkg/validation/spec"
)
// ResourceWithNamespaceScoped contains information about the group, version, resource (GVR), and whether it supports namespace scope.
type ResourceWithNamespaceScoped struct {
GVR schema.GroupVersionResource
NamespaceScoped bool
}
// Config is the struct used to configure Swagger information.
type Config struct {
Scheme *runtime.Scheme // Runtime Scheme used for type registration and object instantiation.
Codecs serializer.CodecFactory // Codec factory used for encoding and decoding objects.
Info spec.InfoProps // Basic information for the OpenAPI specification, such as title, version, etc.
OpenAPIDefinitions []common.GetOpenAPIDefinitions // Array of functions to obtain OpenAPI definitions.
Resources []ResourceWithNamespaceScoped // List of resources containing GVR and namespace scope information.
Mapper *meta.DefaultRESTMapper // REST mapper for conversion between GVR and GVK.
}
// GetOpenAPIDefinitions gets OpenAPI definitions.
func (c *Config) GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {
out := map[string]common.OpenAPIDefinition{} // Create an empty OpenAPIDefinition map.
for _, def := range c.OpenAPIDefinitions { // Iterate through the OpenAPIDefinitions function array.
for k, v := range def(ref) { // Call each function, passing in the reference callback, to get the definition map.
out[k] = v // Add the obtained definition to the output map.
}
}
return out // Return the map containing all definitions.
}
// RenderOpenAPISpec creates the OpenAPI specification for Swagger.
func RenderOpenAPISpec(cfg Config) (string, error) {
// Create and configure server options.
options := genericoptions.NewRecommendedOptions("/registry/kubeedge.io", cfg.Codecs.LegacyCodec()) // Set the prefix for the API server to /registry/kubeedge.io.
options.SecureServing.ServerCert.CertDirectory = "/tmp/kubeedge-tools" // Set the certificate directory.
options.SecureServing.BindPort = 6446 // Set the bind port.
// Disable unnecessary server components.
options.Etcd = nil
options.Authentication = nil
options.Authorization = nil
options.CoreAPI = nil
options.Admission = nil
// Attempt to configure secure serving with self-signed certificates.
if err := options.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil {
klog.Fatal(fmt.Errorf("error creating self-signed certificates: %v", err))
}
// Apply secure serving configuration, create server configuration.
serverConfig := genericapiserver.NewRecommendedConfig(cfg.Codecs)
if err := options.SecureServing.ApplyTo(&serverConfig.Config.SecureServing, &serverConfig.Config.LoopbackClientConfig); err != nil {
klog.Fatal(err)
return "", err
}
// Configure OpenAPI and OpenAPI V3.
serverConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(cfg.GetOpenAPIDefinitions, openapi.NewDefinitionNamer(cfg.Scheme))
serverConfig.OpenAPIV3Config = genericapiserver.DefaultOpenAPIV3Config(cfg.GetOpenAPIDefinitions, openapi.NewDefinitionNamer(cfg.Scheme))
serverConfig.OpenAPIConfig.Info.InfoProps = cfg.Info
// Create and configure the API server, creating a new API server instance named "kubeedge-generated-server".
genericServer, err := serverConfig.Complete().New("kubeedge-generated-server", genericapiserver.NewEmptyDelegate())
if err != nil {
klog.Fatal(err)
return "", err
}
// Create a resource router table.
table, err := createRouterTable(&cfg)
if err != nil {
klog.Fatal(err)
return "", err
}
// Configure APIs for each resource group.
for g, resmap := range table {
apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(g, cfg.Scheme, metav1.ParameterCodec, cfg.Codecs)
storage := map[string]map[string]rest.Storage{}
for r, info := range resmap {
if storage[info.gvk.Version] == nil {
storage[info.gvk.Version] = map[string]rest.Storage{}
}
storage[info.gvk.Version][r.Resource] = &StandardREST{info}
// Add status router for all resources.
storage[info.gvk.Version][r.Resource+"/status"] = &StatusREST{StatusInfo{
gvk: info.gvk,
obj: info.obj,
}}
// To define additional endpoints for CRD resources, we need to
// implement our own REST interface and add it to our custom path.
if r.Resource == "clusters" {
storage[info.gvk.Version][r.Resource+"/proxy"] = &ProxyREST{}
}
}
for version, s := range storage {
apiGroupInfo.VersionedResourcesStorageMap[version] = s
}
// Install API to API server.
if err := genericServer.InstallAPIGroup(&apiGroupInfo); err != nil {
klog.Fatal(err)
return "", err
}
}
// Create Swagger specification.
// BuildOpenAPISpecFromRoutes
// Create Swagger Spec.
spec, err := builder.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(genericServer.Handler.GoRestfulContainer.RegisteredWebServices()), serverConfig.OpenAPIConfig)
if err != nil {
klog.Fatal(err)
return "", err
}
// Serialize the specification to a JSON string.
data, err := json.MarshalIndent(spec, "", " ")
if err != nil {
klog.Fatal(err)
return "", err
}
return string(data), nil
}
// createRouterTable creates a router map for every resource.
func createRouterTable(cfg *Config) (map[string]map[schema.GroupVersionResource]ResourceInfo, error) {
table := map[string]map[schema.GroupVersionResource]ResourceInfo{}
// Create router map for every resource
for _, ti := range cfg.Resources {
var resmap map[schema.GroupVersionResource]ResourceInfo
if m, found := table[ti.GVR.Group]; found {
resmap = m
} else {
resmap = map[schema.GroupVersionResource]ResourceInfo{}
table[ti.GVR.Group] = resmap
}
gvk, err := cfg.Mapper.KindFor(ti.GVR)
if err != nil {
klog.Fatal(err)
return nil, err
}
obj, err := cfg.Scheme.New(gvk)
if err != nil {
klog.Fatal(err)
return nil, err
}
list, err := cfg.Scheme.New(gvk.GroupVersion().WithKind(gvk.Kind + "List"))
if err != nil {
klog.Fatal(err)
return nil, err
}
resmap[ti.GVR] = ResourceInfo{
gvk: gvk,
obj: obj,
list: list,
namespaceScoped: ti.NamespaceScoped,
}
}
return table, nil
}

193
apidoc/tools/lib/storage.go Normal file
View File

@ -0,0 +1,193 @@
/*
Copyright 2024 The KubeEdge 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 lib
import (
"context"
"net/http"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/registry/rest"
)
// StandardREST define CRUD api for resources.
type StandardREST struct {
cfg ResourceInfo
}
// StatusREST define status endpoint for resources.
type StatusREST struct {
cfg StatusInfo
}
// ProxyREST define proxy endpoint for resources.
type ProxyREST struct{}
// Implement below interfaces for StandardREST.
var _ rest.GroupVersionKindProvider = &StandardREST{}
var _ rest.Scoper = &StandardREST{}
var _ rest.StandardStorage = &StandardREST{}
var _ rest.SingularNameProvider = &StandardREST{}
// Implement below interfaces for StatusREST.
var _ rest.Patcher = &StatusREST{}
// Implement below interfaces for ProxyREST.
var _ rest.Connecter = &ProxyREST{}
// GroupVersionKind implement GroupVersionKind interface.
func (r *StandardREST) GroupVersionKind(_ schema.GroupVersion) schema.GroupVersionKind {
return r.cfg.gvk
}
// NamespaceScoped implement NamespaceScoped interface.
func (r *StandardREST) NamespaceScoped() bool {
return r.cfg.namespaceScoped
}
// New implement New interface.
func (r *StandardREST) New() runtime.Object {
return r.cfg.obj
}
// Create implement Create interface.
func (r *StandardREST) Create(_ context.Context, _ runtime.Object, _ rest.ValidateObjectFunc, _ *metav1.CreateOptions) (runtime.Object, error) {
return r.New(), nil
}
// Get implement Get interface.
func (r *StandardREST) Get(_ context.Context, _ string, _ *metav1.GetOptions) (runtime.Object, error) {
return r.New(), nil
}
// NewList implement NewList interface.
func (r *StandardREST) NewList() runtime.Object {
return r.cfg.list
}
// List implement List interface.
func (r *StandardREST) List(_ context.Context, _ *metainternalversion.ListOptions) (runtime.Object, error) {
return r.NewList(), nil
}
// ConvertToTable implement ConvertToTable interface.
func (r *StandardREST) ConvertToTable(_ context.Context, _ runtime.Object, _ runtime.Object) (*metav1.Table, error) {
return nil, nil
}
// Update implement Update interface.
func (r *StandardREST) Update(_ context.Context, _ string, _ rest.UpdatedObjectInfo, _ rest.ValidateObjectFunc, _ rest.ValidateObjectUpdateFunc, _ bool, _ *metav1.UpdateOptions) (runtime.Object, bool, error) {
return r.New(), true, nil
}
// Delete implement Delete interface.
func (r *StandardREST) Delete(_ context.Context, _ string, _ rest.ValidateObjectFunc, _ *metav1.DeleteOptions) (runtime.Object, bool, error) {
return r.New(), true, nil
}
// DeleteCollection implement DeleteCollection interface.
func (r *StandardREST) DeleteCollection(_ context.Context, _ rest.ValidateObjectFunc, _ *metav1.DeleteOptions, _ *metainternalversion.ListOptions) (runtime.Object, error) {
return r.NewList(), nil
}
// Watch implement Watch interface.
func (r *StandardREST) Watch(_ context.Context, _ *metainternalversion.ListOptions) (watch.Interface, error) {
return nil, nil
}
// Destroy cleans up its resources on shutdown.
func (r *StandardREST) Destroy() {
// Given no underlying store, so we don't
// need to destroy anything.
}
// GetSingularName implements the SingularNameProvider interfaces.
func (r *StandardREST) GetSingularName() string {
return ""
}
// GroupVersionKind implement GroupVersionKind interface.
func (r *StatusREST) GroupVersionKind(_ schema.GroupVersion) schema.GroupVersionKind {
return r.cfg.gvk
}
// New returns Cluster object.
func (r *StatusREST) New() runtime.Object {
return r.cfg.obj
}
// Update alters the status subset of an object.
func (r *StatusREST) Update(_ context.Context, _ string, _ rest.UpdatedObjectInfo, _ rest.ValidateObjectFunc, _ rest.ValidateObjectUpdateFunc, _ bool, _ *metav1.UpdateOptions) (runtime.Object, bool, error) {
return r.New(), true, nil
}
// Get retrieves the status object.
func (r *StatusREST) Get(_ context.Context, _ string, _ *metav1.GetOptions) (runtime.Object, error) {
return r.New(), nil
}
// Destroy cleans up its resources on shutdown.
func (r *StatusREST) Destroy() {
// Given no underlying store, so we don't
// need to destroy anything.
}
// New returns an empty cluster proxy subresource.
func (r *ProxyREST) New() runtime.Object {
//return &clusterv1alpha1.ClusterProxyOptions{}
return nil
}
// ConnectMethods returns the list of HTTP methods handled by Connect.
func (r *ProxyREST) ConnectMethods() []string {
return []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
}
// NewConnectOptions returns versioned resource that represents proxy parameters.
func (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string) {
//return &clusterv1alpha1.ClusterProxyOptions{}, true, "path"
return nil, true, "path"
}
// Connect implement Connect interface.
func (r *ProxyREST) Connect(_ context.Context, _ string, _ runtime.Object, _ rest.Responder) (http.Handler, error) {
return nil, nil
}
// Destroy cleans up its resources on shutdown.
func (r *ProxyREST) Destroy() {
// Given no underlying store, so we don't
// need to destroy anything.
}
// ResourceInfo is content of StandardREST.
type ResourceInfo struct {
gvk schema.GroupVersionKind
obj runtime.Object
list runtime.Object
namespaceScoped bool
}
// StatusInfo is content of StatusREST.
type StatusInfo struct {
gvk schema.GroupVersionKind
obj runtime.Object
}

View File

@ -0,0 +1,32 @@
#!/usr/bin/env bash
# Copyright 2024 The KubeEdge 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.
set -o errexit
set -o nounset
set -o pipefail
KUBEEDGE_ROOT=$(unset CDPATH && cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)
folder_name="${KUBEEDGE_ROOT}/apidoc/generated/swagger"
if [ ! -d "$folder_name" ]; then
mkdir "$folder_name"
fi
go run ${KUBEEDGE_ROOT}/apidoc/tools/generate-swagger.go > ${KUBEEDGE_ROOT}/apidoc/generated/swagger/swagger.json
# Delete trash of generating swagger doc
rm -rf /tmp/kubeedge-swagger

21
apis/apps/v1alpha1/doc.go Normal file
View File

@ -0,0 +1,21 @@
/*
Copyright 2022 The KubeEdge 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 v1alpha1 is the v1alpha1 version of the API.
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +groupName=apps.kubeedge.io
package v1alpha1

View File

@ -0,0 +1,306 @@
/*
Copyright 2022 The KubeEdge 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 v1alpha1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// EdgeApplicationSpec defines the desired state of EdgeApplication
type EdgeApplicationSpec struct {
// WorkloadTemplate contains original templates of resources to be deployed
// as an EdgeApplication.
WorkloadTemplate ResourceTemplate `json:"workloadTemplate,omitempty"`
// WorkloadScope represents which node groups the workload will be deployed in.
WorkloadScope WorkloadScope `json:"workloadScope"`
}
// WorkloadScope represents which node groups the workload should be deployed in.
type WorkloadScope struct {
// TargetNodeGroups represents the target node groups of workload to be deployed.
// +optional
TargetNodeGroups []TargetNodeGroup `json:"targetNodeGroups,omitempty"`
}
// TargetNodeGroup represents the target node group of workload to be deployed, including
// override rules to apply for this node group.
type TargetNodeGroup struct {
// Name represents the name of target node group
Name string `json:"name"`
// Overriders represents the override rules that would apply on workload.
Overriders Overriders `json:"overriders,omitempty"`
}
// ResourceTemplate represents original templates of resources to be deployed
// as an EdgeApplication.
type ResourceTemplate struct {
// Manifests represent a list of Kubernetes resources to be deployed on the managed node groups.
// +optional
Manifests []Manifest `json:"manifests,omitempty"`
}
// Overriders represents the override rules that would apply on resources.
type Overriders struct {
// Replicas will override the replicas field of deployment
// +optional
Replicas *int `json:"replicas,omitempty"`
// ImageOverriders represents the rules dedicated to handling image overrides.
// +optional
ImageOverriders []ImageOverrider `json:"imageOverriders,omitempty"`
// EnvOverriders will override the env field of the container
// +optional
EnvOverriders []EnvOverrider `json:"envOverriders,omitempty"`
// CommandOverriders represents the rules dedicated to handling container command
// +optional
CommandOverriders []CommandArgsOverrider `json:"commandOverriders,omitempty"`
// ArgsOverriders represents the rules dedicated to handling container args
// +optional
ArgsOverriders []CommandArgsOverrider `json:"argsOverriders,omitempty"`
// ResourcesOverriders will override the resources field of the container
// +optional
ResourcesOverriders []ResourcesOverrider `json:"resourcesOverriders,omitempty"`
}
// CommandArgsOverrider represents the rules dedicated to handling command/args overrides.
type CommandArgsOverrider struct {
// The name of container
// +required
ContainerName string `json:"containerName"`
// Operator represents the operator which will apply on the command/args.
// +kubebuilder:validation:Enum=add;remove
// +required
Operator OverriderOperator `json:"operator"`
// Value to be applied to command/args.
// Items in Value which will be appended after command/args when Operator is 'add'.
// Items in Value which match in command/args will be deleted when Operator is 'remove'.
// If Value is empty, then the command/args will remain the same.
// +optional
Value []string `json:"value,omitempty"`
}
// EnvOverrider represents the rules dedicated to handling env overrides.
type EnvOverrider struct {
// The name of container
// +required
ContainerName string `json:"containerName"`
// Operator represents the operator which will apply on the env.
// +kubebuilder:validation:Enum=add;remove;replace
// +required
Operator OverriderOperator `json:"operator"`
// Value to be applied to env.
// Must not be empty when operator is 'add' or 'replace'.
// When the operator is 'remove', the matched value in env will be deleted
// and only the name of the value will be matched.
// If Value is empty, then the env will remain the same.
// +optional
Value []corev1.EnvVar `json:"value,omitempty"`
}
// ResourcesOverrider represents the rules dedicated to handling resources overrides.
type ResourcesOverrider struct {
// The name of container
// +required
ContainerName string `json:"containerName"`
// Value to be applied to resources.
// Must not be empty
// +required
Value corev1.ResourceRequirements `json:"value,omitempty"`
}
// ImageOverrider represents the rules dedicated to handling image overrides.
type ImageOverrider struct {
// Predicate filters images before applying the rule.
//
// Defaults to nil, in that case, the system will automatically detect image fields if the resource type is
// Pod, ReplicaSet, Deployment or StatefulSet by following rule:
// - Pod: /spec/containers/<N>/image
// - ReplicaSet: /spec/template/spec/containers/<N>/image
// - Deployment: /spec/template/spec/containers/<N>/image
// - StatefulSet: /spec/template/spec/containers/<N>/image
// In addition, all images will be processed if the resource object has more than one containers.
//
// If not nil, only images matches the filters will be processed.
// +optional
Predicate *ImagePredicate `json:"predicate,omitempty"`
// Component is part of image name.
// Basically we presume an image can be made of '[registry/]repository[:tag]'.
// The registry could be:
// - k8s.gcr.io
// - fictional.registry.example:10443
// The repository could be:
// - kube-apiserver
// - fictional/nginx
// The tag cloud be:
// - latest
// - v1.19.1
// - @sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c
//
// +kubebuilder:validation:Enum=Registry;Repository;Tag
// +required
Component ImageComponent `json:"component"`
// Operator represents the operator which will apply on the image.
// +kubebuilder:validation:Enum=add;remove;replace
// +required
Operator OverriderOperator `json:"operator"`
// Value to be applied to image.
// Must not be empty when operator is 'add' or 'replace'.
// Defaults to empty and ignored when operator is 'remove'.
// +optional
Value string `json:"value,omitempty"`
}
// ImagePredicate describes images filter.
type ImagePredicate struct {
// Path indicates the path of target field
// +required
Path string `json:"path"`
}
// ImageComponent indicates the components for image.
type ImageComponent string
const (
// Registry is the registry component of an image with format '[registry/]repository[:tag]'.
Registry ImageComponent = "Registry"
// Repository is the repository component of an image with format '[registry/]repository[:tag]'.
Repository ImageComponent = "Repository"
// Tag is the tag component of an image with format '[registry/]repository[:tag]'.
Tag ImageComponent = "Tag"
)
// OverriderOperator is the set of operators that can be used in an overrider.
type OverriderOperator string
// These are valid overrider operators.
const (
OverriderOpAdd OverriderOperator = "add"
OverriderOpRemove OverriderOperator = "remove"
OverriderOpReplace OverriderOperator = "replace"
)
// Manifest represents a resource to be deployed on managed node groups.
type Manifest struct {
// +kubebuilder:pruning:PreserveUnknownFields
runtime.RawExtension `json:",inline"`
}
// EdgeApplicationStatus defines the observed state of EdgeApplication
type EdgeApplicationStatus struct {
// WorkloadStatus contains running statuses of generated resources.
// +optional
WorkloadStatus []ManifestStatus `json:"workloadStatus,omitempty"`
}
// ManifestStatus contains running status of a specific manifest in spec.
type ManifestStatus struct {
// Identifier represents the identity of a resource linking to manifests in spec.
// +required
Identifier ResourceIdentifier `json:"identifier"`
// Conditions contain the different condition statuses for this manifest.
// Valid condition types are:
// 1. Processing: this workload is under processing and the current state of manifest does not match the desired.
// 2. Available: the current status of this workload matches the desired.
// +kubebuilder:validation:Enum=Processing;Available
// +optional
Condition ManifestCondition `json:"conditions,omitempty"`
}
// ResourceIdentifier provides the identifiers needed to interact with any arbitrary object.
type ResourceIdentifier struct {
// Ordinal represents an index in manifests list, so the condition can still be linked
// to a manifest even though manifest cannot be parsed successfully.
// +kubebuilder:validation:Minimum=0
// +required
Ordinal int `json:"ordinal"`
// Group is the group of the resource.
// +optional
Group string `json:"group,omitempty"`
// Version is the version of the resource.
// +optional
Version string `json:"version,omitempty"`
// Kind is the kind of the resource.
// +optional
Kind string `json:"kind,omitempty"`
// Resource is the resource type of the resource
// +optional
Resource string `json:"resource,omitempty"`
// Namespace is the namespace of the resource
// +optional
Namespace string `json:"namespace,omitempty"`
// Name is the name of the resource
// +optional
Name string `json:"name,omitempty"`
}
type ManifestCondition string
const (
// EdgeAppProcessing represents that the manifest is under processing and currently
// the status of this manifest does not match the desired.
EdgeAppProcessing ManifestCondition = "Processing"
// EdgeAppAvailable represents that the manifest has been applied successfully and the current
// status matches the desired.
EdgeAppAvailable ManifestCondition = "Available"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:shortName=eapp
// EdgeApplication is the Schema for the edgeapplications API
type EdgeApplication struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Spec represents the desired behavior of EdgeApplication.
// +required
Spec EdgeApplicationSpec `json:"spec,omitempty"`
// Status represents the status of PropagationStatus.
// +optional
Status EdgeApplicationStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// EdgeApplicationList contains a list of EdgeApplication
type EdgeApplicationList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []EdgeApplication `json:"items"`
}

View File

@ -0,0 +1,112 @@
/*
Copyright 2022 The KubeEdge 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 v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// NodeGroupSpec defines the desired state of NodeGroup
type NodeGroupSpec struct {
// Nodes contains names of all the nodes in the nodegroup.
// +optional
Nodes []string `json:"nodes,omitempty"`
// MatchLabels are used to select nodes that have these labels.
// +optional
MatchLabels map[string]string `json:"matchLabels,omitempty"`
}
// NodeGroupStatus contains the observed status of all selected nodes in
// this NodeGroup, including nodes that have been one of the members of this NodeGroup
// and those have not.
type NodeGroupStatus struct {
// NodeStatuses is a status list of all selected nodes.
// +optional
NodeStatuses []NodeStatus `json:"nodeStatuses,omitempty"`
}
// NodeStatus contains status of node that selected by this NodeGroup.
type NodeStatus struct {
// NodeName contains name of this node.
// +required
NodeName string `json:"nodeName"`
// ReadyStatus contains ready status of this node.
// +required
ReadyStatus ReadyStatus `json:"readyStatus"`
// SelectionStatus contains status of the selection result for this node.
// +required
SelectionStatus SelectionStatus `json:"selectionStatus"`
// SelectionStatusReason contains human-readable reason for this SelectionStatus.
// +optional
SelectionStatusReason string `json:"selectionStatusReason,omitempty"`
}
// ReadyStatus represents the healthy status of node.
type ReadyStatus string
const (
// NodeReady indicates that this node is ready.
NodeReady ReadyStatus = "Ready"
// NodeNotReady indicates that this node is not ready.
NodeNotReady ReadyStatus = "NotReady"
// Unknown indicates that the status of this node is unknown.
Unknown ReadyStatus = "Unknown"
)
// SelectionStatus represents the status of selecting a node as a member of this NodeGroup.
type SelectionStatus string
const (
// SucceededSelection represents that this node has been selected as a member of this NodeGroup.
SucceededSelection SelectionStatus = "Succeeded"
// FailedSelection represents that this node failed to become a member of this NodeGroup.
FailedSelection SelectionStatus = "Failed"
)
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Cluster,shortName=ng
// NodeGroup is the Schema for the nodegroups API
type NodeGroup struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Spec represents the specification of the desired behavior of member nodegroup.
// +required
Spec NodeGroupSpec `json:"spec,omitempty"`
// Status represents the status of member nodegroup.
// +optional
Status NodeGroupStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// NodeGroupList contains a list of NodeGroup
type NodeGroupList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []NodeGroup `json:"items"`
}

View File

@ -0,0 +1,69 @@
/*
Copyright The KubeEdge 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 register-gen. DO NOT EDIT.
package v1alpha1
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// GroupName specifies the group name used to register the objects.
const GroupName = "apps.kubeedge.io"
// GroupVersion specifies the group and the version used to register the objects.
var GroupVersion = v1.GroupVersion{Group: GroupName, Version: "v1alpha1"}
// SchemeGroupVersion is group version used to register these objects
// Deprecated: use GroupVersion instead.
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}
// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes.
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
// Depreciated: use Install instead
AddToScheme = localSchemeBuilder.AddToScheme
Install = localSchemeBuilder.AddToScheme
)
func init() {
// 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.
localSchemeBuilder.Register(addKnownTypes)
}
// Adds the list of known types to Scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&EdgeApplication{},
&EdgeApplicationList{},
&NodeGroup{},
&NodeGroupList{},
)
// AddToGroupVersion allows the serialization of client types like ListOptions.
v1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -0,0 +1,520 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The KubeEdge 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 deepcopy-gen. DO NOT EDIT.
package v1alpha1
import (
v1 "k8s.io/api/core/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *CommandArgsOverrider) DeepCopyInto(out *CommandArgsOverrider) {
*out = *in
if in.Value != nil {
in, out := &in.Value, &out.Value
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommandArgsOverrider.
func (in *CommandArgsOverrider) DeepCopy() *CommandArgsOverrider {
if in == nil {
return nil
}
out := new(CommandArgsOverrider)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EdgeApplication) DeepCopyInto(out *EdgeApplication) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeApplication.
func (in *EdgeApplication) DeepCopy() *EdgeApplication {
if in == nil {
return nil
}
out := new(EdgeApplication)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *EdgeApplication) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EdgeApplicationList) DeepCopyInto(out *EdgeApplicationList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]EdgeApplication, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeApplicationList.
func (in *EdgeApplicationList) DeepCopy() *EdgeApplicationList {
if in == nil {
return nil
}
out := new(EdgeApplicationList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *EdgeApplicationList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EdgeApplicationSpec) DeepCopyInto(out *EdgeApplicationSpec) {
*out = *in
in.WorkloadTemplate.DeepCopyInto(&out.WorkloadTemplate)
in.WorkloadScope.DeepCopyInto(&out.WorkloadScope)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeApplicationSpec.
func (in *EdgeApplicationSpec) DeepCopy() *EdgeApplicationSpec {
if in == nil {
return nil
}
out := new(EdgeApplicationSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EdgeApplicationStatus) DeepCopyInto(out *EdgeApplicationStatus) {
*out = *in
if in.WorkloadStatus != nil {
in, out := &in.WorkloadStatus, &out.WorkloadStatus
*out = make([]ManifestStatus, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EdgeApplicationStatus.
func (in *EdgeApplicationStatus) DeepCopy() *EdgeApplicationStatus {
if in == nil {
return nil
}
out := new(EdgeApplicationStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EnvOverrider) DeepCopyInto(out *EnvOverrider) {
*out = *in
if in.Value != nil {
in, out := &in.Value, &out.Value
*out = make([]v1.EnvVar, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EnvOverrider.
func (in *EnvOverrider) DeepCopy() *EnvOverrider {
if in == nil {
return nil
}
out := new(EnvOverrider)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImageOverrider) DeepCopyInto(out *ImageOverrider) {
*out = *in
if in.Predicate != nil {
in, out := &in.Predicate, &out.Predicate
*out = new(ImagePredicate)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageOverrider.
func (in *ImageOverrider) DeepCopy() *ImageOverrider {
if in == nil {
return nil
}
out := new(ImageOverrider)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImagePredicate) DeepCopyInto(out *ImagePredicate) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePredicate.
func (in *ImagePredicate) DeepCopy() *ImagePredicate {
if in == nil {
return nil
}
out := new(ImagePredicate)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Manifest) DeepCopyInto(out *Manifest) {
*out = *in
in.RawExtension.DeepCopyInto(&out.RawExtension)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Manifest.
func (in *Manifest) DeepCopy() *Manifest {
if in == nil {
return nil
}
out := new(Manifest)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ManifestStatus) DeepCopyInto(out *ManifestStatus) {
*out = *in
out.Identifier = in.Identifier
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManifestStatus.
func (in *ManifestStatus) DeepCopy() *ManifestStatus {
if in == nil {
return nil
}
out := new(ManifestStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeGroup) DeepCopyInto(out *NodeGroup) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeGroup.
func (in *NodeGroup) DeepCopy() *NodeGroup {
if in == nil {
return nil
}
out := new(NodeGroup)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *NodeGroup) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeGroupList) DeepCopyInto(out *NodeGroupList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]NodeGroup, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeGroupList.
func (in *NodeGroupList) DeepCopy() *NodeGroupList {
if in == nil {
return nil
}
out := new(NodeGroupList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *NodeGroupList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeGroupSpec) DeepCopyInto(out *NodeGroupSpec) {
*out = *in
if in.Nodes != nil {
in, out := &in.Nodes, &out.Nodes
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.MatchLabels != nil {
in, out := &in.MatchLabels, &out.MatchLabels
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeGroupSpec.
func (in *NodeGroupSpec) DeepCopy() *NodeGroupSpec {
if in == nil {
return nil
}
out := new(NodeGroupSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeGroupStatus) DeepCopyInto(out *NodeGroupStatus) {
*out = *in
if in.NodeStatuses != nil {
in, out := &in.NodeStatuses, &out.NodeStatuses
*out = make([]NodeStatus, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeGroupStatus.
func (in *NodeGroupStatus) DeepCopy() *NodeGroupStatus {
if in == nil {
return nil
}
out := new(NodeGroupStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeStatus) DeepCopyInto(out *NodeStatus) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeStatus.
func (in *NodeStatus) DeepCopy() *NodeStatus {
if in == nil {
return nil
}
out := new(NodeStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Overriders) DeepCopyInto(out *Overriders) {
*out = *in
if in.Replicas != nil {
in, out := &in.Replicas, &out.Replicas
*out = new(int)
**out = **in
}
if in.ImageOverriders != nil {
in, out := &in.ImageOverriders, &out.ImageOverriders
*out = make([]ImageOverrider, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.EnvOverriders != nil {
in, out := &in.EnvOverriders, &out.EnvOverriders
*out = make([]EnvOverrider, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.CommandOverriders != nil {
in, out := &in.CommandOverriders, &out.CommandOverriders
*out = make([]CommandArgsOverrider, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.ArgsOverriders != nil {
in, out := &in.ArgsOverriders, &out.ArgsOverriders
*out = make([]CommandArgsOverrider, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.ResourcesOverriders != nil {
in, out := &in.ResourcesOverriders, &out.ResourcesOverriders
*out = make([]ResourcesOverrider, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Overriders.
func (in *Overriders) DeepCopy() *Overriders {
if in == nil {
return nil
}
out := new(Overriders)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceIdentifier) DeepCopyInto(out *ResourceIdentifier) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceIdentifier.
func (in *ResourceIdentifier) DeepCopy() *ResourceIdentifier {
if in == nil {
return nil
}
out := new(ResourceIdentifier)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceTemplate) DeepCopyInto(out *ResourceTemplate) {
*out = *in
if in.Manifests != nil {
in, out := &in.Manifests, &out.Manifests
*out = make([]Manifest, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceTemplate.
func (in *ResourceTemplate) DeepCopy() *ResourceTemplate {
if in == nil {
return nil
}
out := new(ResourceTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourcesOverrider) DeepCopyInto(out *ResourcesOverrider) {
*out = *in
in.Value.DeepCopyInto(&out.Value)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourcesOverrider.
func (in *ResourcesOverrider) DeepCopy() *ResourcesOverrider {
if in == nil {
return nil
}
out := new(ResourcesOverrider)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TargetNodeGroup) DeepCopyInto(out *TargetNodeGroup) {
*out = *in
in.Overriders.DeepCopyInto(&out.Overriders)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TargetNodeGroup.
func (in *TargetNodeGroup) DeepCopy() *TargetNodeGroup {
if in == nil {
return nil
}
out := new(TargetNodeGroup)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkloadScope) DeepCopyInto(out *WorkloadScope) {
*out = *in
if in.TargetNodeGroups != nil {
in, out := &in.TargetNodeGroups, &out.TargetNodeGroups
*out = make([]TargetNodeGroup, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadScope.
func (in *WorkloadScope) DeepCopy() *WorkloadScope {
if in == nil {
return nil
}
out := new(WorkloadScope)
in.DeepCopyInto(out)
return out
}

View File

@ -0,0 +1,106 @@
package constants
import (
"time"
)
// Resources
const (
DefaultServiceAccountIssuer = "https://kubernetes.default.svc.cluster.local"
// Edged
DefaultDockerAddress = "unix:///var/run/docker.sock"
DefaultRuntimeType = "remote"
DefaultEdgedMemoryCapacity = 7852396000
// update PodSandboxImage version when bumping k8s vendor version, consistent with vendor/k8s.io/kubernetes/cmd/kubelet/app/options/container_runtime.go defaultPodSandboxImageVersion
// When this value are updated, also update comments in pkg/apis/componentconfig/edgecore/v1alpha1/types.go
DefaultPodSandboxImage = "kubeedge/pause:3.6"
DefaultImagePullProgressDeadline = time.Minute
DefaultImageGCHighThreshold = 80
DefaultImageGCLowThreshold = 40
DefaultMaximumDeadContainersPerPod = 1
DefaultHostnameOverride = "default-edge-node"
DefaultRegisterNodeNamespace = "default"
DefaultNetworkPluginMTU = 1500
DefaultConcurrentConsumers = 5
DefaultCgroupRoot = ""
DefaultVolumeStatsAggPeriod = time.Minute
DefaultTunnelPort = 10004
DefaultClusterDomain = "cluster.local"
// MetaManager
DefaultRemoteQueryTimeout = 60
DefaultMetaServerAddr = "127.0.0.1:10550"
DefaultDummyServerAddr = "169.254.30.10:10550"
// Config
DefaultKubeContentType = "application/vnd.kubernetes.protobuf"
DefaultNodeLimit = 500
// EdgeController
DefaultUpdatePodStatusWorkers = 1
DefaultUpdateNodeStatusWorkers = 1
DefaultProcessEventWorkers = 4
DefaultQueryConfigMapWorkers = 100
DefaultQuerySecretWorkers = 100
DefaultQueryPersistentVolumeWorkers = 4
DefaultQueryPersistentVolumeClaimWorkers = 4
DefaultQueryVolumeAttachmentWorkers = 4
DefaultCreateNodeWorkers = 100
DefaultUpdateNodeWorkers = 4
DefaultPatchPodWorkers = 100
DefaultDeletePodWorkers = 100
DefaultUpdateRuleStatusWorkers = 4
DefaultQueryLeaseWorkers = 100
DefaultServiceAccountTokenWorkers = 100
DefaultCreatePodWorkers = 4
DefaultCertificateSigningRequestWorkers = 4
DefaultUpdatePodStatusBuffer = 1024
DefaultProcessEventBuffer = 1024
DefaultUpdateNodeStatusBuffer = 1024
DefaultQueryConfigMapBuffer = 1024
DefaultQuerySecretBuffer = 1024
DefaultQueryPersistentVolumeBuffer = 1024
DefaultQueryPersistentVolumeClaimBuffer = 1024
DefaultQueryVolumeAttachmentBuffer = 1024
DefaultCreateNodeBuffer = 1024
DefaultUpdateNodeBuffer = 1024
DefaultPatchPodBuffer = 1024
DefaultDeletePodBuffer = 1024
DefaultQueryLeaseBuffer = 1024
DefaultServiceAccountTokenBuffer = 1024
DefaultCreatePodBuffer = 1024
DefaultCertificateSigningRequestBuffer = 1024
DefaultPodEventBuffer = 1
DefaultConfigMapEventBuffer = 1
DefaultSecretEventBuffer = 1
DefaultRulesEventBuffer = 1
DefaultRuleEndpointsEventBuffer = 1
// DeviceController
DefaultUpdateDeviceTwinsBuffer = 1024
DefaultUpdateDeviceStatesBuffer = 1024
DefaultDeviceEventBuffer = 1
DefaultDeviceModelEventBuffer = 1
DefaultUpdateDeviceStatusWorkers = 1
// TaskManager
DefaultNodeUpgradeJobStatusBuffer = 1024
DefaultNodeUpgradeJobEventBuffer = 1
DefaultNodeUpgradeJobWorkers = 1
ServerAddress = "127.0.0.1"
// ServerPort is the default port for the edgecore server on each host machine.
// May be overridden by a flag at startup in the future.
ServerPort = 10350
// MessageSuccessfulContent is the successful content value of Message struct
DefaultQPS = 30
DefaultBurst = 60
// DeviceTwin
DefaultDMISockPath = "/etc/kubeedge/dmi.sock"
)

View File

@ -0,0 +1,36 @@
//go:build !windows
package constants
// Resources
const (
// Certificates
DefaultConfigDir = "/etc/kubeedge/config/"
DefaultCAFile = "/etc/kubeedge/ca/rootCA.crt"
DefaultCAKeyFile = "/etc/kubeedge/ca/rootCA.key"
DefaultCertFile = "/etc/kubeedge/certs/server.crt"
DefaultKeyFile = "/etc/kubeedge/certs/server.key"
DefaultStreamCAFile = "/etc/kubeedge/ca/streamCA.crt"
DefaultStreamCertFile = "/etc/kubeedge/certs/stream.crt"
DefaultStreamKeyFile = "/etc/kubeedge/certs/stream.key"
DefaultMqttCAFile = "/etc/kubeedge/ca/rootCA.crt"
DefaultMqttCertFile = "/etc/kubeedge/certs/server.crt"
DefaultMqttKeyFile = "/etc/kubeedge/certs/server.key"
// Bootstrap file, contains token used by edgecore to apply for ca/cert
BootstrapFile = "/etc/kubeedge/bootstrap-edgecore.conf"
// Edged
DefaultRootDir = "/var/lib/edged"
DefaultRemoteRuntimeEndpoint = "unix:///run/containerd/containerd.sock"
DefaultRemoteImageEndpoint = "unix:///run/containerd/containerd.sock"
DefaultCNIConfDir = "/etc/cni/net.d"
DefaultCNIBinDir = "/opt/cni/bin"
DefaultCNICacheDir = "/var/lib/cni/cache"
DefaultVolumePluginDir = "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/"
// DefaultManifestsDir edge node default static pod path
DefaultManifestsDir = "/etc/kubeedge/manifests"
)

View File

@ -0,0 +1,39 @@
//go:build windows
package constants
// Module name and group name
const ()
// Resources
const (
// Certificates
DefaultConfigDir = "c:\\etc\\kubeedge\\config\\"
DefaultCAFile = "c:\\etc\\kubeedge\\ca\\rootCA.crt"
DefaultCAKeyFile = "c:\\etc\\kubeedge\\ca\\rootCA.key"
DefaultCertFile = "c:\\etc\\kubeedge\\certs\\server.crt"
DefaultKeyFile = "c:\\etc\\kubeedge\\certs\\server.key"
DefaultStreamCAFile = "c:\\etc\\kubeedge\\ca\\streamCA.crt"
DefaultStreamCertFile = "c:\\etc\\kubeedge\\certs\\stream.crt"
DefaultStreamKeyFile = "c:\\etc\\kubeedge\\certs\\stream.key"
DefaultMqttCAFile = "c:\\etc\\kubeedge\\ca\\rootCA.crt"
DefaultMqttCertFile = "c:\\etc\\kubeedge\\certs\\server.crt"
DefaultMqttKeyFile = "c:\\etc\\kubeedge\\certs\\server.key"
// Bootstrap file, contains token used by edgecore to apply for ca/cert
BootstrapFile = "c:\\etc\\kubeedge\\bootstrap-edgecore.conf"
// Edged
DefaultRootDir = "c:\\var\\lib\\edged"
DefaultRemoteRuntimeEndpoint = "npipe://./pipe/containerd-containerd"
DefaultRemoteImageEndpoint = "npipe://./pipe/containerd-containerd"
DefaultCNIConfDir = "c:\\etc\\cni\\net.d"
DefaultCNIBinDir = "c:\\opt\\cni\\bin"
DefaultCNICacheDir = "c:\\var\\lib\\cni\\cache"
DefaultVolumePluginDir = "C:\\usr\\libexec\\kubernetes\\kubelet-plugins\\volume\\exec\\"
// DefaultManifestsDir edge node default static pod path
DefaultManifestsDir = "c:\\etc\\kubeedge\\manifests\\"
)

24
apis/common/types/http.go Normal file
View File

@ -0,0 +1,24 @@
package types
import "net/http"
// HTTPRequest is used structure used to unmarshal message content from cloud
type HTTPRequest struct {
Header http.Header `json:"header"`
Body []byte `json:"body"`
Method string `json:"method"`
URL string `json:"url"`
}
// HTTPResponse is HTTP request's response structure used to send response to cloud
type HTTPResponse struct {
Header http.Header `json:"header"`
StatusCode int `json:"status_code"`
Body []byte `json:"body"`
}
const (
HeaderAuthorization = "Authorization"
HeaderNodeName = "NodeName"
HeaderExtKeyUsages = "ExtKeyUsages"
)

112
apis/common/types/types.go Normal file
View File

@ -0,0 +1,112 @@
package types
import (
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
api "github.com/kubeedge/api/apis/fsm/v1alpha1"
"github.com/kubeedge/api/apis/operations/v1alpha1"
)
// PodStatusRequest is Message.Content which comes from edge
type PodStatusRequest struct {
UID types.UID
Name string
Status v1.PodStatus
}
// ExtendResource is the extended resource detail that comes from edge
type ExtendResource struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Capacity resource.Quantity `json:"capacity,omitempty"`
}
// NodeStatusRequest is Message.Content which comes from edge
type NodeStatusRequest struct {
UID types.UID
Status v1.NodeStatus
ExtendResources map[v1.ResourceName][]ExtendResource
}
// NodeUpgradeJobRequest is upgrade msg coming from cloud to edge
type NodeUpgradeJobRequest struct {
UpgradeID string
HistoryID string
Version string
UpgradeTool string
Image string
}
// NodeUpgradeJobResponse is used to report status msg to cloudhub https service
type NodeUpgradeJobResponse struct {
UpgradeID string
HistoryID string
NodeName string
FromVersion string
ToVersion string
Status string
Reason string
}
// NodePreCheckRequest is pre-check msg coming from cloud to edge
type NodePreCheckRequest struct {
CheckItem []string
}
type NodeTaskRequest struct {
TaskID string
Type string
State string
Item interface{}
}
type NodeTaskResponse struct {
// NodeName is the name of edge node.
NodeName string
// State represents for the upgrade state phase of the edge node.
// There are several possible state values: "", Upgrading, BackingUp, RollingBack and Checking.
State api.State
// Event represents for the event of the ImagePrePullJob.
// There are three possible event values: Init, Check, Pull.
Event string
// Action represents for the action of the ImagePrePullJob.
// There are three possible action values: Success, Failure, TimeOut.
Action api.Action
// Reason represents for the reason of the ImagePrePullJob.
Reason string
// Time represents for the running time of the ImagePrePullJob.
Time string
ExternalMessage string
}
// ObjectResp is the object that api-server response
type ObjectResp struct {
Object metaV1.Object
Err error
}
// ImagePrePullJobRequest is image prepull msg from cloud to edge
type ImagePrePullJobRequest struct {
Images []string
NodeName string
Secret string
RetryTimes int32
CheckItems []string
}
// ImagePrePullJobResponse is used to report status msg to cloudhub https service from each node
type ImagePrePullJobResponse struct {
NodeName string
State string
Reason string
ImageStatus []v1alpha1.ImageStatus
}
type RestartResponse struct {
ErrMessages []string `json:"errMessages,omitempty"`
LogMessages []string `json:"LogMessages,omitempty"`
}

View File

@ -0,0 +1,9 @@
approvers:
- fisherxu
- kadisi
- kevin-wangzefeng
reviewers:
- fisherxu
- kadisi
- kevin-wangzefeng
- kuramal

View File

@ -0,0 +1,305 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
import (
"path"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilnet "k8s.io/apimachinery/pkg/util/net"
"github.com/kubeedge/api/apis/common/constants"
)
// NewDefaultCloudCoreConfig returns a full CloudCoreConfig object
func NewDefaultCloudCoreConfig() *CloudCoreConfig {
advertiseAddress, _ := utilnet.ChooseHostInterface()
c := &CloudCoreConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
CommonConfig: &CommonConfig{
TunnelPort: constants.ServerPort,
MonitorServer: MonitorServer{
BindAddress: "127.0.0.1:9091",
EnableProfiling: false,
},
},
KubeAPIConfig: &KubeAPIConfig{
ContentType: constants.DefaultKubeContentType,
QPS: 5 * constants.DefaultNodeLimit,
Burst: 10 * constants.DefaultNodeLimit,
},
Modules: &Modules{
CloudHub: &CloudHub{
Enable: true,
KeepaliveInterval: 30,
NodeLimit: constants.DefaultNodeLimit,
TLSCAFile: constants.DefaultCAFile,
TLSCAKeyFile: constants.DefaultCAKeyFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
WriteTimeout: 30,
AdvertiseAddress: []string{advertiseAddress.String()},
DNSNames: []string{""},
EdgeCertSigningDuration: 365,
TokenRefreshDuration: 12,
Quic: &CloudHubQUIC{
Enable: false,
Address: "0.0.0.0",
Port: 10001,
MaxIncomingStreams: 10000,
},
UnixSocket: &CloudHubUnixSocket{
Enable: true,
Address: "unix:///var/lib/kubeedge/kubeedge.sock",
},
WebSocket: &CloudHubWebSocket{
Enable: true,
Port: 10000,
Address: "0.0.0.0",
},
HTTPS: &CloudHubHTTPS{
Enable: true,
Port: 10002,
Address: "0.0.0.0",
},
Authorization: &CloudHubAuthorization{
Enable: false,
Debug: true,
Modes: []AuthorizationMode{
{
Node: &NodeAuthorization{
Enable: true,
},
},
},
},
},
EdgeController: &EdgeController{
Enable: true,
NodeUpdateFrequency: 10,
Buffer: getDefaultEdgeControllerBuffer(constants.DefaultNodeLimit),
Load: getDefaultEdgeControllerLoad(constants.DefaultNodeLimit),
},
DeviceController: &DeviceController{
Enable: true,
Buffer: &DeviceControllerBuffer{
UpdateDeviceTwins: constants.DefaultUpdateDeviceTwinsBuffer,
UpdateDeviceStates: constants.DefaultUpdateDeviceStatesBuffer,
DeviceEvent: constants.DefaultDeviceEventBuffer,
DeviceModelEvent: constants.DefaultDeviceModelEventBuffer,
},
Load: &DeviceControllerLoad{
UpdateDeviceStatusWorkers: constants.DefaultUpdateDeviceStatusWorkers,
},
},
TaskManager: &TaskManager{
Enable: false,
Buffer: &TaskManagerBuffer{
TaskStatus: constants.DefaultNodeUpgradeJobStatusBuffer,
TaskEvent: constants.DefaultNodeUpgradeJobEventBuffer,
},
Load: &TaskManagerLoad{
TaskWorkers: constants.DefaultNodeUpgradeJobWorkers,
},
},
SyncController: &SyncController{
Enable: true,
},
DynamicController: &DynamicController{
Enable: false,
},
CloudStream: &CloudStream{
Enable: false,
TLSTunnelCAFile: constants.DefaultCAFile,
TLSTunnelCertFile: constants.DefaultCertFile,
TLSTunnelPrivateKeyFile: constants.DefaultKeyFile,
TunnelPort: constants.DefaultTunnelPort,
TLSStreamCAFile: constants.DefaultStreamCAFile,
TLSStreamCertFile: constants.DefaultStreamCertFile,
TLSStreamPrivateKeyFile: constants.DefaultStreamKeyFile,
StreamPort: 10003,
},
Router: &Router{
Enable: false,
Address: "0.0.0.0",
Port: 9443,
RestTimeout: 60,
},
IptablesManager: &IptablesManager{
Enable: true,
Mode: InternalMode,
},
},
}
return c
}
// NodeLimit is a maximum number of edge node that can connect to the single CloudCore
// instance. You should take this parameter seriously, because this parameter is closely
// related to the number of goroutines for upstream message processing.
// getDefaultEdgeControllerLoad return Default EdgeControllerLoad based on nodeLimit
func getDefaultEdgeControllerLoad(nodeLimit int32) *EdgeControllerLoad {
return &EdgeControllerLoad{
UpdatePodStatusWorkers: constants.DefaultUpdatePodStatusWorkers,
UpdateNodeStatusWorkers: constants.DefaultUpdateNodeStatusWorkers,
QueryConfigMapWorkers: constants.DefaultQueryConfigMapWorkers,
ProcessEventWorkers: constants.DefaultProcessEventWorkers,
QuerySecretWorkers: constants.DefaultQuerySecretWorkers,
QueryPersistentVolumeWorkers: constants.DefaultQueryPersistentVolumeWorkers,
QueryPersistentVolumeClaimWorkers: constants.DefaultQueryPersistentVolumeClaimWorkers,
QueryVolumeAttachmentWorkers: constants.DefaultQueryVolumeAttachmentWorkers,
QueryNodeWorkers: nodeLimit,
CreateNodeWorkers: constants.DefaultCreateNodeWorkers,
PatchNodeWorkers: 100 + nodeLimit/50,
UpdateNodeWorkers: constants.DefaultUpdateNodeWorkers,
PatchPodWorkers: constants.DefaultPatchPodWorkers,
DeletePodWorkers: constants.DefaultDeletePodWorkers,
CreateLeaseWorkers: nodeLimit,
QueryLeaseWorkers: constants.DefaultQueryLeaseWorkers,
UpdateRuleStatusWorkers: constants.DefaultUpdateRuleStatusWorkers,
ServiceAccountTokenWorkers: constants.DefaultServiceAccountTokenWorkers,
CreatePodWorks: constants.DefaultCreatePodWorkers,
CertificateSigningRequestWorkers: constants.DefaultCertificateSigningRequestWorkers,
}
}
// getDefaultEdgeControllerBuffer return Default EdgeControllerBuffer based on nodeLimit
func getDefaultEdgeControllerBuffer(nodeLimit int32) *EdgeControllerBuffer {
return &EdgeControllerBuffer{
UpdatePodStatus: constants.DefaultUpdatePodStatusBuffer,
ProcessEvent: constants.DefaultProcessEventBuffer,
UpdateNodeStatus: constants.DefaultUpdateNodeStatusBuffer,
QueryConfigMap: constants.DefaultQueryConfigMapBuffer,
QuerySecret: constants.DefaultQuerySecretBuffer,
PodEvent: constants.DefaultPodEventBuffer,
ConfigMapEvent: constants.DefaultConfigMapEventBuffer,
SecretEvent: constants.DefaultSecretEventBuffer,
RulesEvent: constants.DefaultRulesEventBuffer,
RuleEndpointsEvent: constants.DefaultRuleEndpointsEventBuffer,
QueryPersistentVolume: constants.DefaultQueryPersistentVolumeBuffer,
QueryPersistentVolumeClaim: constants.DefaultQueryPersistentVolumeClaimBuffer,
QueryVolumeAttachment: constants.DefaultQueryVolumeAttachmentBuffer,
CreateNode: constants.DefaultCreateNodeBuffer,
PatchNode: 1024 + nodeLimit/2,
QueryNode: 1024 + nodeLimit,
UpdateNode: constants.DefaultUpdateNodeBuffer,
PatchPod: constants.DefaultPatchPodBuffer,
DeletePod: constants.DefaultDeletePodBuffer,
CreateLease: 1024 + nodeLimit,
QueryLease: constants.DefaultQueryLeaseBuffer,
ServiceAccountToken: constants.DefaultServiceAccountTokenBuffer,
CreatePod: constants.DefaultCreatePodBuffer,
CertificateSigningRequest: constants.DefaultCertificateSigningRequestBuffer,
}
}
func AdjustCloudCoreConfig(c *CloudCoreConfig) bool {
changed := false
nodeLimit := c.Modules.CloudHub.NodeLimit
if c.KubeAPIConfig.QPS != 5*nodeLimit {
changed = true
c.KubeAPIConfig.QPS = 5 * nodeLimit
}
if c.KubeAPIConfig.Burst != 10*nodeLimit {
changed = true
c.KubeAPIConfig.Burst = 10 * nodeLimit
}
if c.Modules.EdgeController.Load.QueryNodeWorkers < nodeLimit {
changed = true
c.Modules.EdgeController.Load.QueryNodeWorkers = nodeLimit
}
if c.Modules.EdgeController.Load.PatchNodeWorkers < 100+nodeLimit/50 {
changed = true
c.Modules.EdgeController.Load.PatchNodeWorkers = 100 + nodeLimit/50
}
if c.Modules.EdgeController.Load.CreateLeaseWorkers < nodeLimit {
changed = true
c.Modules.EdgeController.Load.CreateLeaseWorkers = nodeLimit
}
if c.Modules.EdgeController.Buffer.PatchNode < 1024+nodeLimit/2 {
changed = true
c.Modules.EdgeController.Buffer.PatchNode = 1024 + nodeLimit/2
}
if c.Modules.EdgeController.Buffer.QueryNode < 1024+nodeLimit {
changed = true
c.Modules.EdgeController.Buffer.QueryNode = 1024 + nodeLimit
}
if c.Modules.EdgeController.Buffer.CreateLease < 1024+nodeLimit {
changed = true
c.Modules.EdgeController.Buffer.CreateLease = 1024 + nodeLimit
}
return changed
}
// NewMinCloudCoreConfig returns a min CloudCoreConfig object
func NewMinCloudCoreConfig() *CloudCoreConfig {
advertiseAddress, _ := utilnet.ChooseHostInterface()
return &CloudCoreConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
Modules: &Modules{
CloudHub: &CloudHub{
NodeLimit: 1000,
TLSCAFile: constants.DefaultCAFile,
TLSCAKeyFile: constants.DefaultCAKeyFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
AdvertiseAddress: []string{advertiseAddress.String()},
UnixSocket: &CloudHubUnixSocket{
Enable: true,
Address: "unix:///var/lib/kubeedge/kubeedge.sock",
},
WebSocket: &CloudHubWebSocket{
Enable: true,
Port: 10000,
Address: "0.0.0.0",
},
HTTPS: &CloudHubHTTPS{
Enable: true,
Port: 10002,
Address: "0.0.0.0",
},
},
Router: &Router{
Enable: false,
Address: "0.0.0.0",
Port: 9443,
RestTimeout: 60,
},
IptablesManager: &IptablesManager{
Enable: true,
Mode: InternalMode,
},
},
}
}

View File

@ -0,0 +1,70 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
import (
"encoding/json"
"errors"
"os"
"k8s.io/klog/v2"
"sigs.k8s.io/yaml"
)
type IptablesMgrMode string
const (
InternalMode IptablesMgrMode = "internal"
ExternalMode IptablesMgrMode = "external"
)
func (c *CloudCoreConfig) Parse(filename string) error {
data, err := os.ReadFile(filename)
if err != nil {
klog.Errorf("Failed to read configfile %s: %v", filename, err)
return err
}
err = yaml.Unmarshal(data, c)
if err != nil {
klog.Errorf("Failed to unmarshal configfile %s: %v", filename, err)
return err
}
return nil
}
func (in *IptablesManager) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return nil
}
// Define a secondary type so that we don't end up with a recursive call to json.Unmarshal
type IM IptablesManager
var out = (*IM)(in)
err := json.Unmarshal(data, &out)
if err != nil {
return err
}
// Validate the valid enum values
switch in.Mode {
case InternalMode, ExternalMode:
return nil
default:
in.Mode = ""
return errors.New("invalid value for iptablesmgr mode")
}
}

View File

@ -0,0 +1,23 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
const (
GroupName = "cloudcore.config.kubeedge.io"
APIVersion = "v1alpha1"
Kind = "CloudCore"
)

View File

@ -0,0 +1,552 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
import (
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// CloudCoreConfig indicates the config of cloudCore which get from cloudCore config file
type CloudCoreConfig struct {
metav1.TypeMeta
// CommonConfig indicates common config for all modules
// +Required
CommonConfig *CommonConfig `json:"commonConfig,omitempty"`
// KubeAPIConfig indicates the kubernetes cluster info which cloudCore will connected
// +Required
KubeAPIConfig *KubeAPIConfig `json:"kubeAPIConfig,omitempty"`
// Modules indicates cloudCore modules config
// +Required
Modules *Modules `json:"modules,omitempty"`
// FeatureGates is a map of feature names to bools that enable or disable alpha/experimental features.
FeatureGates map[string]bool `json:"featureGates,omitempty"`
}
// CommonConfig indicates common config for all modules
type CommonConfig struct {
// TunnelPort indicates the port that the cloudcore tunnel listened
TunnelPort int `json:"tunnelPort,omitempty"`
// MonitorServer holds config that exposes prometheus metrics and pprof
MonitorServer MonitorServer `json:"monitorServer,omitempty"`
}
// MonitorServer indicates MonitorServer config
type MonitorServer struct {
// BindAddress is the IP address and port for the monitor server to serve on,
// defaulting to 127.0.0.1:9091 (set to 0.0.0.0 for all interfaces)
BindAddress string `json:"bindAddress,omitempty"`
// EnableProfiling enables profiling via web interface on /debug/pprof handler.
// Profiling handlers will be handled by monitor server.
EnableProfiling bool `json:"enableProfiling,omitempty"`
}
// KubeAPIConfig indicates the configuration for interacting with k8s server
type KubeAPIConfig struct {
// Master indicates the address of the Kubernetes API server (overrides any value in KubeConfig)
// such as https://127.0.0.1:8443
// default ""
// Note: Can not use "omitempty" option, It will affect the output of the default configuration file
Master string `json:"master"`
// ContentType indicates the ContentType of message transmission when interacting with k8s
// default "application/vnd.kubernetes.protobuf"
ContentType string `json:"contentType,omitempty"`
// QPS to while talking with kubernetes apiserver
// default 100
QPS int32 `json:"qps,omitempty"`
// Burst to use while talking with kubernetes apiserver
// default 200
Burst int32 `json:"burst,omitempty"`
// KubeConfig indicates the path to kubeConfig file with authorization and master location information.
// default "/root/.kube/config"
// +Required
KubeConfig string `json:"kubeConfig"`
}
// Modules indicates the modules of CloudCore will be use
type Modules struct {
// CloudHub indicates CloudHub module config
CloudHub *CloudHub `json:"cloudHub,omitempty"`
// EdgeController indicates EdgeController module config
EdgeController *EdgeController `json:"edgeController,omitempty"`
// DeviceController indicates DeviceController module config
DeviceController *DeviceController `json:"deviceController,omitempty"`
// TaskManager indicates TaskManager module config
TaskManager *TaskManager `json:"taskManager,omitempty"`
// SyncController indicates SyncController module config
SyncController *SyncController `json:"syncController,omitempty"`
// DynamicController indicates DynamicController module config
DynamicController *DynamicController `json:"dynamicController,omitempty"`
// CloudStream indicates cloudstream module config
CloudStream *CloudStream `json:"cloudStream,omitempty"`
// Router indicates router module config
Router *Router `json:"router,omitempty"`
// IptablesManager indicates iptables module config
IptablesManager *IptablesManager `json:"iptablesManager,omitempty"`
}
// CloudHub indicates the config of CloudHub module.
// CloudHub is a web socket or quic server responsible for watching changes at the cloud side,
// caching and sending messages to EdgeHub.
type CloudHub struct {
// Enable indicates whether CloudHub is enabled, if set to false (for debugging etc.),
// skip checking other CloudHub configs.
// default true
Enable bool `json:"enable"`
// KeepaliveInterval indicates keep-alive interval (second)
// default 30
KeepaliveInterval int32 `json:"keepaliveInterval,omitempty"`
// NodeLimit is a maximum number of edge node that can connect to the single CloudCore
// default 1000
NodeLimit int32 `json:"nodeLimit,omitempty"`
// TLSCAFile indicates ca file path
// default "/etc/kubeedge/ca/rootCA.crt"
TLSCAFile string `json:"tlsCAFile,omitempty"`
// TLSCAKeyFile indicates caKey file path
// default "/etc/kubeedge/ca/rootCA.key"
TLSCAKeyFile string `json:"tlsCAKeyFile,omitempty"`
// TLSPrivateKeyFile indicates key file path
// default "/etc/kubeedge/certs/server.crt"
TLSCertFile string `json:"tlsCertFile,omitempty"`
// TLSPrivateKeyFile indicates key file path
// default "/etc/kubeedge/certs/server.key"
TLSPrivateKeyFile string `json:"tlsPrivateKeyFile,omitempty"`
// WriteTimeout indicates write time (second)
// default 30
WriteTimeout int32 `json:"writeTimeout,omitempty"`
// Quic indicates quic server info
Quic *CloudHubQUIC `json:"quic,omitempty"`
// UnixSocket set unixsocket server info
UnixSocket *CloudHubUnixSocket `json:"unixsocket,omitempty"`
// WebSocket indicates websocket server info
// +Required
WebSocket *CloudHubWebSocket `json:"websocket,omitempty"`
// HTTPS indicates https server info
// +Required
HTTPS *CloudHubHTTPS `json:"https,omitempty"`
// AdvertiseAddress sets the IP address for the cloudcore to advertise.
AdvertiseAddress []string `json:"advertiseAddress,omitempty"`
// DNSNames sets the DNSNames for CloudCore.
DNSNames []string `json:"dnsNames,omitempty"`
// EdgeCertSigningDuration indicates the validity period of edge certificate
// default 365d
EdgeCertSigningDuration time.Duration `json:"edgeCertSigningDuration,omitempty"`
// TokenRefreshDuration indicates the interval of cloudcore token refresh, unit is hour
// default 12h
TokenRefreshDuration time.Duration `json:"tokenRefreshDuration,omitempty"`
// Authorization authz configurations
Authorization *CloudHubAuthorization `json:"authorization,omitempty"`
}
// CloudHubQUIC indicates the quic server config
type CloudHubQUIC struct {
// Enable indicates whether enable quic protocol
// default false
Enable bool `json:"enable"`
// Address set server ip address
// default 0.0.0.0
Address string `json:"address,omitempty"`
// Port set open port for quic server
// default 10001
Port uint32 `json:"port,omitempty"`
// MaxIncomingStreams set the max incoming stream for quic server
// default 10000
MaxIncomingStreams int32 `json:"maxIncomingStreams,omitempty"`
}
// CloudHubUnixSocket indicates the unix socket config
type CloudHubUnixSocket struct {
// Enable indicates whether enable unix domain socket protocol
// default true
Enable bool `json:"enable"`
// Address indicates unix domain socket address
// default "unix:///var/lib/kubeedge/kubeedge.sock"
Address string `json:"address,omitempty"`
}
// CloudHubWebSocket indicates the websocket config of CloudHub
type CloudHubWebSocket struct {
// Enable indicates whether enable websocket protocol
// default true
Enable bool `json:"enable"`
// Address indicates server ip address
// default 0.0.0.0
Address string `json:"address,omitempty"`
// Port indicates the open port for websocket server
// default 10000
Port uint32 `json:"port,omitempty"`
}
// CloudHubHTTPS indicates the http config of CloudHub
type CloudHubHTTPS struct {
// Enable indicates whether enable Https protocol
// default true
Enable bool `json:"enable"`
// Address indicates server ip address
// default 0.0.0.0
Address string `json:"address,omitempty"`
// Port indicates the open port for HTTPS server
// default 10002
Port uint32 `json:"port,omitempty"`
}
// CloudHubAuthorization CloudHub authz configurations
type CloudHubAuthorization struct {
// Enable indicates whether enable CloudHub Authorization
// default false
Enable bool `json:"enable"`
// Debug only logs errors but always allow messages
// default false
Debug bool `json:"debug"`
// Modes a list of authorization modes will be used
// default node
Modes []AuthorizationMode `json:"modes"`
}
// AuthorizationMode indicates an authorization mdoe
type AuthorizationMode struct {
// Node node authorization
Node *NodeAuthorization `json:"node,omitempty"`
}
// NodeAuthorization node authorization
type NodeAuthorization struct {
// Enable enables node authorization
// default true
Enable bool `json:"enable"`
}
// EdgeController indicates the config of EdgeController module
type EdgeController struct {
// Enable indicates whether EdgeController is enabled,
// if set to false (for debugging etc.), skip checking other EdgeController configs.
// default true
Enable bool `json:"enable"`
// NodeUpdateFrequency indicates node update frequency (second)
// default 10
NodeUpdateFrequency int32 `json:"nodeUpdateFrequency,omitempty"`
// Buffer indicates k8s resource buffer
Buffer *EdgeControllerBuffer `json:"buffer,omitempty"`
// Load indicates EdgeController load
Load *EdgeControllerLoad `json:"load,omitempty"`
}
// EdgeControllerBuffer indicates the EdgeController buffer
type EdgeControllerBuffer struct {
// ProcessEvent indicates the buffer of process event
// default 1024
ProcessEvent int32 `json:"processEvent,omitempty"`
// UpdatePodStatus indicates the buffer of update pod status
// default 1024
UpdatePodStatus int32 `json:"updatePodStatus,omitempty"`
// UpdateNodeStatus indicates the buffer of update node status
// default 1024
UpdateNodeStatus int32 `json:"updateNodeStatus,omitempty"`
// QueryConfigMap indicates the buffer of query configMap
// default 1024
QueryConfigMap int32 `json:"queryConfigMap,omitempty"`
// QuerySecret indicates the buffer of query secret
// default 1024
QuerySecret int32 `json:"querySecret,omitempty"`
// PodEvent indicates the buffer of pod event
// default 1
PodEvent int32 `json:"podEvent,omitempty"`
// ConfigMapEvent indicates the buffer of configMap event
// default 1
ConfigMapEvent int32 `json:"configMapEvent,omitempty"`
// SecretEvent indicates the buffer of secret event
// default 1
SecretEvent int32 `json:"secretEvent,omitempty"`
// RulesEvent indicates the buffer of rule event
// default 1
RulesEvent int32 `json:"rulesEvent,omitempty"`
// RuleEndpointsEvent indicates the buffer of endpoint event
// default 1
RuleEndpointsEvent int32 `json:"ruleEndpointsEvent,omitempty"`
// QueryPersistentVolume indicates the buffer of query persistent volume
// default 1024
QueryPersistentVolume int32 `json:"queryPersistentVolume,omitempty"`
// QueryPersistentVolumeClaim indicates the buffer of query persistent volume claim
// default 1024
QueryPersistentVolumeClaim int32 `json:"queryPersistentVolumeClaim,omitempty"`
// QueryVolumeAttachment indicates the buffer of query volume attachment
// default 1024
QueryVolumeAttachment int32 `json:"queryVolumeAttachment,omitempty"`
// CreateNode indicates the buffer of create node
// default 1024
CreateNode int32 `json:"createNode,omitempty"`
// PatchNode indicates the buffer of patch node
// default 1024
PatchNode int32 `json:"patchNode,omitempty"`
// QueryNode indicates the buffer of query node
// default 1024
QueryNode int32 `json:"queryNode,omitempty"`
// UpdateNode indicates the buffer of update node
// default 1024
UpdateNode int32 `json:"updateNode,omitempty"`
// PatchPod indicates the buffer of patch pod
// default 1024
PatchPod int32 `json:"patchPod,omitempty"`
// DeletePod indicates the buffer of delete pod message from edge
// default 1024
DeletePod int32 `json:"deletePod,omitempty"`
// CreateLease indicates the buffer of create lease message from edge
// default 1024
CreateLease int32 `json:"createLease,omitempty"`
// QueryLease indicates the buffer of query lease message from edge
// default 1024
QueryLease int32 `json:"queryLease,omitempty"`
// ServiceAccount indicates the buffer of service account token
// default 1024
ServiceAccountToken int32 `json:"serviceAccountToken,omitempty"`
// CreatePod indicates the buffer of create pod
// default 1024
CreatePod int32 `json:"createPod,omitempty"`
// CertificateSigningRequest indicates the buffer of certificatesSigningRequest
// default 1024
CertificateSigningRequest int32 `json:"certificateSigningRequest,omitempty"`
}
// EdgeControllerLoad indicates the EdgeController load
type EdgeControllerLoad struct {
// ProcessEventWorkers indicates the load of process event workers
// default 4
ProcessEventWorkers int32 `json:"processEventWorkers,omitempty"`
// UpdatePodStatusWorkers indicates the load of update pod status workers
// default 1
UpdatePodStatusWorkers int32 `json:"updatePodStatusWorkers,omitempty"`
// UpdateNodeStatusWorkers indicates the load of update node status workers
// default 1
UpdateNodeStatusWorkers int32 `json:"updateNodeStatusWorkers,omitempty"`
// QueryConfigMapWorkers indicates the load of query config map workers
// default 4
QueryConfigMapWorkers int32 `json:"queryConfigMapWorkers,omitempty"`
// QuerySecretWorkers indicates the load of query secret workers
// default 4
QuerySecretWorkers int32 `json:"querySecretWorkers,omitempty"`
// QueryPersistentVolumeWorkers indicates the load of query persistent volume workers
// default 4
QueryPersistentVolumeWorkers int32 `json:"queryPersistentVolumeWorkers,omitempty"`
// QueryPersistentVolumeClaimWorkers indicates the load of query persistent volume claim workers
// default 4
QueryPersistentVolumeClaimWorkers int32 `json:"queryPersistentVolumeClaimWorkers,omitempty"`
// QueryVolumeAttachmentWorkers indicates the load of query volume attachment workers
// default 4
QueryVolumeAttachmentWorkers int32 `json:"queryVolumeAttachmentWorkers,omitempty"`
// CreateNodeWorkers indicates the load of create node workers
// default 4
CreateNodeWorkers int32 `json:"createNodeWorkers,omitempty"`
// PatchNodeWorkers indicates the load of patch node workers
// default 4
PatchNodeWorkers int32 `json:"patchNodeWorkers,omitempty"`
// QueryNodeWorkers indicates the load of query node workers
// default 4
QueryNodeWorkers int32 `json:"queryNodeWorkers,omitempty"`
// UpdateNodeWorkers indicates the load of update node workers
// default 4
UpdateNodeWorkers int32 `json:"updateNodeWorkers,omitempty"`
// PatchPodWorkers indicates the load of patch pod workers
// default 4
PatchPodWorkers int32 `json:"patchPodWorkers,omitempty"`
// DeletePodWorkers indicates the load of delete pod workers
// default 4
DeletePodWorkers int32 `json:"deletePodWorkers,omitempty"`
// CreateLeaseWorkers indicates the load of create lease workers
// default 4
CreateLeaseWorkers int32 `json:"createLeaseWorkers,omitempty"`
// QueryLeaseWorkers indicates the load of query lease workers
// default 4
QueryLeaseWorkers int32 `json:"queryLeaseWorkers,omitempty"`
// UpdateRuleStatusWorkers indicates the load of update rule status
// default 4
UpdateRuleStatusWorkers int32 `json:"UpdateRuleStatusWorkers,omitempty"`
// ServiceAccountTokenWorkers indicates the load of service account token
// default 4
ServiceAccountTokenWorkers int32 `json:"ServiceAccountTokenWorkers,omitempty"`
// CreatePodWorks indicates the load of create pod
// default 4
CreatePodWorks int32 `json:"CreatePodWorks,omitempty"`
// CertificateSigningRequestWorkers indicates the load of CertificateSigningRequest
// default 4
CertificateSigningRequestWorkers int32 `json:"certificateSigningRequestWorkers,omitempty"`
}
// DeviceController indicates the device controller
type DeviceController struct {
// Enable indicates whether deviceController is enabled,
// if set to false (for debugging etc.), skip checking other deviceController configs.
// default true
Enable bool `json:"enable"`
// Buffer indicates Device controller buffer
Buffer *DeviceControllerBuffer `json:"buffer,omitempty"`
// Load indicates DeviceController Load
Load *DeviceControllerLoad `json:"load,omitempty"`
}
// DeviceControllerBuffer indicates deviceController buffer
type DeviceControllerBuffer struct {
// UpdateDeviceTwins indicates the buffer of update device twins
// default 1024
UpdateDeviceTwins int32 `json:"updateDeviceTwins,omitempty"`
// UpdateDeviceStates indicates the buffer of update device states
// default 1024
UpdateDeviceStates int32 `json:"updateDeviceStatus,omitempty"`
// DeviceEvent indicates the buffer of device event
// default 1
DeviceEvent int32 `json:"deviceEvent,omitempty"`
// DeviceModelEvent indicates the buffer of device model event
// default 1
DeviceModelEvent int32 `json:"deviceModelEvent,omitempty"`
}
// DeviceControllerLoad indicates the deviceController load
type DeviceControllerLoad struct {
// UpdateDeviceStatusWorkers indicates the load of update device status workers
// default 1
UpdateDeviceStatusWorkers int32 `json:"updateDeviceStatusWorkers,omitempty"`
}
// TaskManager indicates the operations controller
type TaskManager struct {
// Enable indicates whether TaskManager is enabled,
// if set to false (for debugging etc.), skip checking other TaskManager configs.
// default false
Enable bool `json:"enable"`
// Buffer indicates Operation Controller buffer
Buffer *TaskManagerBuffer `json:"buffer,omitempty"`
// Load indicates Operation Controller Load
Load *TaskManagerLoad `json:"load,omitempty"`
}
// TaskManagerBuffer indicates TaskManager buffer
type TaskManagerBuffer struct {
// TaskStatus indicates the buffer of update NodeUpgradeJob status
// default 1024
TaskStatus int32 `json:"taskStatus,omitempty"`
// TaskEvent indicates the buffer of NodeUpgradeJob event
// default 1
TaskEvent int32 `json:"taskEvent,omitempty"`
}
// TaskManagerLoad indicates the TaskManager load
type TaskManagerLoad struct {
// TaskWorkers indicates the load of update NodeUpgradeJob workers
// default 1
TaskWorkers int32 `json:"taskWorkers,omitempty"`
}
// ImagePrePullController indicates the operations controller
type ImagePrePullController struct {
// Enable indicates whether ImagePrePullController is enabled,
// if set to false (for debugging etc.), skip checking other ImagePrePullController configs.
// default false
Enable bool `json:"enable"`
// Buffer indicates Operation Controller buffer
Buffer *ImagePrePullControllerBuffer `json:"buffer,omitempty"`
// Load indicates Operation Controller Load
Load *ImagePrePullControllerLoad `json:"load,omitempty"`
}
// ImagePrePullControllerBuffer indicates ImagePrePullController buffer
type ImagePrePullControllerBuffer struct {
// ImagePrePullJobStatus indicates the buffer of update ImagePrePullJob status
// default 1024
ImagePrePullJobStatus int32 `json:"imagePrePullJobStatus,omitempty"`
// ImagePrePullJobEvent indicates the buffer of ImagePrePullJob event
// default 1
ImagePrePullJobEvent int32 `json:"imagePrePullJobEvent,omitempty"`
}
// ImagePrePullControllerLoad indicates the ImagePrePullController load
type ImagePrePullControllerLoad struct {
// ImagePrePullJobWorkers indicates the load of update ImagePrePullJob workers
// default 1
ImagePrePullJobWorkers int32 `json:"imagePrePullJobWorkers,omitempty"`
}
// SyncController indicates the sync controller
type SyncController struct {
// Enable indicates whether syncController is enabled,
// if set to false (for debugging etc.), skip checking other syncController configs.
// default true
Enable bool `json:"enable"`
}
// DynamicController indicates the dynamic controller
type DynamicController struct {
// Enable indicates whether dynamicController is enabled,
// if set to false (for debugging etc.), skip checking other dynamicController configs.
// default true
Enable bool `json:"enable"`
}
// CloudStream indicates the stream controller
type CloudStream struct {
// Enable indicates whether cloudstream is enabled, if set to false (for debugging etc.), skip checking other configs.
// default true
Enable bool `json:"enable"`
// TLSTunnelCAFile indicates ca file path
// default /etc/kubeedge/ca/rootCA.crt
TLSTunnelCAFile string `json:"tlsTunnelCAFile,omitempty"`
// TLSTunnelCertFile indicates cert file path
// default /etc/kubeedge/certs/server.crt
TLSTunnelCertFile string `json:"tlsTunnelCertFile,omitempty"`
// TLSTunnelPrivateKeyFile indicates key file path
// default /etc/kubeedge/certs/server.key
TLSTunnelPrivateKeyFile string `json:"tlsTunnelPrivateKeyFile,omitempty"`
// TunnelPort set open port for tunnel server
// default 10004
TunnelPort uint32 `json:"tunnelPort,omitempty"`
// TLSStreamCAFile indicates kube-apiserver ca file path
// default /etc/kubeedge/ca/streamCA.crt
TLSStreamCAFile string `json:"tlsStreamCAFile,omitempty"`
// TLSStreamCertFile indicates cert file path
// default /etc/kubeedge/certs/stream.crt
TLSStreamCertFile string `json:"tlsStreamCertFile,omitempty"`
// TLSStreamPrivateKeyFile indicates key file path
// default /etc/kubeedge/certs/stream.key
TLSStreamPrivateKeyFile string `json:"tlsStreamPrivateKeyFile,omitempty"`
// StreamPort set open port for stream server
// default 10003
StreamPort uint32 `json:"streamPort,omitempty"`
}
type Router struct {
// default true
Enable bool `json:"enable"`
Address string `json:"address,omitempty"`
Port uint32 `json:"port,omitempty"`
RestTimeout uint32 `json:"restTimeout,omitempty"`
}
// IptablesManager indicates the config of Iptables
type IptablesManager struct {
// Enable indicates whether enable IptablesManager
// default true
Enable bool `json:"enable"`
// It indicates how the component is deployed, valid mode can use "internal" or "external".
// The iptables manager component with the internal mode is always deployed inside the cloudcore, will share the host network, forward to the internal port of the tunnel port.
// The iptables manager component with the external mode is always deployed outside the cloudcore, will share the host network, forward to the internal cloudcore service and port.
// default internal.
// +kubebuilder:validation:Enum=internal;external
Mode IptablesMgrMode `json:"mode,omitempty"`
}

View File

@ -0,0 +1,216 @@
/*
Copyright 2019 The KubeEdge 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 validation
import (
"fmt"
"net"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
netutils "k8s.io/utils/net"
"github.com/kubeedge/api/apis/componentconfig/cloudcore/v1alpha1"
utilvalidation "github.com/kubeedge/api/apis/util/validation"
)
// ValidateCloudCoreConfiguration validates `c` and returns an errorList if it is invalid
func ValidateCloudCoreConfiguration(c *v1alpha1.CloudCoreConfig) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateKubeAPIConfig(*c.KubeAPIConfig)...)
allErrs = append(allErrs, ValidateCommonConfig(*c.CommonConfig)...)
allErrs = append(allErrs, ValidateModuleCloudHub(*c.Modules.CloudHub)...)
allErrs = append(allErrs, ValidateModuleEdgeController(*c.Modules.EdgeController)...)
allErrs = append(allErrs, ValidateModuleDeviceController(*c.Modules.DeviceController)...)
allErrs = append(allErrs, ValidateModuleSyncController(*c.Modules.SyncController)...)
allErrs = append(allErrs, ValidateModuleDynamicController(*c.Modules.DynamicController)...)
allErrs = append(allErrs, ValidateModuleCloudStream(*c.Modules.CloudStream)...)
return allErrs
}
func ValidateCommonConfig(c v1alpha1.CommonConfig) field.ErrorList {
return validateHostPort(c.MonitorServer.BindAddress, field.NewPath("monitorServer.bindAddress"))
}
func validateHostPort(input string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
hostIP, port, err := net.SplitHostPort(input)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath, input, "must be IP:port"))
return allErrs
}
if ip := netutils.ParseIPSloppy(hostIP); ip == nil {
allErrs = append(allErrs, field.Invalid(fldPath, hostIP, "must be a valid IP"))
}
if p, err := strconv.Atoi(port); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath, port, "must be a valid port"))
} else if p < 1 || p > 65535 {
allErrs = append(allErrs, field.Invalid(fldPath, port, "must be a valid port"))
}
return allErrs
}
// ValidateModuleCloudHub validates `c` and returns an errorList if it is invalid
func ValidateModuleCloudHub(c v1alpha1.CloudHub) field.ErrorList {
if !c.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
validHTTPSPort := utilvalidation.IsValidPortNum(int(c.HTTPS.Port))
validWPort := utilvalidation.IsValidPortNum(int(c.WebSocket.Port))
validAddress := utilvalidation.IsValidIP(c.WebSocket.Address)
validQPort := utilvalidation.IsValidPortNum(int(c.Quic.Port))
validQAddress := utilvalidation.IsValidIP(c.Quic.Address)
if len(validHTTPSPort) > 0 {
for _, m := range validHTTPSPort {
allErrs = append(allErrs, field.Invalid(field.NewPath("port"), c.HTTPS.Port, m))
}
}
if len(validWPort) > 0 {
for _, m := range validWPort {
allErrs = append(allErrs, field.Invalid(field.NewPath("port"), c.WebSocket.Port, m))
}
}
if len(validAddress) > 0 {
for _, m := range validAddress {
allErrs = append(allErrs, field.Invalid(field.NewPath("Address"), c.WebSocket.Address, m))
}
}
if len(validQPort) > 0 {
for _, m := range validQPort {
allErrs = append(allErrs, field.Invalid(field.NewPath("port"), c.Quic.Port, m))
}
}
if len(validQAddress) > 0 {
for _, m := range validQAddress {
allErrs = append(allErrs, field.Invalid(field.NewPath("Address"), c.Quic.Address, m))
}
}
if !strings.HasPrefix(strings.ToLower(c.UnixSocket.Address), "unix://") {
allErrs = append(allErrs, field.Invalid(field.NewPath("address"),
c.UnixSocket.Address, "unixSocketAddress must has prefix unix://"))
}
s := strings.SplitN(c.UnixSocket.Address, "://", 2)
if len(s) > 1 && !utilvalidation.FileIsExist(path.Dir(s[1])) {
if err := os.MkdirAll(path.Dir(s[1]), os.ModePerm); err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("address"),
c.UnixSocket.Address, fmt.Sprintf("create unixSocketAddress %v dir %v error: %v",
c.UnixSocket.Address, path.Dir(s[1]), err)))
}
}
if c.TokenRefreshDuration <= 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("TokenRefreshDuration"),
c.TokenRefreshDuration, "TokenRefreshDuration must be positive"))
}
return allErrs
}
// ValidateModuleEdgeController validates `e` and returns an errorList if it is invalid
func ValidateModuleEdgeController(e v1alpha1.EdgeController) field.ErrorList {
if !e.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
if e.NodeUpdateFrequency <= 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("NodeUpdateFrequency"), e.NodeUpdateFrequency, "NodeUpdateFrequency need > 0"))
}
return allErrs
}
// ValidateModuleDeviceController validates `d` and returns an errorList if it is invalid
func ValidateModuleDeviceController(d v1alpha1.DeviceController) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleSyncController validates `d` and returns an errorList if it is invalid
func ValidateModuleSyncController(d v1alpha1.SyncController) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleDynamicController validates `d` and returns an errorList if it is invalid
func ValidateModuleDynamicController(d v1alpha1.DynamicController) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleCloudStream validates `d` and returns an errorList if it is invalid
func ValidateModuleCloudStream(d v1alpha1.CloudStream) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
if !utilvalidation.FileIsExist(d.TLSTunnelPrivateKeyFile) {
klog.Warningf("TLSTunnelPrivateKeyFile does not exist in %s, will load from secret", d.TLSTunnelPrivateKeyFile)
}
if !utilvalidation.FileIsExist(d.TLSTunnelCertFile) {
klog.Warningf("TLSTunnelCertFile does not exist in %s, will load from secret", d.TLSTunnelCertFile)
}
if !utilvalidation.FileIsExist(d.TLSTunnelCAFile) {
klog.Warningf("TLSTunnelCAFile does not exist in %s, will load from secret", d.TLSTunnelCAFile)
}
if !utilvalidation.FileIsExist(d.TLSStreamPrivateKeyFile) {
allErrs = append(allErrs, field.Invalid(field.NewPath("TLSStreamPrivateKeyFile"), d.TLSStreamPrivateKeyFile, "TLSStreamPrivateKeyFile not exist"))
}
if !utilvalidation.FileIsExist(d.TLSStreamCertFile) {
allErrs = append(allErrs, field.Invalid(field.NewPath("TLSStreamCertFile"), d.TLSStreamCertFile, "TLSStreamCertFile not exist"))
}
if !utilvalidation.FileIsExist(d.TLSStreamCAFile) {
allErrs = append(allErrs, field.Invalid(field.NewPath("TLSStreamCAFile"), d.TLSStreamCAFile, "TLSStreamCAFile not exist"))
}
return allErrs
}
// ValidateKubeAPIConfig validates `k` and returns an errorList if it is invalid
func ValidateKubeAPIConfig(k v1alpha1.KubeAPIConfig) field.ErrorList {
allErrs := field.ErrorList{}
if k.KubeConfig != "" && !filepath.IsAbs(k.KubeConfig) {
allErrs = append(allErrs, field.Invalid(field.NewPath("kubeconfig"), k.KubeConfig, "kubeconfig need abs path"))
}
if k.KubeConfig != "" && !utilvalidation.FileIsExist(k.KubeConfig) {
allErrs = append(allErrs, field.Invalid(field.NewPath("kubeconfig"), k.KubeConfig, "kubeconfig not exist"))
}
return allErrs
}

View File

@ -0,0 +1,535 @@
/*
Copyright 2021 The KubeEdge 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 validation
import (
"os"
"path/filepath"
"reflect"
"testing"
"time"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/kubeedge/api/apis/componentconfig/cloudcore/v1alpha1"
)
func TestValidateCloudCoreConfiguration(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "existFile")
if err != nil {
t.Errorf("create temp file failed: %v", err)
return
}
config := v1alpha1.NewDefaultCloudCoreConfig()
config.Modules.CloudHub.UnixSocket.Address = "unix://" + ef.Name()
config.KubeAPIConfig.KubeConfig = ef.Name()
errList := ValidateCloudCoreConfiguration(config)
if len(errList) > 0 {
t.Errorf("cloudcore configuration is not correct: %v", errList)
}
}
func TestValidateModuleCloudHub(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "existFile")
if err != nil {
t.Errorf("create temp file failed: %v", err)
return
}
unixAddr := "unix://" + ef.Name()
cases := []struct {
name string
input v1alpha1.CloudHub
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.CloudHub{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 invalid https port",
input: v1alpha1.CloudHub{
Enable: true,
HTTPS: &v1alpha1.CloudHubHTTPS{
Port: 0,
},
WebSocket: &v1alpha1.CloudHubWebSocket{
Port: 10002,
Address: "127.0.0.1",
},
Quic: &v1alpha1.CloudHubQUIC{
Port: 10002,
Address: "127.0.0.1",
},
UnixSocket: &v1alpha1.CloudHubUnixSocket{
Address: unixAddr,
},
TokenRefreshDuration: 1,
},
expected: field.ErrorList{field.Invalid(field.NewPath("port"), uint32(0), "must be between 1 and 65535, inclusive")},
},
{
name: "case3 invalid websocket port",
input: v1alpha1.CloudHub{
Enable: true,
HTTPS: &v1alpha1.CloudHubHTTPS{
Port: 10000,
},
WebSocket: &v1alpha1.CloudHubWebSocket{
Port: 0,
Address: "127.0.0.1",
},
Quic: &v1alpha1.CloudHubQUIC{
Port: 10002,
Address: "127.0.0.1",
},
UnixSocket: &v1alpha1.CloudHubUnixSocket{
Address: unixAddr,
},
TokenRefreshDuration: 1,
},
expected: field.ErrorList{field.Invalid(field.NewPath("port"), uint32(0), "must be between 1 and 65535, inclusive")},
},
{
name: "case4 invalid websocket addr",
input: v1alpha1.CloudHub{
Enable: true,
HTTPS: &v1alpha1.CloudHubHTTPS{
Port: 10000,
},
WebSocket: &v1alpha1.CloudHubWebSocket{
Port: 10002,
Address: "xxx.xxx.xxx.xxx",
},
Quic: &v1alpha1.CloudHubQUIC{
Port: 10002,
Address: "127.0.0.1",
},
UnixSocket: &v1alpha1.CloudHubUnixSocket{
Address: unixAddr,
},
TokenRefreshDuration: 1,
},
expected: field.ErrorList{field.Invalid(field.NewPath("Address"), "xxx.xxx.xxx.xxx", "must be a valid IP address, (e.g. 10.9.8.7)")},
},
{
name: "case5 invalid quic port",
input: v1alpha1.CloudHub{
Enable: true,
HTTPS: &v1alpha1.CloudHubHTTPS{
Port: 10000,
},
WebSocket: &v1alpha1.CloudHubWebSocket{
Port: 10002,
Address: "127.0.0.1",
},
Quic: &v1alpha1.CloudHubQUIC{
Port: 0,
Address: "127.0.0.1",
},
UnixSocket: &v1alpha1.CloudHubUnixSocket{
Address: unixAddr,
},
TokenRefreshDuration: 1,
},
expected: field.ErrorList{field.Invalid(field.NewPath("port"), uint32(0), "must be between 1 and 65535, inclusive")},
},
{
name: "case6 invalid websocket addr",
input: v1alpha1.CloudHub{
Enable: true,
HTTPS: &v1alpha1.CloudHubHTTPS{
Port: 10000,
},
WebSocket: &v1alpha1.CloudHubWebSocket{
Port: 10002,
Address: "127.0.0.1",
},
Quic: &v1alpha1.CloudHubQUIC{
Port: 10002,
Address: "xxx.xxx.xxx.xxx",
},
UnixSocket: &v1alpha1.CloudHubUnixSocket{
Address: unixAddr,
},
TokenRefreshDuration: 1,
},
expected: field.ErrorList{field.Invalid(field.NewPath("Address"), "xxx.xxx.xxx.xxx", "must be a valid IP address, (e.g. 10.9.8.7)")},
},
{
name: "case7 invalid unixSocketAddress",
input: v1alpha1.CloudHub{
Enable: true,
HTTPS: &v1alpha1.CloudHubHTTPS{
Port: 10000,
},
WebSocket: &v1alpha1.CloudHubWebSocket{
Port: 10002,
Address: "127.0.0.1",
},
Quic: &v1alpha1.CloudHubQUIC{
Port: 10002,
Address: "127.0.0.1",
},
UnixSocket: &v1alpha1.CloudHubUnixSocket{
Address: "var/lib/kubeedge/kubeedge.sock",
},
TokenRefreshDuration: 1,
},
expected: field.ErrorList{field.Invalid(field.NewPath("address"),
"var/lib/kubeedge/kubeedge.sock", "unixSocketAddress must has prefix unix://")},
},
{
name: "case8 invalid TokenRefreshDuration",
input: v1alpha1.CloudHub{
Enable: true,
HTTPS: &v1alpha1.CloudHubHTTPS{
Port: 10000,
},
WebSocket: &v1alpha1.CloudHubWebSocket{
Port: 10002,
Address: "127.0.0.1",
},
Quic: &v1alpha1.CloudHubQUIC{
Port: 10002,
Address: "127.0.0.1",
},
UnixSocket: &v1alpha1.CloudHubUnixSocket{
Address: unixAddr,
},
TokenRefreshDuration: 0,
},
expected: field.ErrorList{field.Invalid(field.NewPath("TokenRefreshDuration"),
time.Duration(0), "TokenRefreshDuration must be positive")},
},
}
for _, c := range cases {
if result := ValidateModuleCloudHub(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleEdgeController(t *testing.T) {
cases := []struct {
name string
input v1alpha1.EdgeController
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.EdgeController{
Enable: false,
NodeUpdateFrequency: 0,
},
expected: field.ErrorList{},
},
{
name: "case2 NodeUpdateFrequency not legal",
input: v1alpha1.EdgeController{
Enable: true,
NodeUpdateFrequency: 0,
},
expected: field.ErrorList{field.Invalid(field.NewPath("NodeUpdateFrequency"), int32(0),
"NodeUpdateFrequency need > 0")},
},
{
name: "case3 all ok",
input: v1alpha1.EdgeController{
Enable: true,
NodeUpdateFrequency: 10,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleEdgeController(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleDeviceController(t *testing.T) {
cases := []struct {
name string
input v1alpha1.DeviceController
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.DeviceController{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 all ok",
input: v1alpha1.DeviceController{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleDeviceController(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleSyncController(t *testing.T) {
cases := []struct {
name string
input v1alpha1.SyncController
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.SyncController{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 all ok",
input: v1alpha1.SyncController{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleSyncController(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleDynamicController(t *testing.T) {
cases := []struct {
name string
input v1alpha1.DynamicController
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.DynamicController{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 all ok",
input: v1alpha1.DynamicController{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleDynamicController(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleCloudStream(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "existFile")
if err != nil {
t.Errorf("create temp file failed: %v", err)
return
}
nonexistentDir := filepath.Join(dir, "not_exist_dir")
notExistFile := filepath.Join(nonexistentDir, "not_exist_file")
cases := []struct {
name string
input v1alpha1.CloudStream
expected field.ErrorList
}{
{
name: "case1 not enable",
input: v1alpha1.CloudStream{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 TLSStreamPrivateKeyFile not exist",
input: v1alpha1.CloudStream{
Enable: true,
TLSStreamPrivateKeyFile: notExistFile,
TLSStreamCertFile: ef.Name(),
TLSStreamCAFile: ef.Name(),
},
expected: field.ErrorList{field.Invalid(field.NewPath("TLSStreamPrivateKeyFile"), notExistFile,
"TLSStreamPrivateKeyFile not exist")},
},
{
name: "case3 TLSStreamCertFile not exist",
input: v1alpha1.CloudStream{
Enable: true,
TLSStreamPrivateKeyFile: ef.Name(),
TLSStreamCertFile: notExistFile,
TLSStreamCAFile: ef.Name(),
},
expected: field.ErrorList{field.Invalid(field.NewPath("TLSStreamCertFile"), notExistFile,
"TLSStreamCertFile not exist")},
},
{
name: "case4 TLSStreamCAFile not exist",
input: v1alpha1.CloudStream{
Enable: true,
TLSStreamPrivateKeyFile: ef.Name(),
TLSStreamCertFile: ef.Name(),
TLSStreamCAFile: notExistFile,
},
expected: field.ErrorList{field.Invalid(field.NewPath("TLSStreamCAFile"), notExistFile,
"TLSStreamCAFile not exist")},
},
{
name: "case5 all ok",
input: v1alpha1.CloudStream{
Enable: true,
TLSStreamPrivateKeyFile: ef.Name(),
TLSStreamCertFile: ef.Name(),
TLSStreamCAFile: ef.Name(),
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleCloudStream(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateKubeAPIConfig(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "existFile")
if err != nil {
t.Errorf("create temp file failed: %v", err)
return
}
nonexistentDir := filepath.Join(dir, "not_exist_dir")
notExistFile := filepath.Join(nonexistentDir, "not_exist_file")
cases := []struct {
name string
input v1alpha1.KubeAPIConfig
expected field.ErrorList
}{
{
name: "case1 not abs path",
input: v1alpha1.KubeAPIConfig{
KubeConfig: ".",
},
expected: field.ErrorList{field.Invalid(field.NewPath("kubeconfig"), ".",
"kubeconfig need abs path")},
},
{
name: "case2 file not exist",
input: v1alpha1.KubeAPIConfig{
KubeConfig: notExistFile,
},
expected: field.ErrorList{field.Invalid(field.NewPath("kubeconfig"), notExistFile,
"kubeconfig not exist")},
},
{
name: "case3 all ok",
input: v1alpha1.KubeAPIConfig{
KubeConfig: ef.Name(),
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateKubeAPIConfig(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateCommonConfig(t *testing.T) {
tests := []struct {
name string
commonConfig v1alpha1.CommonConfig
expectedErr bool
}{
{
name: "invalid metric server addr",
commonConfig: v1alpha1.CommonConfig{
MonitorServer: v1alpha1.MonitorServer{
BindAddress: "xxx.xxx.xxx.xxx:9091",
},
},
expectedErr: true,
},
{
name: "invalid metric server port",
commonConfig: v1alpha1.CommonConfig{
MonitorServer: v1alpha1.MonitorServer{
BindAddress: "127.0.0.1:88888",
},
},
expectedErr: true,
},
{
name: "valid metric server config",
commonConfig: v1alpha1.CommonConfig{
MonitorServer: v1alpha1.MonitorServer{
BindAddress: "127.0.0.1:9091",
},
},
expectedErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
errList := ValidateCommonConfig(tt.commonConfig)
if len(errList) == 0 && tt.expectedErr {
t.Errorf("ValidateCommonConfig expected get err, but errList is nil")
}
if len(errList) != 0 && !tt.expectedErr {
t.Errorf("ValidateCommonConfig expected get no err, but errList is not nil")
}
})
}
}

View File

@ -0,0 +1,235 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
import (
"net"
"net/url"
"path"
"strconv"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/kubeedge/api/apis/common/constants"
metaconfig "github.com/kubeedge/api/apis/componentconfig/meta/v1alpha1"
"github.com/kubeedge/api/apis/util"
)
// NewDefaultEdgeCoreConfig returns a full EdgeCoreConfig object
func NewDefaultEdgeCoreConfig() *EdgeCoreConfig {
hostnameOverride := util.GetHostname()
localIP, _ := util.GetLocalIP(hostnameOverride)
return &EdgeCoreConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
DataBase: &DataBase{
DriverName: DataBaseDriverName,
AliasName: DataBaseAliasName,
DataSource: DataBaseDataSource,
},
Modules: &Modules{
Edged: &Edged{
Enable: true,
Labels: map[string]string{},
Annotations: map[string]string{},
Taints: []v1.Taint{},
NodeStatusUpdateFrequency: 10,
RuntimeType: constants.DefaultRuntimeType,
DockerAddress: constants.DefaultDockerAddress,
RemoteRuntimeEndpoint: constants.DefaultRemoteRuntimeEndpoint,
RemoteImageEndpoint: constants.DefaultRemoteImageEndpoint,
NodeIP: localIP,
ClusterDNS: "",
ClusterDomain: "",
ConcurrentConsumers: constants.DefaultConcurrentConsumers,
EdgedMemoryCapacity: constants.DefaultEdgedMemoryCapacity,
PodSandboxImage: constants.DefaultPodSandboxImage,
ImagePullProgressDeadline: 60,
RuntimeRequestTimeout: 2,
HostnameOverride: hostnameOverride,
RegisterNodeNamespace: constants.DefaultRegisterNodeNamespace,
CustomInterfaceName: "",
RegisterNode: true,
DevicePluginEnabled: false,
GPUPluginEnabled: false,
ImageGCHighThreshold: constants.DefaultImageGCHighThreshold,
ImageGCLowThreshold: constants.DefaultImageGCLowThreshold,
MaximumDeadContainersPerPod: constants.DefaultMaximumDeadContainersPerPod,
CGroupDriver: CGroupDriverCGroupFS,
CgroupsPerQOS: true,
CgroupRoot: constants.DefaultCgroupRoot,
NetworkPluginName: "",
CNIConfDir: constants.DefaultCNIConfDir,
CNIBinDir: constants.DefaultCNIBinDir,
CNICacheDir: constants.DefaultCNICacheDir,
NetworkPluginMTU: constants.DefaultNetworkPluginMTU,
VolumeStatsAggPeriod: constants.DefaultVolumeStatsAggPeriod,
EnableMetrics: true,
},
EdgeHub: &EdgeHub{
Enable: true,
Heartbeat: 15,
MessageQPS: constants.DefaultQPS,
MessageBurst: constants.DefaultBurst,
ProjectID: "e632aba927ea4ac2b575ec1603d56f10",
TLSCAFile: constants.DefaultCAFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
Quic: &EdgeHubQUIC{
Enable: false,
HandshakeTimeout: 30,
ReadDeadline: 15,
Server: net.JoinHostPort(localIP, "10001"),
WriteDeadline: 15,
},
WebSocket: &EdgeHubWebSocket{
Enable: true,
HandshakeTimeout: 30,
ReadDeadline: 15,
Server: net.JoinHostPort(localIP, "10000"),
WriteDeadline: 15,
},
HTTPServer: (&url.URL{
Scheme: "https",
Host: net.JoinHostPort(localIP, "10002"),
}).String(),
Token: "",
RotateCertificates: true,
},
EventBus: &EventBus{
Enable: true,
MqttQOS: 0,
MqttRetain: false,
MqttSessionQueueSize: 100,
MqttServerExternal: "tcp://127.0.0.1:1883",
MqttServerInternal: "tcp://127.0.0.1:1884",
MqttSubClientID: "",
MqttPubClientID: "",
MqttUsername: "",
MqttPassword: "",
MqttMode: MqttModeExternal,
TLS: &EventBusTLS{
Enable: false,
TLSMqttCAFile: constants.DefaultMqttCAFile,
TLSMqttCertFile: constants.DefaultMqttCertFile,
TLSMqttPrivateKeyFile: constants.DefaultMqttKeyFile,
},
},
MetaManager: &MetaManager{
Enable: true,
ContextSendGroup: metaconfig.GroupNameHub,
ContextSendModule: metaconfig.ModuleNameEdgeHub,
RemoteQueryTimeout: constants.DefaultRemoteQueryTimeout,
MetaServer: &MetaServer{
Enable: false,
Server: constants.DefaultMetaServerAddr,
TLSCaFile: constants.DefaultCAFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
},
},
ServiceBus: &ServiceBus{
Enable: false,
Server: "127.0.0.1",
Port: 9060,
Timeout: 60,
},
DeviceTwin: &DeviceTwin{
Enable: true,
},
DBTest: &DBTest{
Enable: false,
},
EdgeStream: &EdgeStream{
Enable: false,
TLSTunnelCAFile: constants.DefaultCAFile,
TLSTunnelCertFile: constants.DefaultCertFile,
TLSTunnelPrivateKeyFile: constants.DefaultKeyFile,
HandshakeTimeout: 30,
ReadDeadline: 15,
TunnelServer: net.JoinHostPort("127.0.0.1", strconv.Itoa(constants.DefaultTunnelPort)),
WriteDeadline: 15,
},
},
}
}
// NewMinEdgeCoreConfig returns a common EdgeCoreConfig object
func NewMinEdgeCoreConfig() *EdgeCoreConfig {
hostnameOverride := util.GetHostname()
localIP, _ := util.GetLocalIP(hostnameOverride)
return &EdgeCoreConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
DataBase: &DataBase{
DataSource: DataBaseDataSource,
},
Modules: &Modules{
Edged: &Edged{
RuntimeType: constants.DefaultRuntimeType,
RemoteRuntimeEndpoint: constants.DefaultRemoteRuntimeEndpoint,
RemoteImageEndpoint: constants.DefaultRemoteImageEndpoint,
DockerAddress: constants.DefaultDockerAddress,
NodeIP: localIP,
ClusterDNS: "",
ClusterDomain: "",
PodSandboxImage: constants.DefaultPodSandboxImage,
HostnameOverride: hostnameOverride,
DevicePluginEnabled: false,
GPUPluginEnabled: false,
CGroupDriver: CGroupDriverCGroupFS,
CgroupsPerQOS: true,
CgroupRoot: constants.DefaultCgroupRoot,
},
EdgeHub: &EdgeHub{
Heartbeat: 15,
TLSCAFile: constants.DefaultCAFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
WebSocket: &EdgeHubWebSocket{
Enable: true,
HandshakeTimeout: 30,
ReadDeadline: 15,
Server: net.JoinHostPort(localIP, "10000"),
WriteDeadline: 15,
},
HTTPServer: (&url.URL{
Scheme: "https",
Host: net.JoinHostPort(localIP, "10002"),
}).String(),
Token: "",
},
EventBus: &EventBus{
MqttQOS: 0,
MqttRetain: false,
MqttServerExternal: "tcp://127.0.0.1:1883",
MqttServerInternal: "tcp://127.0.0.1:1884",
MqttSubClientID: "",
MqttPubClientID: "",
MqttUsername: "",
MqttPassword: "",
MqttMode: MqttModeExternal,
},
},
}
}

View File

@ -0,0 +1,38 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
import (
"os"
"k8s.io/klog/v2"
"sigs.k8s.io/yaml"
)
func (c *EdgeCoreConfig) Parse(filename string) error {
data, err := os.ReadFile(filename)
if err != nil {
klog.Errorf("Failed to read configfile %s: %v", filename, err)
return err
}
err = yaml.Unmarshal(data, c)
if err != nil {
klog.Errorf("Failed to unmarshal configfile %s: %v", filename, err)
return err
}
return nil
}

View File

@ -0,0 +1,23 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
const (
GroupName = "edgecore.config.kubeedge.io"
APIVersion = "v1alpha1"
Kind = "EdgeCore"
)

View File

@ -0,0 +1,468 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
import (
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
metaconfig "github.com/kubeedge/api/apis/componentconfig/meta/v1alpha1"
)
const (
MqttModeInternal MqttMode = 0
MqttModeBoth MqttMode = 1
MqttModeExternal MqttMode = 2
)
const (
CGroupDriverCGroupFS = "cgroupfs"
CGroupDriverSystemd = "systemd"
)
const (
// DataBaseDriverName is sqlite3
DataBaseDriverName = "sqlite3"
// DataBaseAliasName is default
DataBaseAliasName = "default"
// DataBaseDataSource is edge.db
DataBaseDataSource = "/var/lib/kubeedge/edgecore.db"
)
type ProtocolName string
type MqttMode int
// EdgeCoreConfig indicates the EdgeCore config which read from EdgeCore config file
type EdgeCoreConfig struct {
metav1.TypeMeta
// DataBase indicates database info
// +Required
DataBase *DataBase `json:"database,omitempty"`
// Modules indicates EdgeCore modules config
// +Required
Modules *Modules `json:"modules,omitempty"`
// FeatureGates is a map of feature names to bools that enable or disable alpha/experimental features.
FeatureGates map[string]bool `json:"featureGates,omitempty"`
}
// DataBase indicates the database info
type DataBase struct {
// DriverName indicates database driver name
// default "sqlite3"
DriverName string `json:"driverName,omitempty"`
// AliasName indicates alias name
// default "default"
AliasName string `json:"aliasName,omitempty"`
// DataSource indicates the data source path
// default "/var/lib/kubeedge/edgecore.db"
DataSource string `json:"dataSource,omitempty"`
}
// Modules indicates the modules which edgeCore will be used
type Modules struct {
// Edged indicates edged module config
// +Required
Edged *Edged `json:"edged,omitempty"`
// EdgeHub indicates edgeHub module config
// +Required
EdgeHub *EdgeHub `json:"edgeHub,omitempty"`
// EventBus indicates eventBus config for edgeCore
// +Required
EventBus *EventBus `json:"eventBus,omitempty"`
// MetaManager indicates meta module config
// +Required
MetaManager *MetaManager `json:"metaManager,omitempty"`
// ServiceBus indicates serviceBus module config
ServiceBus *ServiceBus `json:"serviceBus,omitempty"`
// DeviceTwin indicates deviceTwin module config
DeviceTwin *DeviceTwin `json:"deviceTwin,omitempty"`
// DBTest indicates dbTest module config
DBTest *DBTest `json:"dbTest,omitempty"`
// EdgeStream indicates edgestream module config
// +Required
EdgeStream *EdgeStream `json:"edgeStream,omitempty"`
}
// Edged indicates the config fo edged module
// edged is lighted-kubelet
type Edged struct {
// Enable indicates whether edged is enabled,
// if set to false (for debugging etc.), skip checking other edged configs.
// default true
Enable bool `json:"enable"`
// Labels indicates current node labels
Labels map[string]string `json:"labels,omitempty"`
// Annotations indicates current node annotations
Annotations map[string]string `json:"annotations,omitempty"`
// Taints indicates current node taints
Taints []v1.Taint `json:"taints,omitempty"`
// NodeStatusUpdateFrequency indicates node status update frequency (second)
// default 10
NodeStatusUpdateFrequency int32 `json:"nodeStatusUpdateFrequency,omitempty"`
// RuntimeType indicates cri runtime ,support: docker, remote
// default "docker"
RuntimeType string `json:"runtimeType,omitempty"`
// DockerAddress indicates docker server address
// default "unix:///var/run/docker.sock"
DockerAddress string `json:"dockerAddress,omitempty"`
// RemoteRuntimeEndpoint indicates remote runtime endpoint
// default "unix:///var/run/dockershim.sock"
RemoteRuntimeEndpoint string `json:"remoteRuntimeEndpoint,omitempty"`
// RemoteImageEndpoint indicates remote image endpoint
// default "unix:///var/run/dockershim.sock"
RemoteImageEndpoint string `json:"remoteImageEndpoint,omitempty"`
// NodeIP indicates current node ip.
// Setting the value overwrites the automatically detected IP address
// default get local host ip
NodeIP string `json:"nodeIP"`
// ClusterDNS indicates cluster dns
// Note: Can not use "omitempty" option, It will affect the output of the default configuration file
// +Required
ClusterDNS string `json:"clusterDNS"`
// ClusterDomain indicates cluster domain
// Note: Can not use "omitempty" option, It will affect the output of the default configuration file
ClusterDomain string `json:"clusterDomain"`
// EdgedMemoryCapacity indicates memory capacity (byte)
// default 7852396000
EdgedMemoryCapacity int64 `json:"edgedMemoryCapacity,omitempty"`
// PodSandboxImage is the image whose network/ipc namespaces containers in each pod will use.
// +Required
// default kubeedge/pause:3.6
PodSandboxImage string `json:"podSandboxImage,omitempty"`
// ImagePullProgressDeadline indicates image pull progress dead line (second)
// default 60
ImagePullProgressDeadline int32 `json:"imagePullProgressDeadline,omitempty"`
// RuntimeRequestTimeout indicates runtime request timeout (second)
// default 2
RuntimeRequestTimeout int32 `json:"runtimeRequestTimeout,omitempty"`
// HostnameOverride indicates hostname
// default os.Hostname()
HostnameOverride string `json:"hostnameOverride,omitempty"`
// RegisterNode enables automatic registration
// default true
RegisterNode bool `json:"registerNode,omitempty"`
// RegisterNodeNamespace indicates register node namespace
// default "default"
RegisterNodeNamespace string `json:"registerNodeNamespace,omitempty"`
// CustomInterfaceName indicates the name of the network interface used for obtaining the IP address.
// Setting this will override the setting 'NodeIP' if provided.
// If this is not defined the IP address is obtained by the hostname.
// default ""
CustomInterfaceName string `json:"customInterfaceName,omitempty"`
// ConcurrentConsumers indicates concurrent consumers for pod add or remove operation
// default 5
ConcurrentConsumers int `json:"concurrentConsumers,omitempty"`
// DevicePluginEnabled indicates enable device plugin
// default false
// Note: Can not use "omitempty" option, it will affect the output of the default configuration file
DevicePluginEnabled bool `json:"devicePluginEnabled"`
// GPUPluginEnabled indicates enable gpu plugin
// default false,
// Note: Can not use "omitempty" option, it will affect the output of the default configuration file
GPUPluginEnabled bool `json:"gpuPluginEnabled"`
// ImageGCHighThreshold indicates image gc high threshold (percent)
// default 80
ImageGCHighThreshold int32 `json:"imageGCHighThreshold,omitempty"`
// ImageGCLowThreshold indicates image gc low threshold (percent)
// default 40
ImageGCLowThreshold int32 `json:"imageGCLowThreshold,omitempty"`
// MaximumDeadContainersPerPod indicates max num dead containers per pod
// default 1
MaximumDeadContainersPerPod int32 `json:"maximumDeadContainersPerPod,omitempty"`
// CGroupDriver indicates container cgroup driver, support: cgroupfs, systemd
// default "cgroupfs"
// +Required
CGroupDriver string `json:"cgroupDriver,omitempty"`
// NetworkPluginName indicates the name of the network plugin to be invoked,
// if an empty string is specified, use noop plugin
// default ""
NetworkPluginName string `json:"networkPluginName,omitempty"`
// CNIConfDir indicates the full path of the directory in which to search for CNI config files
// default "/etc/cni/net.d"
CNIConfDir string `json:"cniConfDir,omitempty"`
// CNIBinDir indicates a comma-separated list of full paths of directories
// in which to search for CNI plugin binaries
// default "/opt/cni/bin"
CNIBinDir string `json:"cniBinDir,omitempty"`
// CNICacheDir indicates the full path of the directory in which CNI should store cache files
// default "/var/lib/cni/cache"
CNICacheDir string `json:"cniCacheDirs,omitempty"`
// NetworkPluginMTU indicates the MTU to be passed to the network plugin
// default 1500
NetworkPluginMTU int32 `json:"networkPluginMTU,omitempty"`
// CgroupsPerQOS enables QoS based Cgroup hierarchy: top level cgroups for QoS Classes
// And all Burstable and BestEffort pods are brought up under their
// specific top level QoS cgroup.
// Default: true
CgroupsPerQOS bool `json:"cgroupsPerQOS"`
// CgroupRoot is the root cgroup to use for pods.
// If CgroupsPerQOS is enabled, this is the root of the QoS cgroup hierarchy.
// Default: ""
CgroupRoot string `json:"cgroupRoot"`
// EdgeCoreCgroups is the absolute name of cgroups to isolate the edgecore in
// Dynamic Kubelet Config (beta): This field should not be updated without a full node
// reboot. It is safest to keep this value the same as the local config.
// Default: ""
EdgeCoreCgroups string `json:"edgeCoreCgroups,omitempty"`
// systemCgroups is absolute name of cgroups in which to place
// all non-kernel processes that are not already in a container. Empty
// for no container. Rolling back the flag requires a reboot.
// Dynamic Kubelet Config (beta): This field should not be updated without a full node
// reboot. It is safest to keep this value the same as the local config.
// Default: ""
SystemCgroups string `json:"systemCgroups,omitempty"`
// How frequently to calculate and cache volume disk usage for all pods
// Dynamic Kubelet Config (beta): If dynamically updating this field, consider that
// shortening the period may carry a performance impact.
// Default: "1m"
VolumeStatsAggPeriod time.Duration `json:"volumeStatsAggPeriod,omitempty"`
// EnableMetrics indicates whether enable the metrics
// default true
EnableMetrics bool `json:"enableMetrics,omitempty"`
}
// EdgeHub indicates the EdgeHub module config
type EdgeHub struct {
// Enable indicates whether EdgeHub is enabled,
// if set to false (for debugging etc.), skip checking other EdgeHub configs.
// default true
Enable bool `json:"enable"`
// Heartbeat indicates heart beat (second)
// default 15
Heartbeat int32 `json:"heartbeat,omitempty"`
// MessageQPS is the QPS to allow while send message to cloudHub.
// DefaultQPS: 30
MessageQPS int32 `json:"messageQPS,omitempty"`
// MessageBurst is the burst to allow while send message to cloudHub.
// DefaultBurst: 60
MessageBurst int32 `json:"messageBurst,omitempty"`
// ProjectID indicates project id
// default e632aba927ea4ac2b575ec1603d56f10
ProjectID string `json:"projectID,omitempty"`
// TLSCAFile set ca file path
// default "/etc/kubeedge/ca/rootCA.crt"
TLSCAFile string `json:"tlsCaFile,omitempty"`
// TLSCertFile indicates the file containing x509 Certificate for HTTPS
// default "/etc/kubeedge/certs/server.crt"
TLSCertFile string `json:"tlsCertFile,omitempty"`
// TLSPrivateKeyFile indicates the file containing x509 private key matching tlsCertFile
// default "/etc/kubeedge/certs/server.key"
TLSPrivateKeyFile string `json:"tlsPrivateKeyFile,omitempty"`
// Quic indicates quic config for EdgeHub module
// Optional if websocket is configured
Quic *EdgeHubQUIC `json:"quic,omitempty"`
// WebSocket indicates websocket config for EdgeHub module
// Optional if quic is configured
WebSocket *EdgeHubWebSocket `json:"websocket,omitempty"`
// Token indicates the priority of joining the cluster for the edge
Token string `json:"token"`
// HTTPServer indicates the server for edge to apply for the certificate.
HTTPServer string `json:"httpServer,omitempty"`
// RotateCertificates indicates whether edge certificate can be rotated
// default true
RotateCertificates bool `json:"rotateCertificates,omitempty"`
}
// EdgeHubQUIC indicates the quic client config
type EdgeHubQUIC struct {
// Enable indicates whether enable this protocol
// default false
Enable bool `json:"enable"`
// HandshakeTimeout indicates handshake timeout (second)
// default 30
HandshakeTimeout int32 `json:"handshakeTimeout,omitempty"`
// ReadDeadline indicates read deadline (second)
// default 15
ReadDeadline int32 `json:"readDeadline,omitempty"`
// Server indicates quic server address (ip:port)
// +Required
Server string `json:"server,omitempty"`
// WriteDeadline indicates write deadline (second)
// default 15
WriteDeadline int32 `json:"writeDeadline,omitempty"`
}
// EdgeHubWebSocket indicates the websocket client config
type EdgeHubWebSocket struct {
// Enable indicates whether enable this protocol
// default true
Enable bool `json:"enable"`
// HandshakeTimeout indicates handshake timeout (second)
// default 30
HandshakeTimeout int32 `json:"handshakeTimeout,omitempty"`
// ReadDeadline indicates read deadline (second)
// default 15
ReadDeadline int32 `json:"readDeadline,omitempty"`
// Server indicates websocket server address (ip:port)
// +Required
Server string `json:"server,omitempty"`
// WriteDeadline indicates write deadline (second)
// default 15
WriteDeadline int32 `json:"writeDeadline,omitempty"`
}
// EventBus indicates the event bus module config
type EventBus struct {
// Enable indicates whether EventBus is enabled, if set to false (for debugging etc.),
// skip checking other EventBus configs.
// default true
Enable bool `json:"enable"`
// MqttQOS indicates mqtt qos
// 0: QOSAtMostOnce, 1: QOSAtLeastOnce, 2: QOSExactlyOnce
// default 0
// Note: Can not use "omitempty" option, It will affect the output of the default configuration file
MqttQOS uint8 `json:"mqttQOS"`
// MqttRetain indicates whether server will store the message and can be delivered to future subscribers,
// if this flag set true, sever will store the message and can be delivered to future subscribers
// default false
// Note: Can not use "omitempty" option, It will affect the output of the default configuration file
MqttRetain bool `json:"mqttRetain"`
// MqttSessionQueueSize indicates the size of how many sessions will be handled.
// default 100
MqttSessionQueueSize int32 `json:"mqttSessionQueueSize,omitempty"`
// MqttServerInternal indicates internal mqtt broker url
// default "tcp://127.0.0.1:1884"
MqttServerInternal string `json:"mqttServerInternal,omitempty"`
// MqttServerExternal indicates external mqtt broker url
// default "tcp://127.0.0.1:1883"
MqttServerExternal string `json:"mqttServerExternal,omitempty"`
// MqttSubClientID indicates mqtt subscribe ClientID
// default ""
MqttSubClientID string `json:"mqttSubClientID"`
// MqttPubClientID indicates mqtt publish ClientID
// default ""
MqttPubClientID string `json:"mqttPubClientID"`
// MqttUsername indicates mqtt username
// default ""
MqttUsername string `json:"mqttUsername"`
// MqttPassword indicates mqtt password
// default ""
MqttPassword string `json:"mqttPassword"`
// MqttMode indicates which broker type will be chosen
// 0: internal mqtt broker enable only.
// 1: internal and external mqtt broker enable.
// 2: external mqtt broker enable only
// +Required
// default: 2
MqttMode MqttMode `json:"mqttMode"`
// Tls indicates tls config for EventBus module
TLS *EventBusTLS `json:"eventBusTLS,omitempty"`
}
// EventBusTLS indicates the EventBus tls config with MQTT broker
type EventBusTLS struct {
// Enable indicates whether enable tls connection
// default false
Enable bool `json:"enable"`
// TLSMqttCAFile sets ca file path
// default "/etc/kubeedge/ca/rootCA.crt"
TLSMqttCAFile string `json:"tlsMqttCAFile,omitempty"`
// TLSMqttCertFile indicates the file containing x509 Certificate for HTTPS
// default "/etc/kubeedge/certs/server.crt"
TLSMqttCertFile string `json:"tlsMqttCertFile,omitempty"`
// TLSMqttPrivateKeyFile indicates the file containing x509 private key matching tlsMqttCertFile
// default "/etc/kubeedge/certs/server.key"
TLSMqttPrivateKeyFile string `json:"tlsMqttPrivateKeyFile,omitempty"`
}
// MetaManager indicates the MetaManager module config
type MetaManager struct {
// Enable indicates whether MetaManager is enabled,
// if set to false (for debugging etc.), skip checking other MetaManager configs.
// default true
Enable bool `json:"enable"`
// ContextSendGroup indicates send group
ContextSendGroup metaconfig.GroupName `json:"contextSendGroup,omitempty"`
// ContextSendModule indicates send module
ContextSendModule metaconfig.ModuleName `json:"contextSendModule,omitempty"`
// RemoteQueryTimeout indicates remote query timeout (second)
// default 60
RemoteQueryTimeout int32 `json:"remoteQueryTimeout,omitempty"`
// The config of MetaServer
MetaServer *MetaServer `json:"metaServer,omitempty"`
}
type MetaServer struct {
Enable bool `json:"enable"`
Server string `json:"server"`
TLSCaFile string `json:"tlsCaFile"`
TLSCertFile string `json:"tlsCertFile"`
TLSPrivateKeyFile string `json:"tlsPrivateKeyFile"`
}
// ServiceBus indicates the ServiceBus module config
type ServiceBus struct {
// Enable indicates whether ServiceBus is enabled,
// if set to false (for debugging etc.), skip checking other ServiceBus configs.
// default false
Enable bool `json:"enable"`
// Address indicates address for http server
Server string `json:"server"`
// Port indicates port for http server
Port int `json:"port"`
// Timeout indicates timeout for servicebus receive message
Timeout int `json:"timeout"`
}
// DeviceTwin indicates the DeviceTwin module config
type DeviceTwin struct {
// Enable indicates whether DeviceTwin is enabled,
// if set to false (for debugging etc.), skip checking other DeviceTwin configs.
// default true
Enable bool `json:"enable"`
}
// DBTest indicates the DBTest module config
type DBTest struct {
// Enable indicates whether DBTest is enabled,
// if set to false (for debugging etc.), skip checking other DBTest configs.
// default false
Enable bool `json:"enable"`
}
// EdgeStream indicates the stream controller
type EdgeStream struct {
// Enable indicates whether edgestream is enabled, if set to false (for debugging etc.), skip checking other configs.
// default true
Enable bool `json:"enable"`
// TLSTunnelCAFile indicates ca file path
// default /etc/kubeedge/ca/rootCA.crt
TLSTunnelCAFile string `json:"tlsTunnelCAFile,omitempty"`
// TLSTunnelCertFile indicates the file containing x509 Certificate for HTTPS
// default /etc/kubeedge/certs/server.crt
TLSTunnelCertFile string `json:"tlsTunnelCertFile,omitempty"`
// TLSTunnelPrivateKeyFile indicates the file containing x509 private key matching tlsCertFile
// default /etc/kubeedge/certs/server.key
TLSTunnelPrivateKeyFile string `json:"tlsTunnelPrivateKeyFile,omitempty"`
// HandshakeTimeout indicates handshake timeout (second)
// default 30
HandshakeTimeout int32 `json:"handshakeTimeout,omitempty"`
// ReadDeadline indicates read deadline (second)
// default 15
ReadDeadline int32 `json:"readDeadline,omitempty"`
// TunnelServer indicates websocket server address (ip:port)
// +Required
TunnelServer string `json:"server,omitempty"`
// WriteDeadline indicates write deadline (second)
// default 15
WriteDeadline int32 `json:"writeDeadline,omitempty"`
}

View File

@ -0,0 +1,154 @@
/*
Copyright 2019 The KubeEdge 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 validation
import (
"fmt"
"os"
"path"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/apis/core/validation"
"github.com/kubeedge/api/apis/componentconfig/edgecore/v1alpha1"
utilvalidation "github.com/kubeedge/api/apis/util/validation"
)
// ValidateEdgeCoreConfiguration validates `c` and returns an errorList if it is invalid
func ValidateEdgeCoreConfiguration(c *v1alpha1.EdgeCoreConfig) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateDataBase(*c.DataBase)...)
allErrs = append(allErrs, ValidateModuleEdged(*c.Modules.Edged)...)
allErrs = append(allErrs, ValidateModuleEdgeHub(*c.Modules.EdgeHub)...)
allErrs = append(allErrs, ValidateModuleEventBus(*c.Modules.EventBus)...)
allErrs = append(allErrs, ValidateModuleMetaManager(*c.Modules.MetaManager)...)
allErrs = append(allErrs, ValidateModuleServiceBus(*c.Modules.ServiceBus)...)
allErrs = append(allErrs, ValidateModuleDeviceTwin(*c.Modules.DeviceTwin)...)
allErrs = append(allErrs, ValidateModuleDBTest(*c.Modules.DBTest)...)
allErrs = append(allErrs, ValidateModuleEdgeStream(*c.Modules.EdgeStream)...)
return allErrs
}
// ValidateDataBase validates `db` and returns an errorList if it is invalid
func ValidateDataBase(db v1alpha1.DataBase) field.ErrorList {
allErrs := field.ErrorList{}
sourceDir := path.Dir(db.DataSource)
if !utilvalidation.FileIsExist(sourceDir) {
if err := os.MkdirAll(sourceDir, os.ModePerm); err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("DataSource"), db.DataSource,
fmt.Sprintf("create DataSoure dir %v error ", sourceDir)))
}
}
return allErrs
}
// ValidateModuleEdged validates `e` and returns an errorList if it is invalid
func ValidateModuleEdged(e v1alpha1.Edged) field.ErrorList {
if !e.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
messages := validation.ValidateNodeName(e.HostnameOverride, false)
for _, msg := range messages {
allErrs = append(allErrs, field.Invalid(field.NewPath("HostnameOverride"), e.HostnameOverride, msg))
}
if e.NodeIP == "" {
klog.Warningf("NodeIP is empty , use default ip which can connect to cloud.")
}
switch e.CGroupDriver {
case v1alpha1.CGroupDriverCGroupFS, v1alpha1.CGroupDriverSystemd:
default:
allErrs = append(allErrs, field.Invalid(field.NewPath("CGroupDriver"), e.CGroupDriver,
"CGroupDriver value error"))
}
return allErrs
}
// ValidateModuleEdgeHub validates `h` and returns an errorList if it is invalid
func ValidateModuleEdgeHub(h v1alpha1.EdgeHub) field.ErrorList {
if !h.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
if h.WebSocket.Enable == h.Quic.Enable {
allErrs = append(allErrs, field.Invalid(field.NewPath("enable"),
h.Quic.Enable, "websocket.enable and quic.enable cannot be true and false at the same time"))
}
return allErrs
}
// ValidateModuleEventBus validates `m` and returns an errorList if it is invalid
func ValidateModuleEventBus(m v1alpha1.EventBus) field.ErrorList {
if !m.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
if m.MqttMode > v1alpha1.MqttModeExternal || m.MqttMode < v1alpha1.MqttModeInternal {
allErrs = append(allErrs, field.Invalid(field.NewPath("Mode"), m.MqttMode,
fmt.Sprintf("Mode need in [%v,%v] range", v1alpha1.MqttModeInternal,
v1alpha1.MqttModeExternal)))
}
return allErrs
}
// ValidateModuleMetaManager validates `m` and returns an errorList if it is invalid
func ValidateModuleMetaManager(m v1alpha1.MetaManager) field.ErrorList {
if !m.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleServiceBus validates `s` and returns an errorList if it is invalid
func ValidateModuleServiceBus(s v1alpha1.ServiceBus) field.ErrorList {
if !s.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleDeviceTwin validates `d` and returns an errorList if it is invalid
func ValidateModuleDeviceTwin(d v1alpha1.DeviceTwin) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleDBTest validates `d` and returns an errorList if it is invalid
func ValidateModuleDBTest(d v1alpha1.DBTest) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleEdgeStream validates `m` and returns an errorList if it is invalid
func ValidateModuleEdgeStream(m v1alpha1.EdgeStream) field.ErrorList {
allErrs := field.ErrorList{}
if !m.Enable {
return allErrs
}
return allErrs
}

View File

@ -0,0 +1,356 @@
/*
Copyright 2021 The KubeEdge 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 validation
import (
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/kubeedge/api/apis/componentconfig/edgecore/v1alpha1"
)
func TestValidateEdgeCoreConfiguration(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "existFile")
if err != nil {
t.Errorf("create temp file failed: %v", err)
return
}
config := v1alpha1.NewDefaultEdgeCoreConfig()
config.DataBase.DataSource = ef.Name()
errList := ValidateEdgeCoreConfiguration(config)
if len(errList) > 0 {
t.Errorf("configuration is not right: %v", errList)
}
}
func TestValidateDataBase(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "FileIsExist")
if err == nil {
db := v1alpha1.DataBase{
DataSource: ef.Name(),
}
if errs := ValidateDataBase(db); len(errs) > 0 {
t.Errorf("file %v should exist: err is %v", db, errs)
}
}
nonexistentDir := filepath.Join(dir, "not_exists_dir")
nonexistentFile := filepath.Join(nonexistentDir, "not_exist_file")
db := v1alpha1.DataBase{
DataSource: nonexistentFile,
}
if errs := ValidateDataBase(db); len(errs) > 0 {
t.Errorf("file %v should not created, err is %v", nonexistentFile, errs)
}
}
func TestValidateModuleEdged(t *testing.T) {
cases := []struct {
name string
input v1alpha1.Edged
result field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.Edged{
Enable: false,
},
result: field.ErrorList{},
},
{
name: "case2 not right CGroupDriver",
input: v1alpha1.Edged{
Enable: true,
HostnameOverride: "example.com",
CGroupDriver: "fake",
},
result: field.ErrorList{field.Invalid(field.NewPath("CGroupDriver"), "fake",
"CGroupDriver value error")},
},
{
name: "case3 invalid hostname",
input: v1alpha1.Edged{
Enable: true,
HostnameOverride: "Example%$#com",
CGroupDriver: v1alpha1.CGroupDriverCGroupFS,
},
result: field.ErrorList{field.Invalid(field.NewPath("HostnameOverride"), "Example%$#com", `a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')`)},
},
{
name: "case4 success",
input: v1alpha1.Edged{
Enable: true,
HostnameOverride: "example.com",
CGroupDriver: v1alpha1.CGroupDriverCGroupFS,
},
result: field.ErrorList{},
},
}
for _, c := range cases {
if got := ValidateModuleEdged(c.input); !reflect.DeepEqual(got, c.result) {
t.Errorf("%v: expected %v, but got %v", c.name, c.result, got)
}
}
}
func TestValidateModuleEdgeHub(t *testing.T) {
cases := []struct {
name string
input v1alpha1.EdgeHub
result field.ErrorList
}{
{
name: "case1 not enable",
input: v1alpha1.EdgeHub{
Enable: false,
},
result: field.ErrorList{},
},
{
name: "case2 both quic and websocket are enabled",
input: v1alpha1.EdgeHub{
Enable: true,
Quic: &v1alpha1.EdgeHubQUIC{
Enable: true,
},
WebSocket: &v1alpha1.EdgeHubWebSocket{
Enable: true,
},
},
result: field.ErrorList{field.Invalid(field.NewPath("enable"),
true, "websocket.enable and quic.enable cannot be true and false at the same time")},
},
{
name: "case3 success",
input: v1alpha1.EdgeHub{
Enable: true,
WebSocket: &v1alpha1.EdgeHubWebSocket{
Enable: true,
},
Quic: &v1alpha1.EdgeHubQUIC{
Enable: false,
},
},
result: field.ErrorList{},
},
}
for _, c := range cases {
if got := ValidateModuleEdgeHub(c.input); !reflect.DeepEqual(got, c.result) {
t.Errorf("%v: expected %v, but got %v", c.name, c.result, got)
}
}
}
func TestValidateModuleEventBus(t *testing.T) {
cases := []struct {
name string
input v1alpha1.EventBus
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.EventBus{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 mqtt not right",
input: v1alpha1.EventBus{
Enable: true,
MqttMode: v1alpha1.MqttMode(3),
},
expected: field.ErrorList{field.Invalid(field.NewPath("Mode"), v1alpha1.MqttMode(3),
fmt.Sprintf("Mode need in [%v,%v] range", v1alpha1.MqttModeInternal,
v1alpha1.MqttModeExternal))},
},
{
name: "case2 all ok",
input: v1alpha1.EventBus{
Enable: true,
MqttMode: 2,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleEventBus(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleMetaManager(t *testing.T) {
cases := []struct {
name string
input v1alpha1.MetaManager
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.MetaManager{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha1.MetaManager{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleMetaManager(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleServiceBus(t *testing.T) {
cases := []struct {
name string
input v1alpha1.ServiceBus
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.ServiceBus{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha1.ServiceBus{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleServiceBus(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleDeviceTwin(t *testing.T) {
cases := []struct {
name string
input v1alpha1.DeviceTwin
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.DeviceTwin{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha1.DeviceTwin{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleDeviceTwin(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleDBTest(t *testing.T) {
cases := []struct {
name string
input v1alpha1.DBTest
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.DBTest{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha1.DBTest{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleDBTest(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleEdgeStream(t *testing.T) {
cases := []struct {
name string
input v1alpha1.EdgeStream
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha1.EdgeStream{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha1.EdgeStream{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleEdgeStream(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}

View File

@ -0,0 +1,234 @@
/*
Copyright 2022 The KubeEdge 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 v1alpha2
import (
"net"
"net/url"
"path"
"strconv"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/kubeedge/api/apis/common/constants"
metaconfig "github.com/kubeedge/api/apis/componentconfig/meta/v1alpha1"
"github.com/kubeedge/api/apis/util"
)
// NewDefaultEdgeCoreConfig returns a full EdgeCoreConfig object
func NewDefaultEdgeCoreConfig() (config *EdgeCoreConfig) {
hostnameOverride := util.GetHostname()
localIP, _ := util.GetLocalIP(hostnameOverride)
defaultTailedKubeletConfig := TailoredKubeletConfiguration{}
SetDefaultsKubeletConfiguration(&defaultTailedKubeletConfig)
config = &EdgeCoreConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
DataBase: &DataBase{
DriverName: DataBaseDriverName,
AliasName: DataBaseAliasName,
DataSource: DataBaseDataSource,
},
Modules: &Modules{
Edged: &Edged{
Enable: true,
ReportEvent: false,
TailoredKubeletConfig: &defaultTailedKubeletConfig,
TailoredKubeletFlag: TailoredKubeletFlag{
HostnameOverride: hostnameOverride,
ContainerRuntimeOptions: ContainerRuntimeOptions{
PodSandboxImage: constants.DefaultPodSandboxImage,
},
RootDirectory: constants.DefaultRootDir,
MaxContainerCount: -1,
MaxPerPodContainerCount: 1,
MinimumGCAge: metav1.Duration{Duration: 0},
NodeLabels: make(map[string]string),
RegisterSchedulable: true,
WindowsPriorityClass: DefaultWindowsPriorityClass,
},
CustomInterfaceName: "",
RegisterNodeNamespace: constants.DefaultRegisterNodeNamespace,
},
EdgeHub: &EdgeHub{
Enable: true,
Heartbeat: 15,
MessageQPS: constants.DefaultQPS,
MessageBurst: constants.DefaultBurst,
ProjectID: "e632aba927ea4ac2b575ec1603d56f10",
TLSCAFile: constants.DefaultCAFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
Quic: &EdgeHubQUIC{
Enable: false,
HandshakeTimeout: 30,
ReadDeadline: 15,
Server: net.JoinHostPort(localIP, "10001"),
WriteDeadline: 15,
},
WebSocket: &EdgeHubWebSocket{
Enable: true,
HandshakeTimeout: 30,
ReadDeadline: 15,
Server: net.JoinHostPort(localIP, "10000"),
WriteDeadline: 15,
},
HTTPServer: (&url.URL{
Scheme: "https",
Host: net.JoinHostPort(localIP, "10002"),
}).String(),
Token: "",
RotateCertificates: true,
},
EventBus: &EventBus{
Enable: true,
MqttQOS: 0,
MqttRetain: false,
MqttSessionQueueSize: 100,
MqttServerExternal: "tcp://127.0.0.1:1883",
MqttServerInternal: "tcp://127.0.0.1:1884",
MqttSubClientID: "",
MqttPubClientID: "",
MqttUsername: "",
MqttPassword: "",
MqttMode: MqttModeExternal,
TLS: &EventBusTLS{
Enable: false,
TLSMqttCAFile: constants.DefaultMqttCAFile,
TLSMqttCertFile: constants.DefaultMqttCertFile,
TLSMqttPrivateKeyFile: constants.DefaultMqttKeyFile,
},
},
MetaManager: &MetaManager{
Enable: true,
ContextSendGroup: metaconfig.GroupNameHub,
ContextSendModule: metaconfig.ModuleNameEdgeHub,
RemoteQueryTimeout: constants.DefaultRemoteQueryTimeout,
MetaServer: &MetaServer{
Enable: false,
Server: constants.DefaultMetaServerAddr,
TLSCaFile: constants.DefaultCAFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
ServiceAccountIssuers: []string{constants.DefaultServiceAccountIssuer},
DummyServer: constants.DefaultDummyServerAddr,
},
},
ServiceBus: &ServiceBus{
Enable: false,
Server: "127.0.0.1",
Port: 9060,
Timeout: 60,
},
DeviceTwin: &DeviceTwin{
Enable: true,
DMISockPath: constants.DefaultDMISockPath,
},
DBTest: &DBTest{
Enable: false,
},
EdgeStream: &EdgeStream{
Enable: false,
TLSTunnelCAFile: constants.DefaultCAFile,
TLSTunnelCertFile: constants.DefaultCertFile,
TLSTunnelPrivateKeyFile: constants.DefaultKeyFile,
HandshakeTimeout: 30,
ReadDeadline: 15,
TunnelServer: net.JoinHostPort("127.0.0.1", strconv.Itoa(constants.DefaultTunnelPort)),
WriteDeadline: 15,
},
},
}
return
}
// NewMinEdgeCoreConfig returns a common EdgeCoreConfig object
func NewMinEdgeCoreConfig() (config *EdgeCoreConfig) {
hostnameOverride := util.GetHostname()
localIP, _ := util.GetLocalIP(hostnameOverride)
defaultTailedKubeletConfig := TailoredKubeletConfiguration{}
SetDefaultsKubeletConfiguration(&defaultTailedKubeletConfig)
config = &EdgeCoreConfig{
TypeMeta: metav1.TypeMeta{
Kind: Kind,
APIVersion: path.Join(GroupName, APIVersion),
},
DataBase: &DataBase{
DataSource: DataBaseDataSource,
},
Modules: &Modules{
DeviceTwin: &DeviceTwin{
DMISockPath: constants.DefaultDMISockPath,
},
Edged: &Edged{
Enable: true,
TailoredKubeletConfig: &defaultTailedKubeletConfig,
TailoredKubeletFlag: TailoredKubeletFlag{
HostnameOverride: hostnameOverride,
ContainerRuntimeOptions: ContainerRuntimeOptions{
PodSandboxImage: constants.DefaultPodSandboxImage,
},
RootDirectory: constants.DefaultRootDir,
MaxContainerCount: -1,
MaxPerPodContainerCount: 1,
MinimumGCAge: metav1.Duration{Duration: 0},
NodeLabels: make(map[string]string),
RegisterSchedulable: true,
WindowsPriorityClass: DefaultWindowsPriorityClass,
},
CustomInterfaceName: "",
RegisterNodeNamespace: constants.DefaultRegisterNodeNamespace,
},
EdgeHub: &EdgeHub{
Heartbeat: 15,
TLSCAFile: constants.DefaultCAFile,
TLSCertFile: constants.DefaultCertFile,
TLSPrivateKeyFile: constants.DefaultKeyFile,
WebSocket: &EdgeHubWebSocket{
Enable: true,
HandshakeTimeout: 30,
ReadDeadline: 15,
Server: net.JoinHostPort(localIP, "10000"),
WriteDeadline: 15,
},
HTTPServer: (&url.URL{
Scheme: "https",
Host: net.JoinHostPort(localIP, "10002"),
}).String(),
Token: "",
},
EventBus: &EventBus{
MqttQOS: 0,
MqttRetain: false,
MqttServerExternal: "tcp://127.0.0.1:1883",
MqttServerInternal: "tcp://127.0.0.1:1884",
MqttSubClientID: "",
MqttPubClientID: "",
MqttUsername: "",
MqttPassword: "",
MqttMode: MqttModeExternal,
},
},
}
return
}

View File

@ -0,0 +1,108 @@
/*
Copyright 2023 The KubeEdge 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.
@CHANGELOG
KubeEdge Authors: To set default tailored kubelet configuration,
This file is derived from K8S Kubelet apis code with reduced set of methods
Changes done are
1. Package edged got some functions from "k8s.io/kubernetes/pkg/kubelet/apis/config/v1beta1"
and made some variant
*/
package v1alpha2
import (
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
logsapi "k8s.io/component-base/logs/api/v1"
kubeletconfigv1beta1 "k8s.io/kubelet/config/v1beta1"
configv1beta1 "k8s.io/kubernetes/pkg/kubelet/apis/config/v1beta1"
"k8s.io/kubernetes/pkg/kubelet/eviction"
"k8s.io/kubernetes/pkg/kubelet/qos"
utilpointer "k8s.io/utils/pointer"
"github.com/kubeedge/api/apis/common/constants"
)
// SetDefaultsKubeletConfiguration sets defaults for tailored kubelet configuration
func SetDefaultsKubeletConfiguration(obj *TailoredKubeletConfiguration) {
obj.StaticPodPath = constants.DefaultManifestsDir
obj.SyncFrequency = metav1.Duration{Duration: 1 * time.Minute}
obj.FileCheckFrequency = metav1.Duration{Duration: 20 * time.Second}
obj.Address = constants.ServerAddress
obj.ReadOnlyPort = constants.ServerPort
obj.ClusterDomain = constants.DefaultClusterDomain
obj.RegistryPullQPS = utilpointer.Int32(5)
obj.RegistryBurst = 10
obj.EventRecordQPS = utilpointer.Int32(50)
obj.EventBurst = 100
obj.EnableDebuggingHandlers = utilpointer.Bool(true)
obj.OOMScoreAdj = utilpointer.Int32(int32(qos.KubeletOOMScoreAdj))
obj.StreamingConnectionIdleTimeout = metav1.Duration{Duration: 4 * time.Hour}
obj.NodeStatusReportFrequency = metav1.Duration{Duration: 5 * time.Minute}
obj.NodeStatusUpdateFrequency = metav1.Duration{Duration: 10 * time.Second}
obj.NodeLeaseDurationSeconds = 40
obj.ImageMinimumGCAge = metav1.Duration{Duration: 2 * time.Minute}
// default is below docker's default dm.min_free_space of 90%
obj.ImageGCHighThresholdPercent = utilpointer.Int32(85)
obj.ImageGCLowThresholdPercent = utilpointer.Int32(80)
obj.VolumeStatsAggPeriod = metav1.Duration{Duration: time.Minute}
obj.CPUManagerPolicy = "none"
// Keep the same as default NodeStatusUpdateFrequency
obj.CPUManagerReconcilePeriod = metav1.Duration{Duration: 10 * time.Second}
obj.MemoryManagerPolicy = kubeletconfigv1beta1.NoneMemoryManagerPolicy
obj.TopologyManagerPolicy = kubeletconfigv1beta1.NoneTopologyManagerPolicy
obj.TopologyManagerScope = kubeletconfigv1beta1.ContainerTopologyManagerScope
obj.RuntimeRequestTimeout = metav1.Duration{Duration: 2 * time.Minute}
obj.HairpinMode = kubeletconfigv1beta1.PromiscuousBridge
obj.MaxPods = 110
// default nil or negative value to -1 (implies node allocatable pid limit)
obj.PodPidsLimit = utilpointer.Int64(-1)
obj.CPUCFSQuotaPeriod = &metav1.Duration{Duration: 100 * time.Millisecond}
obj.NodeStatusMaxImages = utilpointer.Int32(0)
obj.MaxOpenFiles = 1000000
obj.ContentType = "application/json"
obj.SerializeImagePulls = utilpointer.Bool(true)
obj.EvictionHard = eviction.DefaultEvictionHard
obj.EvictionPressureTransitionPeriod = metav1.Duration{Duration: 5 * time.Minute}
obj.EnableControllerAttachDetach = utilpointer.Bool(true)
obj.MakeIPTablesUtilChains = utilpointer.Bool(true)
obj.IPTablesMasqueradeBit = utilpointer.Int32(configv1beta1.DefaultIPTablesMasqueradeBit)
obj.IPTablesDropBit = utilpointer.Int32(configv1beta1.DefaultIPTablesDropBit)
obj.FailSwapOn = utilpointer.Bool(false)
obj.ContainerLogMaxSize = "10Mi"
obj.ContainerLogMaxFiles = utilpointer.Int32(5)
obj.ConfigMapAndSecretChangeDetectionStrategy = kubeletconfigv1beta1.GetChangeDetectionStrategy
obj.EnforceNodeAllocatable = DefaultNodeAllocatableEnforcement
obj.VolumePluginDir = constants.DefaultVolumePluginDir
// Use the Default LoggingConfiguration option
logsapi.SetRecommendedLoggingConfiguration(&obj.Logging)
obj.EnableSystemLogHandler = utilpointer.Bool(true)
obj.EnableProfilingHandler = utilpointer.Bool(true)
obj.EnableDebugFlagsHandler = utilpointer.Bool(true)
obj.SeccompDefault = utilpointer.Bool(false)
obj.MemoryThrottlingFactor = utilpointer.Float64(configv1beta1.DefaultMemoryThrottlingFactor)
obj.RegisterNode = utilpointer.Bool(true)
obj.EnforceNodeAllocatable = DefaultNodeAllocatableEnforcement
obj.CgroupDriver = DefaultCgroupDriver
obj.CgroupsPerQOS = utilpointer.Bool(DefaultCgroupsPerQOS)
obj.ResolverConfig = utilpointer.String(DefaultResolverConfig)
obj.CPUCFSQuota = utilpointer.Bool(DefaultCPUCFSQuota)
obj.LocalStorageCapacityIsolation = utilpointer.Bool(true)
obj.ContainerRuntimeEndpoint = constants.DefaultRemoteRuntimeEndpoint
obj.ImageServiceEndpoint = constants.DefaultRemoteImageEndpoint
}

View File

@ -0,0 +1,25 @@
//go:build !windows
package v1alpha2
import kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
const (
CGroupDriverCGroupFS = "cgroupfs"
CGroupDriverSystemd = "systemd"
// DataBaseDataSource is edge.db
DataBaseDataSource = "/var/lib/kubeedge/edgecore.db"
DefaultCgroupDriver = "cgroupfs"
DefaultCgroupsPerQOS = true
DefaultResolverConfig = kubetypes.ResolvConfDefault
DefaultCPUCFSQuota = true
DefaultWindowsPriorityClass = ""
)
var (
// TODO: Move these constants to k8s.io/kubelet/config/v1beta1 instead?
// Refer to [Node Allocatable](https://git.k8s.io/community/contributors/design-proposals/node/node-allocatable.md) doc for more information.
DefaultNodeAllocatableEnforcement = []string{"pods"}
)

View File

@ -0,0 +1,23 @@
//go:build windows
package v1alpha2
const (
CGroupDriverCGroupFS = "-"
CGroupDriverSystemd = ""
// DataBaseDataSource is edge.db
DataBaseDataSource = "C:\\var\\lib\\kubeedge\\edgecore.db"
DefaultCgroupDriver = ""
DefaultCgroupsPerQOS = false
DefaultResolverConfig = ""
DefaultCPUCFSQuota = false
DefaultWindowsPriorityClass = "NORMAL_PRIORITY_CLASS"
)
var (
// TODO: Move these constants to k8s.io/kubelet/config/v1beta1 instead?
// Refer to [Node Allocatable](https://git.k8s.io/community/contributors/design-proposals/node/node-allocatable.md) doc for more information.
DefaultNodeAllocatableEnforcement = []string{}
)

View File

@ -0,0 +1,38 @@
/*
Copyright 2022 The KubeEdge 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 v1alpha2
import (
"os"
"k8s.io/klog/v2"
"sigs.k8s.io/yaml"
)
func (c *EdgeCoreConfig) Parse(filename string) error {
data, err := os.ReadFile(filename)
if err != nil {
klog.Errorf("Failed to read configfile %s: %v", filename, err)
return err
}
err = yaml.Unmarshal(data, c)
if err != nil {
klog.Errorf("Failed to unmarshal configfile %s: %v", filename, err)
return err
}
return nil
}

View File

@ -0,0 +1,23 @@
/*
Copyright 2022 The KubeEdge 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 v1alpha2
const (
GroupName = "edgecore.config.kubeedge.io"
APIVersion = "v1alpha2"
Kind = "EdgeCore"
)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,161 @@
/*
Copyright 2022 The KubeEdge 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 validation
import (
"fmt"
"os"
"path"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/apis/core/validation"
"github.com/kubeedge/api/apis/componentconfig/edgecore/v1alpha2"
utilvalidation "github.com/kubeedge/api/apis/util/validation"
)
// ValidateEdgeCoreConfiguration validates `c` and returns an errorList if it is invalid
func ValidateEdgeCoreConfiguration(c *v1alpha2.EdgeCoreConfig) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateDataBase(*c.DataBase)...)
allErrs = append(allErrs, ValidateModuleEdged(*c.Modules.Edged)...)
allErrs = append(allErrs, ValidateModuleEdgeHub(*c.Modules.EdgeHub)...)
allErrs = append(allErrs, ValidateModuleEventBus(*c.Modules.EventBus)...)
allErrs = append(allErrs, ValidateModuleMetaManager(*c.Modules.MetaManager)...)
allErrs = append(allErrs, ValidateModuleServiceBus(*c.Modules.ServiceBus)...)
allErrs = append(allErrs, ValidateModuleDeviceTwin(*c.Modules.DeviceTwin)...)
allErrs = append(allErrs, ValidateModuleDBTest(*c.Modules.DBTest)...)
allErrs = append(allErrs, ValidateModuleEdgeStream(*c.Modules.EdgeStream)...)
return allErrs
}
// ValidateDataBase validates `db` and returns an errorList if it is invalid
func ValidateDataBase(db v1alpha2.DataBase) field.ErrorList {
allErrs := field.ErrorList{}
sourceDir := path.Dir(db.DataSource)
if !utilvalidation.FileIsExist(sourceDir) {
if err := os.MkdirAll(sourceDir, os.ModePerm); err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("DataSource"), db.DataSource,
fmt.Sprintf("create DataSoure dir %v error ", sourceDir)))
}
}
return allErrs
}
// ValidateModuleEdged validates `e` and returns an errorList if it is invalid
func ValidateModuleEdged(e v1alpha2.Edged) field.ErrorList {
if !e.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
messages := validation.ValidateNodeName(e.HostnameOverride, false)
for _, msg := range messages {
allErrs = append(allErrs, field.Invalid(field.NewPath("HostnameOverride"), e.HostnameOverride, msg))
}
if e.NodeIP == "" {
klog.Warningf("NodeIP is empty , use default ip which can connect to cloud.")
}
if err := ValidateCgroupDriver(e.TailoredKubeletConfig.CgroupDriver); err != nil {
allErrs = append(allErrs, err)
}
return allErrs
}
// ValidateModuleEdgeHub validates `h` and returns an errorList if it is invalid
func ValidateModuleEdgeHub(h v1alpha2.EdgeHub) field.ErrorList {
if !h.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
if h.WebSocket.Enable == h.Quic.Enable {
allErrs = append(allErrs, field.Invalid(field.NewPath("enable"),
h.Quic.Enable, "websocket.enable and quic.enable cannot be true and false at the same time"))
}
if h.MessageQPS < 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("messageQPS"), h.MessageQPS,
"MessageQPS must not be a negative number"))
}
if h.MessageBurst < 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("messageBurst"), h.MessageBurst,
"MessageBurst must not be a negative number"))
}
return allErrs
}
// ValidateModuleEventBus validates `m` and returns an errorList if it is invalid
func ValidateModuleEventBus(m v1alpha2.EventBus) field.ErrorList {
if !m.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
if m.MqttMode > v1alpha2.MqttModeExternal || m.MqttMode < v1alpha2.MqttModeInternal {
allErrs = append(allErrs, field.Invalid(field.NewPath("Mode"), m.MqttMode,
fmt.Sprintf("Mode need in [%v,%v] range", v1alpha2.MqttModeInternal,
v1alpha2.MqttModeExternal)))
}
return allErrs
}
// ValidateModuleMetaManager validates `m` and returns an errorList if it is invalid
func ValidateModuleMetaManager(m v1alpha2.MetaManager) field.ErrorList {
if !m.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleServiceBus validates `s` and returns an errorList if it is invalid
func ValidateModuleServiceBus(s v1alpha2.ServiceBus) field.ErrorList {
if !s.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleDeviceTwin validates `d` and returns an errorList if it is invalid
func ValidateModuleDeviceTwin(d v1alpha2.DeviceTwin) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleDBTest validates `d` and returns an errorList if it is invalid
func ValidateModuleDBTest(d v1alpha2.DBTest) field.ErrorList {
if !d.Enable {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
return allErrs
}
// ValidateModuleEdgeStream validates `m` and returns an errorList if it is invalid
func ValidateModuleEdgeStream(m v1alpha2.EdgeStream) field.ErrorList {
allErrs := field.ErrorList{}
if !m.Enable {
return allErrs
}
return allErrs
}

View File

@ -0,0 +1,20 @@
//go:build !windows
package validation
import (
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/kubeedge/api/apis/componentconfig/edgecore/v1alpha2"
)
// ValidateCgroupDriver validates `edged.TailoredKubeletConfig.CgroupDriver` and returns an errorList if it is invalid
func ValidateCgroupDriver(cgroupDriver string) *field.Error {
switch cgroupDriver {
case v1alpha2.CGroupDriverCGroupFS, v1alpha2.CGroupDriverSystemd:
default:
return field.Invalid(field.NewPath("CGroupDriver"), cgroupDriver,
"CGroupDriver value error")
}
return nil
}

View File

@ -0,0 +1,398 @@
/*
Copyright 2022 The KubeEdge 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 validation
import (
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/kubeedge/api/apis/componentconfig/edgecore/v1alpha2"
)
func TestValidateEdgeCoreConfiguration(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "existFile")
if err != nil {
t.Errorf("create temp file failed: %v", err)
return
}
config := v1alpha2.NewDefaultEdgeCoreConfig()
config.DataBase.DataSource = ef.Name()
errList := ValidateEdgeCoreConfiguration(config)
if len(errList) > 0 {
t.Errorf("configuration is not right: %v", errList)
}
}
func TestValidateDataBase(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "FileIsExist")
if err == nil {
db := v1alpha2.DataBase{
DataSource: ef.Name(),
}
if errs := ValidateDataBase(db); len(errs) > 0 {
t.Errorf("file %v should exist: err is %v", db, errs)
}
}
nonexistentDir := filepath.Join(dir, "not_exists_dir")
nonexistentFile := filepath.Join(nonexistentDir, "not_exist_file")
db := v1alpha2.DataBase{
DataSource: nonexistentFile,
}
if errs := ValidateDataBase(db); len(errs) > 0 {
t.Errorf("file %v should not created, err is %v", nonexistentFile, errs)
}
}
func TestValidateModuleEdged(t *testing.T) {
cases := []struct {
name string
input v1alpha2.Edged
result field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha2.Edged{
Enable: false,
},
result: field.ErrorList{},
},
{
name: "case2 not right CGroupDriver",
input: v1alpha2.Edged{
Enable: true,
TailoredKubeletFlag: v1alpha2.TailoredKubeletFlag{
HostnameOverride: "example.com",
},
TailoredKubeletConfig: &v1alpha2.TailoredKubeletConfiguration{
CgroupDriver: "fake",
},
},
result: field.ErrorList{field.Invalid(field.NewPath("CGroupDriver"), "fake",
"CGroupDriver value error")},
},
{
name: "case3 invalid hostname",
input: v1alpha2.Edged{
Enable: true,
TailoredKubeletFlag: v1alpha2.TailoredKubeletFlag{
HostnameOverride: "Example%$#com",
},
TailoredKubeletConfig: &v1alpha2.TailoredKubeletConfiguration{
CgroupDriver: v1alpha2.CGroupDriverCGroupFS,
},
},
result: field.ErrorList{field.Invalid(field.NewPath("HostnameOverride"), "Example%$#com", `a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')`)},
},
{
name: "case4 success",
input: v1alpha2.Edged{
Enable: true,
TailoredKubeletFlag: v1alpha2.TailoredKubeletFlag{
HostnameOverride: "example.com",
},
TailoredKubeletConfig: &v1alpha2.TailoredKubeletConfiguration{
CgroupDriver: v1alpha2.CGroupDriverCGroupFS,
},
},
result: field.ErrorList{},
},
}
for _, c := range cases {
if got := ValidateModuleEdged(c.input); !reflect.DeepEqual(got, c.result) {
t.Errorf("%v: expected %v, but got %v", c.name, c.result, got)
}
}
}
func TestValidateModuleEdgeHub(t *testing.T) {
cases := []struct {
name string
input v1alpha2.EdgeHub
result field.ErrorList
}{
{
name: "case1 not enable",
input: v1alpha2.EdgeHub{
Enable: false,
},
result: field.ErrorList{},
},
{
name: "case2 both quic and websocket are enabled",
input: v1alpha2.EdgeHub{
Enable: true,
Quic: &v1alpha2.EdgeHubQUIC{
Enable: true,
},
WebSocket: &v1alpha2.EdgeHubWebSocket{
Enable: true,
},
},
result: field.ErrorList{field.Invalid(field.NewPath("enable"),
true, "websocket.enable and quic.enable cannot be true and false at the same time")},
},
{
name: "case3 success",
input: v1alpha2.EdgeHub{
Enable: true,
WebSocket: &v1alpha2.EdgeHubWebSocket{
Enable: true,
},
Quic: &v1alpha2.EdgeHubQUIC{
Enable: false,
},
},
result: field.ErrorList{},
},
{
name: "case4 MessageQPS must not be a negative number",
input: v1alpha2.EdgeHub{
Enable: true,
WebSocket: &v1alpha2.EdgeHubWebSocket{
Enable: true,
},
Quic: &v1alpha2.EdgeHubQUIC{
Enable: false,
},
MessageQPS: -1,
},
result: field.ErrorList{field.Invalid(field.NewPath("messageQPS"),
int32(-1), "MessageQPS must not be a negative number")},
},
{
name: "case5 MessageBurst must not be a negative number",
input: v1alpha2.EdgeHub{
Enable: true,
WebSocket: &v1alpha2.EdgeHubWebSocket{
Enable: true,
},
Quic: &v1alpha2.EdgeHubQUIC{
Enable: false,
},
MessageBurst: -1,
},
result: field.ErrorList{field.Invalid(field.NewPath("messageBurst"),
int32(-1), "MessageBurst must not be a negative number")},
},
}
for _, c := range cases {
if got := ValidateModuleEdgeHub(c.input); !reflect.DeepEqual(got, c.result) {
t.Errorf("%v: expected %v, but got %v", c.name, c.result, got)
}
}
}
func TestValidateModuleEventBus(t *testing.T) {
cases := []struct {
name string
input v1alpha2.EventBus
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha2.EventBus{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 mqtt not right",
input: v1alpha2.EventBus{
Enable: true,
MqttMode: v1alpha2.MqttMode(3),
},
expected: field.ErrorList{field.Invalid(field.NewPath("Mode"), v1alpha2.MqttMode(3),
fmt.Sprintf("Mode need in [%v,%v] range", v1alpha2.MqttModeInternal,
v1alpha2.MqttModeExternal))},
},
{
name: "case2 all ok",
input: v1alpha2.EventBus{
Enable: true,
MqttMode: 2,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleEventBus(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleMetaManager(t *testing.T) {
cases := []struct {
name string
input v1alpha2.MetaManager
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha2.MetaManager{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha2.MetaManager{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleMetaManager(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleServiceBus(t *testing.T) {
cases := []struct {
name string
input v1alpha2.ServiceBus
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha2.ServiceBus{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha2.ServiceBus{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleServiceBus(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleDeviceTwin(t *testing.T) {
cases := []struct {
name string
input v1alpha2.DeviceTwin
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha2.DeviceTwin{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha2.DeviceTwin{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleDeviceTwin(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleDBTest(t *testing.T) {
cases := []struct {
name string
input v1alpha2.DBTest
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha2.DBTest{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha2.DBTest{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleDBTest(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}
func TestValidateModuleEdgeStream(t *testing.T) {
cases := []struct {
name string
input v1alpha2.EdgeStream
expected field.ErrorList
}{
{
name: "case1 not enabled",
input: v1alpha2.EdgeStream{
Enable: false,
},
expected: field.ErrorList{},
},
{
name: "case2 enabled",
input: v1alpha2.EdgeStream{
Enable: true,
},
expected: field.ErrorList{},
},
}
for _, c := range cases {
if result := ValidateModuleEdgeStream(c.input); !reflect.DeepEqual(result, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, result)
}
}
}

View File

@ -0,0 +1,10 @@
//go:build windows
package validation
import "k8s.io/apimachinery/pkg/util/validation/field"
// ValidateCgroupDriver validates `e` and returns an errorList if it is invalid
func ValidateCgroupDriver(cgroupDriver string) *field.Error {
return nil
}

View File

@ -0,0 +1,43 @@
/*
Copyright 2019 The KubeEdge 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 v1alpha1
type ModuleName string
type GroupName string
// Available modules for EdgeCore
const (
ModuleNameEventBus ModuleName = "eventbus"
ModuleNameServiceBus ModuleName = "servicebus"
// TODO @kadisi change websocket to edgehub
ModuleNameEdgeHub ModuleName = "websocket"
ModuleNameMetaManager ModuleName = "metamanager"
ModuleNameEdged ModuleName = "edged"
ModuleNameTwin ModuleName = "twin"
ModuleNameDBTest ModuleName = "dbTest"
)
// Available modules group
const (
GroupNameHub GroupName = "hub"
GroupNameEdgeController GroupName = "edgecontroller"
GroupNameBus GroupName = "bus"
GroupNameTwin GroupName = "twin"
GroupNameMeta GroupName = "meta"
GroupNameEdged GroupName = "edged"
GroupNameUser GroupName = "user"
)

View File

@ -0,0 +1,432 @@
/*
Copyright 2020 The KubeEdge 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 v1alpha2
import (
"encoding/json"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// DeviceSpec represents a single device instance. It is an instantation of a device model.
type DeviceSpec struct {
// Required: DeviceModelRef is reference to the device model used as a template
// to create the device instance.
DeviceModelRef *v1.LocalObjectReference `json:"deviceModelRef,omitempty"`
// Required: The protocol configuration used to connect to the device.
Protocol ProtocolConfig `json:"protocol,omitempty"`
// List of property visitors which describe how to access the device properties.
// PropertyVisitors must unique by propertyVisitor.propertyName.
// +optional
PropertyVisitors []DevicePropertyVisitor `json:"propertyVisitors,omitempty"`
// Data section describe a list of time-series properties which should be processed
// on edge node.
// +optional
Data DeviceData `json:"data,omitempty"`
// NodeSelector indicates the binding preferences between devices and nodes.
// Refer to k8s.io/kubernetes/pkg/apis/core NodeSelector for more details
// +optional
NodeSelector *v1.NodeSelector `json:"nodeSelector,omitempty"`
}
// Only one of its members may be specified.
type ProtocolConfig struct {
// Protocol configuration for opc-ua
// +optional
OpcUA *ProtocolConfigOpcUA `json:"opcua,omitempty"`
// Protocol configuration for modbus
// +optional
Modbus *ProtocolConfigModbus `json:"modbus,omitempty"`
// Protocol configuration for bluetooth
// +optional
Bluetooth *ProtocolConfigBluetooth `json:"bluetooth,omitempty"`
// Configuration for protocol common part
// +optional
Common *ProtocolConfigCommon `json:"common,omitempty"`
// Configuration for customized protocol
// +optional
CustomizedProtocol *ProtocolConfigCustomized `json:"customizedProtocol,omitempty"`
}
type ProtocolConfigOpcUA struct {
// Required: The URL for opc server endpoint.
URL string `json:"url,omitempty"`
// Username for access opc server.
// +optional
UserName string `json:"userName,omitempty"`
// Password for access opc server.
// +optional
Password string `json:"password,omitempty"`
// Defaults to "none".
// +optional
SecurityPolicy string `json:"securityPolicy,omitempty"`
// Defaults to "none".
// +optional
SecurityMode string `json:"securityMode,omitempty"`
// Certificate for access opc server.
// +optional
Certificate string `json:"certificate,omitempty"`
// PrivateKey for access opc server.
// +optional
PrivateKey string `json:"privateKey,omitempty"`
// Timeout seconds for the opc server connection.???
// +optional
Timeout int64 `json:"timeout,omitempty"`
}
// Only one of its members may be specified.
type ProtocolConfigModbus struct {
// Required. 0-255
SlaveID *int64 `json:"slaveID,omitempty"`
}
// Only one of COM or TCP may be specified.
type ProtocolConfigCommon struct {
// +optional
COM *ProtocolConfigCOM `json:"com,omitempty"`
// +optional
TCP *ProtocolConfigTCP `json:"tcp,omitempty"`
// Communication type, like tcp client, tcp server or COM
// +optional
CommType string `json:"commType,omitempty"`
// Reconnection timeout
// +optional
ReconnTimeout int64 `json:"reconnTimeout,omitempty"`
// Reconnecting retry times
// +optional
ReconnRetryTimes int64 `json:"reconnRetryTimes,omitempty"`
// Define timeout of mapper collect from device.
// +optional
CollectTimeout int64 `json:"collectTimeout,omitempty"`
// Define retry times of mapper will collect from device.
// +optional
CollectRetryTimes int64 `json:"collectRetryTimes,omitempty"`
// Define collect type, sync or async.
// +optional
// +kubebuilder:validation:Enum=sync;async
CollectType string `json:"collectType,omitempty"`
// Customized values for provided protocol
// +optional
// +kubebuilder:validation:XPreserveUnknownFields
CustomizedValues *CustomizedValue `json:"customizedValues,omitempty"`
}
type ProtocolConfigTCP struct {
// Required.
IP string `json:"ip,omitempty"`
// Required.
Port int64 `json:"port,omitempty"`
}
type ProtocolConfigCOM struct {
// Required.
SerialPort string `json:"serialPort,omitempty"`
// Required. BaudRate 115200|57600|38400|19200|9600|4800|2400|1800|1200|600|300|200|150|134|110|75|50
// +kubebuilder:validation:Enum=115200;57600;38400;19200;9600;4800;2400;1800;1200;600;300;200;150;134;110;75;50
BaudRate int64 `json:"baudRate,omitempty"`
// Required. Valid values are 8, 7, 6, 5.
// +kubebuilder:validation:Enum=8;7;6;5
DataBits int64 `json:"dataBits,omitempty"`
// Required. Valid options are "none", "even", "odd". Defaults to "none".
// +kubebuilder:validation:Enum=none;even;odd
Parity string `json:"parity,omitempty"`
// Required. Bit that stops 1|2
// +kubebuilder:validation:Enum=1;2
StopBits int64 `json:"stopBits,omitempty"`
}
type ProtocolConfigBluetooth struct {
// Unique identifier assigned to the device.
// +optional
MACAddress string `json:"macAddress,omitempty"`
}
type ProtocolConfigCustomized struct {
// Unique protocol name
// Required.
ProtocolName string `json:"protocolName,omitempty"`
// Any config data
// +optional
// +kubebuilder:validation:XPreserveUnknownFields
ConfigData *CustomizedValue `json:"configData,omitempty"`
}
// DeviceStatus reports the device state and the desired/reported values of twin attributes.
type DeviceStatus struct {
// A list of device twins containing desired/reported desired/reported values of twin properties.
// Optional: A passive device won't have twin properties and this list could be empty.
// +optional
Twins []Twin `json:"twins,omitempty"`
}
// Twin provides a logical representation of control properties (writable properties in the
// device model). The properties can have a Desired state and a Reported state. The cloud configures
// the `Desired`state of a device property and this configuration update is pushed to the edge node.
// The mapper sends a command to the device to change this property value as per the desired state .
// It receives the `Reported` state of the property once the previous operation is complete and sends
// the reported state to the cloud. Offline device interaction in the edge is possible via twin
// properties for control/command operations.
type Twin struct {
// Required: The property name for which the desired/reported values are specified.
// This property should be present in the device model.
PropertyName string `json:"propertyName,omitempty"`
// Required: the desired property value.
Desired TwinProperty `json:"desired,omitempty"`
// Required: the reported property value.
Reported TwinProperty `json:"reported,omitempty"`
}
// TwinProperty represents the device property for which an Expected/Actual state can be defined.
type TwinProperty struct {
// Required: The value for this property.
Value string `json:"value,"`
// Additional metadata like timestamp when the value was reported etc.
// +optional
Metadata map[string]string `json:"metadata,omitempty"`
}
// DeviceData reports the device's time-series data to edge MQTT broker.
// These data should not be processed by edgecore. Instead, they can be processed by
// third-party data-processing apps like EMQX kuiper.
type DeviceData struct {
// Required: A list of data properties, which are not required to be processed by edgecore
DataProperties []DataProperty `json:"dataProperties,omitempty"`
// Topic used by mapper, all data collected from dataProperties
// should be published to this topic,
// the default value is $ke/events/device/+/data/update
// +optional
DataTopic string `json:"dataTopic,omitempty"`
}
// DataProperty represents the device property for external use.
type DataProperty struct {
// Required: The property name for which should be processed by external apps.
// This property should be present in the device model.
PropertyName string `json:"propertyName,omitempty"`
// Additional metadata like timestamp when the value was reported etc.
// +optional
Metadata map[string]string `json:"metadata,omitempty"`
}
// DevicePropertyVisitor describes the specifics of accessing a particular device
// property. Visitors are intended to be consumed by device mappers which connect to devices
// and collect data / perform actions on the device.
type DevicePropertyVisitor struct {
// Required: The device property name to be accessed. This should refer to one of the
// device properties defined in the device model.
PropertyName string `json:"propertyName,omitempty"`
// Define how frequent mapper will report the value.
// +optional
ReportCycle int64 `json:"reportCycle,omitempty"`
// Define how frequent mapper will collect from device.
// +optional
CollectCycle int64 `json:"collectCycle,omitempty"`
// Customized values for visitor of provided protocols
// +optional
// +kubebuilder:validation:XPreserveUnknownFields
CustomizedValues *CustomizedValue `json:"customizedValues,omitempty"`
// Required: Protocol relevant config details about the how to access the device property.
VisitorConfig `json:",inline"`
}
// At least one of its members must be specified.
type VisitorConfig struct {
// Opcua represents a set of additional visitor config fields of opc-ua protocol.
// +optional
OpcUA *VisitorConfigOPCUA `json:"opcua,omitempty"`
// Modbus represents a set of additional visitor config fields of modbus protocol.
// +optional
Modbus *VisitorConfigModbus `json:"modbus,omitempty"`
// Bluetooth represents a set of additional visitor config fields of bluetooth protocol.
// +optional
Bluetooth *VisitorConfigBluetooth `json:"bluetooth,omitempty"`
// CustomizedProtocol represents a set of visitor config fields of bluetooth protocol.
// +optional
CustomizedProtocol *VisitorConfigCustomized `json:"customizedProtocol,omitempty"`
}
// Common visitor configurations for bluetooth protocol
type VisitorConfigBluetooth struct {
// Required: Unique ID of the corresponding operation
CharacteristicUUID string `json:"characteristicUUID,omitempty"`
// Responsible for converting the data coming from the platform into a form that is understood by the bluetooth device
// For example: "ON":[1], "OFF":[0]
// +optional
DataWriteToBluetooth map[string][]byte `json:"dataWrite,omitempty"`
// Responsible for converting the data being read from the bluetooth device into a form that is understandable by the platform
// +optional
BluetoothDataConverter BluetoothReadConverter `json:"dataConverter,omitempty"`
}
// Specifies the operations that may need to be performed to convert the data
type BluetoothReadConverter struct {
// Required: Specifies the start index of the incoming byte stream to be considered to convert the data.
// For example: start-index:2, end-index:3 concatenates the value present at second and third index of the incoming byte stream. If we want to reverse the order we can give it as start-index:3, end-index:2
StartIndex int `json:"startIndex,omitempty"`
// Required: Specifies the end index of incoming byte stream to be considered to convert the data
// the value specified should be inclusive for example if 3 is specified it includes the third index
EndIndex int `json:"endIndex,omitempty"`
// Refers to the number of bits to shift left, if left-shift operation is necessary for conversion
// +optional
ShiftLeft uint `json:"shiftLeft,omitempty"`
// Refers to the number of bits to shift right, if right-shift operation is necessary for conversion
// +optional
ShiftRight uint `json:"shiftRight,omitempty"`
// Specifies in what order the operations(which are required to be performed to convert incoming data into understandable form) are performed
// +optional
OrderOfOperations []BluetoothOperations `json:"orderOfOperations,omitempty"`
}
// Specify the operation that should be performed to convert incoming data into understandable form
type BluetoothOperations struct {
// Required: Specifies the operation to be performed to convert incoming data
BluetoothOperationType BluetoothArithmeticOperationType `json:"operationType,omitempty"`
// Required: Specifies with what value the operation is to be performed
BluetoothOperationValue float64 `json:"operationValue,omitempty"`
}
// Operations supported by Bluetooth protocol to convert the value being read from the device into an understandable form
// +kubebuilder:validation:Enum:Add;Subtract;Multiply;Divide
type BluetoothArithmeticOperationType string
// Bluetooth Protocol Operation type
const (
BluetoothAdd BluetoothArithmeticOperationType = "Add"
BluetoothSubtract BluetoothArithmeticOperationType = "Subtract"
BluetoothMultiply BluetoothArithmeticOperationType = "Multiply"
BluetoothDivide BluetoothArithmeticOperationType = "Divide"
)
// Common visitor configurations for opc-ua protocol
type VisitorConfigOPCUA struct {
// Required: The ID of opc-ua node, e.g. "ns=1,i=1005"
NodeID string `json:"nodeID,omitempty"`
// The name of opc-ua node
BrowseName string `json:"browseName,omitempty"`
}
// Common visitor configurations for modbus protocol
type VisitorConfigModbus struct {
// Required: Type of register
Register ModbusRegisterType `json:"register,omitempty"`
// Required: Offset indicates the starting register number to read/write data.
Offset *int64 `json:"offset,omitempty"`
// Required: Limit number of registers to read/write.
Limit *int64 `json:"limit,omitempty"`
// The scale to convert raw property data into final units.
// Defaults to 1.0
// +optional
Scale float64 `json:"scale,omitempty"`
// Indicates whether the high and low byte swapped.
// Defaults to false.
// +optional
IsSwap bool `json:"isSwap,omitempty"`
// Indicates whether the high and low register swapped.
// Defaults to false.
// +optional
IsRegisterSwap bool `json:"isRegisterSwap,omitempty"`
}
// The Modbus register type to read a device property.
// +kubebuilder:validation:Enum=CoilRegister;DiscreteInputRegister;InputRegister;HoldingRegister
type ModbusRegisterType string
// Modbus protocol register types
const (
ModbusRegisterTypeCoilRegister ModbusRegisterType = "CoilRegister"
ModbusRegisterTypeDiscreteInputRegister ModbusRegisterType = "DiscreteInputRegister"
ModbusRegisterTypeInputRegister ModbusRegisterType = "InputRegister"
ModbusRegisterTypeHoldingRegister ModbusRegisterType = "HoldingRegister"
)
// Common visitor configurations for customized protocol
type VisitorConfigCustomized struct {
// Required: name of customized protocol
ProtocolName string `json:"protocolName,omitempty"`
// Required: The configData of customized protocol
// +kubebuilder:validation:XPreserveUnknownFields
ConfigData *CustomizedValue `json:"configData,omitempty"`
}
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Device is the Schema for the devices API
// +k8s:openapi-gen=true
type Device struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DeviceSpec `json:"spec,omitempty"`
Status DeviceStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DeviceList contains a list of Device
type DeviceList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Device `json:"items"`
}
// CustomizedValue contains a map type data
// +kubebuilder:validation:Type=object
type CustomizedValue struct {
Data map[string]interface{} `json:"-"`
}
// MarshalJSON implements the Marshaler interface.
func (in *CustomizedValue) MarshalJSON() ([]byte, error) {
return json.Marshal(in.Data)
}
// UnmarshalJSON implements the Unmarshaler interface.
func (in *CustomizedValue) UnmarshalJSON(data []byte) error {
var out map[string]interface{}
err := json.Unmarshal(data, &out)
if err != nil {
return err
}
in.Data = out
return nil
}
// DeepCopyInto implements the DeepCopyInto interface.
func (in *CustomizedValue) DeepCopyInto(out *CustomizedValue) {
bytes, err := json.Marshal(*in)
if err != nil {
panic(err)
}
var clone map[string]interface{}
err = json.Unmarshal(bytes, &clone)
if err != nil {
panic(err)
}
out.Data = clone
}
// DeepCopy implements the DeepCopy interface.
func (in *CustomizedValue) DeepCopy() *CustomizedValue {
if in == nil {
return nil
}
out := new(CustomizedValue)
in.DeepCopyInto(out)
return out
}

View File

@ -0,0 +1,150 @@
/*
Copyright 2020 The KubeEdge 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 v1alpha2
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// DeviceModelSpec defines the model / template for a device.It is a blueprint which describes the device
// capabilities and access mechanism via property visitors.
type DeviceModelSpec struct {
// Required for DMI: Protocol name used by the device.
Protocol string `json:"protocol,omitempty"`
// Required: List of device properties.
Properties []DeviceProperty `json:"properties,omitempty"`
}
// DeviceProperty describes an individual device property / attribute like temperature / humidity etc.
type DeviceProperty struct {
// Required: The device property name.
Name string `json:"name,omitempty"`
// The device property description.
// +optional
Description string `json:"description,omitempty"`
// Required: PropertyType represents the type and data validation of the property.
Type PropertyType `json:"type,omitempty"`
}
// Represents the type and data validation of a property.
// Only one of its members may be specified.
type PropertyType struct {
// +optional
Int *PropertyTypeInt64 `json:"int,omitempty"`
// +optional
String *PropertyTypeString `json:"string,omitempty"`
// +optional
Double *PropertyTypeDouble `json:"double,omitempty"`
// +optional
Float *PropertyTypeFloat `json:"float,omitempty"`
// +optional
Boolean *PropertyTypeBoolean `json:"boolean,omitempty"`
// +optional
Bytes *PropertyTypeBytes `json:"bytes,omitempty"`
}
type PropertyTypeInt64 struct {
// Required: Access mode of property, ReadWrite or ReadOnly.
AccessMode PropertyAccessMode `json:"accessMode,omitempty"`
// +optional
DefaultValue int64 `json:"defaultValue,omitempty"`
// +optional
Minimum int64 `json:"minimum,omitempty"`
// +optional
Maximum int64 `json:"maximum,omitempty"`
// The unit of the property
// +optional
Unit string `json:"unit,omitempty"`
}
type PropertyTypeString struct {
// Required: Access mode of property, ReadWrite or ReadOnly.
AccessMode PropertyAccessMode `json:"accessMode,omitempty"`
// +optional
DefaultValue string `json:"defaultValue,omitempty"`
}
type PropertyTypeDouble struct {
// Required: Access mode of property, ReadWrite or ReadOnly.
AccessMode PropertyAccessMode `json:"accessMode,omitempty"`
// +optional
DefaultValue float64 `json:"defaultValue,omitempty"`
// +optional
Minimum float64 `json:"minimum,omitempty"`
// +optional
Maximum float64 `json:"maximum,omitempty"`
// The unit of the property
// +optional
Unit string `json:"unit,omitempty"`
}
type PropertyTypeFloat struct {
// Required: Access mode of property, ReadWrite or ReadOnly.
AccessMode PropertyAccessMode `json:"accessMode,omitempty"`
// +optional
DefaultValue float32 `json:"defaultValue,omitempty"`
// +optional
Minimum float32 `json:"minimum,omitempty"`
// +optional
Maximum float32 `json:"maximum,omitempty"`
// The unit of the property
// +optional
Unit string `json:"unit,omitempty"`
}
type PropertyTypeBoolean struct {
// Required: Access mode of property, ReadWrite or ReadOnly.
AccessMode PropertyAccessMode `json:"accessMode,omitempty"`
// +optional
DefaultValue bool `json:"defaultValue,omitempty"`
}
type PropertyTypeBytes struct {
// Required: Access mode of property, ReadWrite or ReadOnly.
AccessMode PropertyAccessMode `json:"accessMode,omitempty"`
}
// The access mode for a device property.
// +kubebuilder:validation:Enum=ReadWrite;ReadOnly
type PropertyAccessMode string
// Access mode constants for a device property.
const (
ReadWrite PropertyAccessMode = "ReadWrite"
ReadOnly PropertyAccessMode = "ReadOnly"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DeviceModel is the Schema for the device model API
// +k8s:openapi-gen=true
type DeviceModel struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DeviceModelSpec `json:"spec,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DeviceModelList contains a list of DeviceModel
type DeviceModelList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []DeviceModel `json:"items"`
}

View File

@ -0,0 +1,19 @@
/*
Copyright 2019 The KubeEdge 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.
*/
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package
package v1alpha2

View File

@ -0,0 +1,84 @@
/*
Copyright 2019 The KubeEdge 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.
*/
// NOTE: Boilerplate only. Ignore this file.
// Package v1alpha2 contains API Schema definitions for the devices v1alpha2 API group
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=kubeedge/cloud/pkg/apis/devices
// +k8s:defaulter-gen=TypeMeta
// +groupName=devices.kubeedge.io
package v1alpha2
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
const (
// GroupName is the group name use in this package.
GroupName = "devices.kubeedge.io"
// Version is the API version.
Version = "v1alpha2"
)
var (
// SchemeGroupVersion is the group version used to register these objects.
SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: Version}
)
func init() {
// 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.
localSchemeBuilder.Register(addKnownTypes)
}
// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Device{},
&DeviceList{},
&DeviceModel{},
&DeviceModelList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
func AddDeviceCrds(scheme *runtime.Scheme) error {
// Add Device
scheme.AddKnownTypes(SchemeGroupVersion, &Device{}, &DeviceList{})
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
// Add DeviceModel
scheme.AddKnownTypes(SchemeGroupVersion, &DeviceModel{}, &DeviceModelList{})
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -0,0 +1,839 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The KubeEdge 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 deepcopy-gen. DO NOT EDIT.
package v1alpha2
import (
v1 "k8s.io/api/core/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *BluetoothOperations) DeepCopyInto(out *BluetoothOperations) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BluetoothOperations.
func (in *BluetoothOperations) DeepCopy() *BluetoothOperations {
if in == nil {
return nil
}
out := new(BluetoothOperations)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *BluetoothReadConverter) DeepCopyInto(out *BluetoothReadConverter) {
*out = *in
if in.OrderOfOperations != nil {
in, out := &in.OrderOfOperations, &out.OrderOfOperations
*out = make([]BluetoothOperations, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BluetoothReadConverter.
func (in *BluetoothReadConverter) DeepCopy() *BluetoothReadConverter {
if in == nil {
return nil
}
out := new(BluetoothReadConverter)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DataProperty) DeepCopyInto(out *DataProperty) {
*out = *in
if in.Metadata != nil {
in, out := &in.Metadata, &out.Metadata
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DataProperty.
func (in *DataProperty) DeepCopy() *DataProperty {
if in == nil {
return nil
}
out := new(DataProperty)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Device) DeepCopyInto(out *Device) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Device.
func (in *Device) DeepCopy() *Device {
if in == nil {
return nil
}
out := new(Device)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Device) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceData) DeepCopyInto(out *DeviceData) {
*out = *in
if in.DataProperties != nil {
in, out := &in.DataProperties, &out.DataProperties
*out = make([]DataProperty, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceData.
func (in *DeviceData) DeepCopy() *DeviceData {
if in == nil {
return nil
}
out := new(DeviceData)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceList) DeepCopyInto(out *DeviceList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Device, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceList.
func (in *DeviceList) DeepCopy() *DeviceList {
if in == nil {
return nil
}
out := new(DeviceList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DeviceList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceModel) DeepCopyInto(out *DeviceModel) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceModel.
func (in *DeviceModel) DeepCopy() *DeviceModel {
if in == nil {
return nil
}
out := new(DeviceModel)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DeviceModel) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceModelList) DeepCopyInto(out *DeviceModelList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]DeviceModel, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceModelList.
func (in *DeviceModelList) DeepCopy() *DeviceModelList {
if in == nil {
return nil
}
out := new(DeviceModelList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DeviceModelList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceModelSpec) DeepCopyInto(out *DeviceModelSpec) {
*out = *in
if in.Properties != nil {
in, out := &in.Properties, &out.Properties
*out = make([]DeviceProperty, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceModelSpec.
func (in *DeviceModelSpec) DeepCopy() *DeviceModelSpec {
if in == nil {
return nil
}
out := new(DeviceModelSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceProperty) DeepCopyInto(out *DeviceProperty) {
*out = *in
in.Type.DeepCopyInto(&out.Type)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceProperty.
func (in *DeviceProperty) DeepCopy() *DeviceProperty {
if in == nil {
return nil
}
out := new(DeviceProperty)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DevicePropertyVisitor) DeepCopyInto(out *DevicePropertyVisitor) {
*out = *in
if in.CustomizedValues != nil {
in, out := &in.CustomizedValues, &out.CustomizedValues
*out = (*in).DeepCopy()
}
in.VisitorConfig.DeepCopyInto(&out.VisitorConfig)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DevicePropertyVisitor.
func (in *DevicePropertyVisitor) DeepCopy() *DevicePropertyVisitor {
if in == nil {
return nil
}
out := new(DevicePropertyVisitor)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceSpec) DeepCopyInto(out *DeviceSpec) {
*out = *in
if in.DeviceModelRef != nil {
in, out := &in.DeviceModelRef, &out.DeviceModelRef
*out = new(v1.LocalObjectReference)
**out = **in
}
in.Protocol.DeepCopyInto(&out.Protocol)
if in.PropertyVisitors != nil {
in, out := &in.PropertyVisitors, &out.PropertyVisitors
*out = make([]DevicePropertyVisitor, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
in.Data.DeepCopyInto(&out.Data)
if in.NodeSelector != nil {
in, out := &in.NodeSelector, &out.NodeSelector
*out = new(v1.NodeSelector)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceSpec.
func (in *DeviceSpec) DeepCopy() *DeviceSpec {
if in == nil {
return nil
}
out := new(DeviceSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceStatus) DeepCopyInto(out *DeviceStatus) {
*out = *in
if in.Twins != nil {
in, out := &in.Twins, &out.Twins
*out = make([]Twin, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceStatus.
func (in *DeviceStatus) DeepCopy() *DeviceStatus {
if in == nil {
return nil
}
out := new(DeviceStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PropertyType) DeepCopyInto(out *PropertyType) {
*out = *in
if in.Int != nil {
in, out := &in.Int, &out.Int
*out = new(PropertyTypeInt64)
**out = **in
}
if in.String != nil {
in, out := &in.String, &out.String
*out = new(PropertyTypeString)
**out = **in
}
if in.Double != nil {
in, out := &in.Double, &out.Double
*out = new(PropertyTypeDouble)
**out = **in
}
if in.Float != nil {
in, out := &in.Float, &out.Float
*out = new(PropertyTypeFloat)
**out = **in
}
if in.Boolean != nil {
in, out := &in.Boolean, &out.Boolean
*out = new(PropertyTypeBoolean)
**out = **in
}
if in.Bytes != nil {
in, out := &in.Bytes, &out.Bytes
*out = new(PropertyTypeBytes)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PropertyType.
func (in *PropertyType) DeepCopy() *PropertyType {
if in == nil {
return nil
}
out := new(PropertyType)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PropertyTypeBoolean) DeepCopyInto(out *PropertyTypeBoolean) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PropertyTypeBoolean.
func (in *PropertyTypeBoolean) DeepCopy() *PropertyTypeBoolean {
if in == nil {
return nil
}
out := new(PropertyTypeBoolean)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PropertyTypeBytes) DeepCopyInto(out *PropertyTypeBytes) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PropertyTypeBytes.
func (in *PropertyTypeBytes) DeepCopy() *PropertyTypeBytes {
if in == nil {
return nil
}
out := new(PropertyTypeBytes)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PropertyTypeDouble) DeepCopyInto(out *PropertyTypeDouble) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PropertyTypeDouble.
func (in *PropertyTypeDouble) DeepCopy() *PropertyTypeDouble {
if in == nil {
return nil
}
out := new(PropertyTypeDouble)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PropertyTypeFloat) DeepCopyInto(out *PropertyTypeFloat) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PropertyTypeFloat.
func (in *PropertyTypeFloat) DeepCopy() *PropertyTypeFloat {
if in == nil {
return nil
}
out := new(PropertyTypeFloat)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PropertyTypeInt64) DeepCopyInto(out *PropertyTypeInt64) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PropertyTypeInt64.
func (in *PropertyTypeInt64) DeepCopy() *PropertyTypeInt64 {
if in == nil {
return nil
}
out := new(PropertyTypeInt64)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PropertyTypeString) DeepCopyInto(out *PropertyTypeString) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PropertyTypeString.
func (in *PropertyTypeString) DeepCopy() *PropertyTypeString {
if in == nil {
return nil
}
out := new(PropertyTypeString)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfig) DeepCopyInto(out *ProtocolConfig) {
*out = *in
if in.OpcUA != nil {
in, out := &in.OpcUA, &out.OpcUA
*out = new(ProtocolConfigOpcUA)
**out = **in
}
if in.Modbus != nil {
in, out := &in.Modbus, &out.Modbus
*out = new(ProtocolConfigModbus)
(*in).DeepCopyInto(*out)
}
if in.Bluetooth != nil {
in, out := &in.Bluetooth, &out.Bluetooth
*out = new(ProtocolConfigBluetooth)
**out = **in
}
if in.Common != nil {
in, out := &in.Common, &out.Common
*out = new(ProtocolConfigCommon)
(*in).DeepCopyInto(*out)
}
if in.CustomizedProtocol != nil {
in, out := &in.CustomizedProtocol, &out.CustomizedProtocol
*out = new(ProtocolConfigCustomized)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfig.
func (in *ProtocolConfig) DeepCopy() *ProtocolConfig {
if in == nil {
return nil
}
out := new(ProtocolConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfigBluetooth) DeepCopyInto(out *ProtocolConfigBluetooth) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfigBluetooth.
func (in *ProtocolConfigBluetooth) DeepCopy() *ProtocolConfigBluetooth {
if in == nil {
return nil
}
out := new(ProtocolConfigBluetooth)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfigCOM) DeepCopyInto(out *ProtocolConfigCOM) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfigCOM.
func (in *ProtocolConfigCOM) DeepCopy() *ProtocolConfigCOM {
if in == nil {
return nil
}
out := new(ProtocolConfigCOM)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfigCommon) DeepCopyInto(out *ProtocolConfigCommon) {
*out = *in
if in.COM != nil {
in, out := &in.COM, &out.COM
*out = new(ProtocolConfigCOM)
**out = **in
}
if in.TCP != nil {
in, out := &in.TCP, &out.TCP
*out = new(ProtocolConfigTCP)
**out = **in
}
if in.CustomizedValues != nil {
in, out := &in.CustomizedValues, &out.CustomizedValues
*out = (*in).DeepCopy()
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfigCommon.
func (in *ProtocolConfigCommon) DeepCopy() *ProtocolConfigCommon {
if in == nil {
return nil
}
out := new(ProtocolConfigCommon)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfigCustomized) DeepCopyInto(out *ProtocolConfigCustomized) {
*out = *in
if in.ConfigData != nil {
in, out := &in.ConfigData, &out.ConfigData
*out = (*in).DeepCopy()
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfigCustomized.
func (in *ProtocolConfigCustomized) DeepCopy() *ProtocolConfigCustomized {
if in == nil {
return nil
}
out := new(ProtocolConfigCustomized)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfigModbus) DeepCopyInto(out *ProtocolConfigModbus) {
*out = *in
if in.SlaveID != nil {
in, out := &in.SlaveID, &out.SlaveID
*out = new(int64)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfigModbus.
func (in *ProtocolConfigModbus) DeepCopy() *ProtocolConfigModbus {
if in == nil {
return nil
}
out := new(ProtocolConfigModbus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfigOpcUA) DeepCopyInto(out *ProtocolConfigOpcUA) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfigOpcUA.
func (in *ProtocolConfigOpcUA) DeepCopy() *ProtocolConfigOpcUA {
if in == nil {
return nil
}
out := new(ProtocolConfigOpcUA)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfigTCP) DeepCopyInto(out *ProtocolConfigTCP) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfigTCP.
func (in *ProtocolConfigTCP) DeepCopy() *ProtocolConfigTCP {
if in == nil {
return nil
}
out := new(ProtocolConfigTCP)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Twin) DeepCopyInto(out *Twin) {
*out = *in
in.Desired.DeepCopyInto(&out.Desired)
in.Reported.DeepCopyInto(&out.Reported)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Twin.
func (in *Twin) DeepCopy() *Twin {
if in == nil {
return nil
}
out := new(Twin)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TwinProperty) DeepCopyInto(out *TwinProperty) {
*out = *in
if in.Metadata != nil {
in, out := &in.Metadata, &out.Metadata
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TwinProperty.
func (in *TwinProperty) DeepCopy() *TwinProperty {
if in == nil {
return nil
}
out := new(TwinProperty)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VisitorConfig) DeepCopyInto(out *VisitorConfig) {
*out = *in
if in.OpcUA != nil {
in, out := &in.OpcUA, &out.OpcUA
*out = new(VisitorConfigOPCUA)
**out = **in
}
if in.Modbus != nil {
in, out := &in.Modbus, &out.Modbus
*out = new(VisitorConfigModbus)
(*in).DeepCopyInto(*out)
}
if in.Bluetooth != nil {
in, out := &in.Bluetooth, &out.Bluetooth
*out = new(VisitorConfigBluetooth)
(*in).DeepCopyInto(*out)
}
if in.CustomizedProtocol != nil {
in, out := &in.CustomizedProtocol, &out.CustomizedProtocol
*out = new(VisitorConfigCustomized)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VisitorConfig.
func (in *VisitorConfig) DeepCopy() *VisitorConfig {
if in == nil {
return nil
}
out := new(VisitorConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VisitorConfigBluetooth) DeepCopyInto(out *VisitorConfigBluetooth) {
*out = *in
if in.DataWriteToBluetooth != nil {
in, out := &in.DataWriteToBluetooth, &out.DataWriteToBluetooth
*out = make(map[string][]byte, len(*in))
for key, val := range *in {
var outVal []byte
if val == nil {
(*out)[key] = nil
} else {
in, out := &val, &outVal
*out = make([]byte, len(*in))
copy(*out, *in)
}
(*out)[key] = outVal
}
}
in.BluetoothDataConverter.DeepCopyInto(&out.BluetoothDataConverter)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VisitorConfigBluetooth.
func (in *VisitorConfigBluetooth) DeepCopy() *VisitorConfigBluetooth {
if in == nil {
return nil
}
out := new(VisitorConfigBluetooth)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VisitorConfigCustomized) DeepCopyInto(out *VisitorConfigCustomized) {
*out = *in
if in.ConfigData != nil {
in, out := &in.ConfigData, &out.ConfigData
*out = (*in).DeepCopy()
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VisitorConfigCustomized.
func (in *VisitorConfigCustomized) DeepCopy() *VisitorConfigCustomized {
if in == nil {
return nil
}
out := new(VisitorConfigCustomized)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VisitorConfigModbus) DeepCopyInto(out *VisitorConfigModbus) {
*out = *in
if in.Offset != nil {
in, out := &in.Offset, &out.Offset
*out = new(int64)
**out = **in
}
if in.Limit != nil {
in, out := &in.Limit, &out.Limit
*out = new(int64)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VisitorConfigModbus.
func (in *VisitorConfigModbus) DeepCopy() *VisitorConfigModbus {
if in == nil {
return nil
}
out := new(VisitorConfigModbus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VisitorConfigOPCUA) DeepCopyInto(out *VisitorConfigOPCUA) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VisitorConfigOPCUA.
func (in *VisitorConfigOPCUA) DeepCopy() *VisitorConfigOPCUA {
if in == nil {
return nil
}
out := new(VisitorConfigOPCUA)
in.DeepCopyInto(out)
return out
}

View File

@ -0,0 +1,359 @@
/*
Copyright 2023 The KubeEdge 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 v1beta1
import (
"encoding/json"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// DeviceSpec represents a single device instance.
type DeviceSpec struct {
// Required: DeviceModelRef is reference to the device model used as a template
// to create the device instance.
DeviceModelRef *v1.LocalObjectReference `json:"deviceModelRef,omitempty"`
// NodeName is a request to schedule this device onto a specific node. If it is non-empty,
// the scheduler simply schedules this device onto that node, assuming that it fits
// resource requirements.
// +optional
NodeName string `json:"nodeName,omitempty"`
// List of properties which describe the device properties.
// properties list item must be unique by properties.Name.
// +optional
Properties []DeviceProperty `json:"properties,omitempty"`
// Required: The protocol configuration used to connect to the device.
Protocol ProtocolConfig `json:"protocol,omitempty"`
// List of methods of device.
// methods list item must be unique by method.Name.
// +optional
Methods []DeviceMethod `json:"methods,omitempty"`
}
// DeviceStatus reports the device state and the desired/reported values of twin attributes.
type DeviceStatus struct {
// A list of device twins containing desired/reported desired/reported values of twin properties.
// Optional: A passive device won't have twin properties and this list could be empty.
// +optional
Twins []Twin `json:"twins,omitempty"`
// Optional: The state of the device.
// +optional
State string `json:"state,omitempty"`
// Optional: The last time the device was online.
// +optional
LastOnlineTime string `json:"lastOnlineTime,omitempty"`
// Optional: whether be reported to the cloud
// +optional
ReportToCloud bool `json:"reportToCloud,omitempty"`
// Optional: Define how frequent mapper will report the device status.
// +optional
ReportCycle int64 `json:"reportCycle,omitempty"`
}
// Twin provides a logical representation of control properties (writable properties in the
// device model). The properties can have a Desired state and a Reported state. The cloud configures
// the `Desired`state of a device property and this configuration update is pushed to the edge node.
// The mapper sends a command to the device to change this property value as per the desired state .
// It receives the `Reported` state of the property once the previous operation is complete and sends
// the reported state to the cloud. Offline device interaction in the edge is possible via twin
// properties for control/command operations.
type Twin struct {
// Required: The property name for which the desired/reported values are specified.
// This property should be present in the device model.
PropertyName string `json:"propertyName,omitempty"`
// Required: the reported property value.
Reported TwinProperty `json:"reported,omitempty"`
// The meaning of here is to indicate desired value of `deviceProperty.Desired`
// that the mapper has received in current cycle.
// Useful in cases that people want to check whether the mapper is working
// appropriately and its internal status is up-to-date.
// This value should be only updated by devicecontroller upstream.
ObservedDesired TwinProperty `json:"observedDesired,omitempty"`
}
// TwinProperty represents the device property for which an Expected/Actual state can be defined.
type TwinProperty struct {
// Required: The value for this property.
Value string `json:"value,"`
// Additional metadata like timestamp when the value was reported etc.
// +optional
Metadata map[string]string `json:"metadata,omitempty"`
}
type ProtocolConfig struct {
// Unique protocol name
// Required.
ProtocolName string `json:"protocolName,omitempty"`
// Any config data
// +optional
// +kubebuilder:validation:XPreserveUnknownFields
ConfigData *CustomizedValue `json:"configData,omitempty"`
}
// DeviceMethod describes the specifics all the methods of the device.
type DeviceMethod struct {
// Required: The device method name to be accessed. It must be unique.
Name string `json:"name,omitempty"`
// Define the description of device method.
// +optional
Description string `json:"description,omitempty"`
// PropertyNames are list of device properties that device methods can control.
// Required: A device method can control multiple device properties.
PropertyNames []string `json:"propertyNames,omitempty"`
}
// DeviceProperty describes the specifics all the properties of the device.
type DeviceProperty struct {
// Required: The device property name to be accessed. It must be unique.
// Note: If you need to use the built-in stream data processing function, you need to define Name as saveFrame or saveVideo
Name string `json:"name,omitempty"`
// The desired property value.
Desired TwinProperty `json:"desired,omitempty"`
// Visitors are intended to be consumed by device mappers which connect to devices
// and collect data / perform actions on the device.
// Required: Protocol relevant config details about the how to access the device property.
Visitors VisitorConfig `json:"visitors,omitempty"`
// Define how frequent mapper will report the value.
// +optional
ReportCycle int64 `json:"reportCycle,omitempty"`
// Define how frequent mapper will collect from device.
// +optional
CollectCycle int64 `json:"collectCycle,omitempty"`
// whether be reported to the cloud
ReportToCloud bool `json:"reportToCloud,omitempty"`
// PushMethod represents the protocol used to push data,
// please ensure that the mapper can access the destination address.
// +optional
PushMethod *PushMethod `json:"pushMethod,omitempty"`
}
type PushMethod struct {
// HTTP Push method configuration for http
// +optional
HTTP *PushMethodHTTP `json:"http,omitempty"`
// MQTT Push method configuration for mqtt
// +optional
MQTT *PushMethodMQTT `json:"mqtt,omitempty"`
// OTEL Push Method configuration for otel
// +optional
OTEL *PushMethodOTEL `json:"otel,omitempty"`
// DBMethod represents the method used to push data to database,
// please ensure that the mapper can access the destination address.
// +optional
DBMethod *DBMethodConfig `json:"dbMethod,omitempty"`
}
type PushMethodHTTP struct {
// +optional
HostName string `json:"hostName,omitempty"`
// +optional
Port int64 `json:"port,omitempty"`
// +optional
RequestPath string `json:"requestPath,omitempty"`
// +optional
Timeout int64 `json:"timeout,omitempty"`
}
type PushMethodMQTT struct {
// broker address, like mqtt://127.0.0.1:1883
// +optional
Address string `json:"address,omitempty"`
// publish topic for mqtt
// +optional
Topic string `json:"topic,omitempty"`
// qos of mqtt publish param
// +optional
QoS int32 `json:"qos,omitempty"`
// Is the message retained
// +optional
Retained bool `json:"retained,omitempty"`
}
type PushMethodOTEL struct {
// the target endpoint URL the Exporter will connect to, like https://localhost:4318/v1/metrics
EndpointURL string `protobuf:"bytes,1,opt,name=endpointURL,proto3" json:"endpointURL,omitempty"`
}
type DBMethodConfig struct {
// method configuration for database
// +optional
Influxdb2 *DBMethodInfluxdb2 `json:"influxdb2,omitempty"`
// +optional
Redis *DBMethodRedis `json:"redis,omitempty"`
// +optional
TDEngine *DBMethodTDEngine `json:"TDEngine,omitempty"`
// +optional
Mysql *DBMethodMySQL `json:"mysql,omitempty"`
}
type DBMethodInfluxdb2 struct {
// Config of influx database
// +optional
Influxdb2ClientConfig *Influxdb2ClientConfig `json:"influxdb2ClientConfig"`
// config of device data when push to influx database
// +optional
Influxdb2DataConfig *Influxdb2DataConfig `json:"influxdb2DataConfig"`
}
type Influxdb2ClientConfig struct {
// Url of influx database
// +optional
URL string `json:"url,omitempty"`
// Org of the user in influx database
// +optional
Org string `json:"org,omitempty"`
// Bucket of the user in influx database
// +optional
Bucket string `json:"bucket,omitempty"`
}
type Influxdb2DataConfig struct {
// Measurement of the user data
// +optional
Measurement string `json:"measurement,omitempty"`
// the tag of device data
// +optional
Tag map[string]string `json:"tag,omitempty"`
// FieldKey of the user data
// +optional
FieldKey string `json:"fieldKey,omitempty"`
}
type DBMethodRedis struct {
// RedisClientConfig of redis database
// +optional
RedisClientConfig *RedisClientConfig `json:"redisClientConfig,omitempty"`
}
type RedisClientConfig struct {
// Addr of Redis database
// +optional
Addr string `json:"addr,omitempty"`
// Db of Redis database
// +optional
DB int `json:"db,omitempty"`
// Poolsize of Redis database
// +optional
Poolsize int `json:"poolsize,omitempty"`
// MinIdleConns of Redis database
// +optional
MinIdleConns int `json:"minIdleConns,omitempty"`
}
type DBMethodTDEngine struct {
// tdengineClientConfig of tdengine database
// +optional
TDEngineClientConfig *TDEngineClientConfig `json:"TDEngineClientConfig,omitempty"`
}
type TDEngineClientConfig struct {
// addr of tdEngine database
// +optional
Addr string `json:"addr,omitempty"`
// dbname of tdEngine database
// +optional
DBName string `json:"dbName,omitempty"`
}
type DBMethodMySQL struct {
MySQLClientConfig *MySQLClientConfig `json:"mysqlClientConfig,omitempty"`
}
type MySQLClientConfig struct {
// mysql address,like localhost:3306
Addr string `protobuf:"bytes,1,opt,name=addr,proto3" json:"addr,omitempty"`
// database name
Database string `protobuf:"bytes,2,opt,name=database,proto3" json:"database,omitempty"`
// user name
UserName string `protobuf:"bytes,3,opt,name=userName,proto3" json:"userName,omitempty"`
}
type VisitorConfig struct {
// Required: name of customized protocol
ProtocolName string `json:"protocolName,omitempty"`
// Required: The configData of customized protocol
// +kubebuilder:validation:XPreserveUnknownFields
ConfigData *CustomizedValue `json:"configData,omitempty"`
}
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Device is the Schema for the devices API
// +k8s:openapi-gen=true
// +kubebuilder:storageversion
type Device struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DeviceSpec `json:"spec,omitempty"`
Status DeviceStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DeviceList contains a list of Device
type DeviceList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Device `json:"items"`
}
// CustomizedValue contains a map type data
// +kubebuilder:validation:Type=object
type CustomizedValue struct {
Data map[string]interface{} `json:"-"`
}
// MarshalJSON implements the Marshaler interface.
func (in *CustomizedValue) MarshalJSON() ([]byte, error) {
return json.Marshal(in.Data)
}
// UnmarshalJSON implements the Unmarshaler interface.
func (in *CustomizedValue) UnmarshalJSON(data []byte) error {
var out map[string]interface{}
err := json.Unmarshal(data, &out)
if err != nil {
return err
}
in.Data = out
return nil
}
// DeepCopyInto implements the DeepCopyInto interface.
func (in *CustomizedValue) DeepCopyInto(out *CustomizedValue) {
bytes, err := json.Marshal(*in)
if err != nil {
panic(err)
}
var clone map[string]interface{}
err = json.Unmarshal(bytes, &clone)
if err != nil {
panic(err)
}
out.Data = clone
}
// DeepCopy implements the DeepCopy interface.
func (in *CustomizedValue) DeepCopy() *CustomizedValue {
if in == nil {
return nil
}
out := new(CustomizedValue)
in.DeepCopyInto(out)
return out
}

View File

@ -0,0 +1,97 @@
/*
Copyright 2023 The KubeEdge 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 v1beta1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// DeviceModelSpec defines the model for a device.It is a blueprint which describes the device
// capabilities and access mechanism via property visitors.
type DeviceModelSpec struct {
// Required: List of device properties.
Properties []ModelProperty `json:"properties,omitempty"`
// Required: Protocol name used by the device.
Protocol string `json:"protocol,omitempty"`
}
// ModelProperty describes an individual device property / attribute like temperature / humidity etc.
type ModelProperty struct {
// Required: The device property name.
// Note: If you need to use the built-in stream data processing function, you need to define Name as saveFrame or saveVideo
Name string `json:"name,omitempty"`
// The device property description.
// +optional
Description string `json:"description,omitempty"`
// Required: Type of device property, ENUM: INT,FLOAT,DOUBLE,STRING,BOOLEAN,BYTES,STREAM
Type PropertyType `json:"type,omitempty"`
// Required: Access mode of property, ReadWrite or ReadOnly.
AccessMode PropertyAccessMode `json:"accessMode,omitempty"`
// +optional
Minimum string `json:"minimum,omitempty"`
// +optional
Maximum string `json:"maximum,omitempty"`
// The unit of the property
// +optional
Unit string `json:"unit,omitempty"`
}
// The type of device property.
// +kubebuilder:validation:Enum=INT;FLOAT;DOUBLE;STRING;BOOLEAN;BYTES;STREAM
type PropertyType string
const (
INT PropertyType = "INT"
FLOAT PropertyType = "FLOAT"
DOUBLE PropertyType = "DOUBLE"
STRING PropertyType = "STRING"
BOOLEAN PropertyType = "BOOLEAN"
BYTES PropertyType = "BYTES"
STREAM PropertyType = "STREAM"
)
// The access mode for a device property.
// +kubebuilder:validation:Enum=ReadWrite;ReadOnly
type PropertyAccessMode string
// Access mode constants for a device property.
const (
ReadWrite PropertyAccessMode = "ReadWrite"
ReadOnly PropertyAccessMode = "ReadOnly"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DeviceModel is the Schema for the device model API
// +k8s:openapi-gen=true
// +kubebuilder:storageversion
type DeviceModel struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DeviceModelSpec `json:"spec,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DeviceModelList contains a list of DeviceModel
type DeviceModelList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []DeviceModel `json:"items"`
}

View File

@ -0,0 +1,19 @@
/*
Copyright 2023 The KubeEdge 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.
*/
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package
package v1beta1

View File

@ -0,0 +1,84 @@
/*
Copyright 2023 The KubeEdge 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.
*/
// NOTE: Boilerplate only. Ignore this file.
// Package v1beta1 contains API Schema definitions for the devices v1beta1 API group
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=kubeedge/cloud/pkg/apis/devices
// +k8s:defaulter-gen=TypeMeta
// +groupName=devices.kubeedge.io
package v1beta1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
const (
// GroupName is the group name use in this package.
GroupName = "devices.kubeedge.io"
// Version is the API version.
Version = "v1beta1"
)
var (
// SchemeGroupVersion is the group version used to register these objects.
SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: Version}
)
func init() {
// 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.
localSchemeBuilder.Register(addKnownTypes)
}
// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Device{},
&DeviceList{},
&DeviceModel{},
&DeviceModelList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
func AddDeviceCrds(scheme *runtime.Scheme) error {
// Add Device
scheme.AddKnownTypes(SchemeGroupVersion, &Device{}, &DeviceList{})
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
// Add DeviceModel
scheme.AddKnownTypes(SchemeGroupVersion, &DeviceModel{}, &DeviceModelList{})
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -0,0 +1,665 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The KubeEdge 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 deepcopy-gen. DO NOT EDIT.
package v1beta1
import (
v1 "k8s.io/api/core/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DBMethodConfig) DeepCopyInto(out *DBMethodConfig) {
*out = *in
if in.Influxdb2 != nil {
in, out := &in.Influxdb2, &out.Influxdb2
*out = new(DBMethodInfluxdb2)
(*in).DeepCopyInto(*out)
}
if in.Redis != nil {
in, out := &in.Redis, &out.Redis
*out = new(DBMethodRedis)
(*in).DeepCopyInto(*out)
}
if in.TDEngine != nil {
in, out := &in.TDEngine, &out.TDEngine
*out = new(DBMethodTDEngine)
(*in).DeepCopyInto(*out)
}
if in.Mysql != nil {
in, out := &in.Mysql, &out.Mysql
*out = new(DBMethodMySQL)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DBMethodConfig.
func (in *DBMethodConfig) DeepCopy() *DBMethodConfig {
if in == nil {
return nil
}
out := new(DBMethodConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DBMethodInfluxdb2) DeepCopyInto(out *DBMethodInfluxdb2) {
*out = *in
if in.Influxdb2ClientConfig != nil {
in, out := &in.Influxdb2ClientConfig, &out.Influxdb2ClientConfig
*out = new(Influxdb2ClientConfig)
**out = **in
}
if in.Influxdb2DataConfig != nil {
in, out := &in.Influxdb2DataConfig, &out.Influxdb2DataConfig
*out = new(Influxdb2DataConfig)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DBMethodInfluxdb2.
func (in *DBMethodInfluxdb2) DeepCopy() *DBMethodInfluxdb2 {
if in == nil {
return nil
}
out := new(DBMethodInfluxdb2)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DBMethodMySQL) DeepCopyInto(out *DBMethodMySQL) {
*out = *in
if in.MySQLClientConfig != nil {
in, out := &in.MySQLClientConfig, &out.MySQLClientConfig
*out = new(MySQLClientConfig)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DBMethodMySQL.
func (in *DBMethodMySQL) DeepCopy() *DBMethodMySQL {
if in == nil {
return nil
}
out := new(DBMethodMySQL)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DBMethodRedis) DeepCopyInto(out *DBMethodRedis) {
*out = *in
if in.RedisClientConfig != nil {
in, out := &in.RedisClientConfig, &out.RedisClientConfig
*out = new(RedisClientConfig)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DBMethodRedis.
func (in *DBMethodRedis) DeepCopy() *DBMethodRedis {
if in == nil {
return nil
}
out := new(DBMethodRedis)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DBMethodTDEngine) DeepCopyInto(out *DBMethodTDEngine) {
*out = *in
if in.TDEngineClientConfig != nil {
in, out := &in.TDEngineClientConfig, &out.TDEngineClientConfig
*out = new(TDEngineClientConfig)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DBMethodTDEngine.
func (in *DBMethodTDEngine) DeepCopy() *DBMethodTDEngine {
if in == nil {
return nil
}
out := new(DBMethodTDEngine)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Device) DeepCopyInto(out *Device) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Device.
func (in *Device) DeepCopy() *Device {
if in == nil {
return nil
}
out := new(Device)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Device) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceList) DeepCopyInto(out *DeviceList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Device, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceList.
func (in *DeviceList) DeepCopy() *DeviceList {
if in == nil {
return nil
}
out := new(DeviceList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DeviceList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceMethod) DeepCopyInto(out *DeviceMethod) {
*out = *in
if in.PropertyNames != nil {
in, out := &in.PropertyNames, &out.PropertyNames
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceMethod.
func (in *DeviceMethod) DeepCopy() *DeviceMethod {
if in == nil {
return nil
}
out := new(DeviceMethod)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceModel) DeepCopyInto(out *DeviceModel) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceModel.
func (in *DeviceModel) DeepCopy() *DeviceModel {
if in == nil {
return nil
}
out := new(DeviceModel)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DeviceModel) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceModelList) DeepCopyInto(out *DeviceModelList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]DeviceModel, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceModelList.
func (in *DeviceModelList) DeepCopy() *DeviceModelList {
if in == nil {
return nil
}
out := new(DeviceModelList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DeviceModelList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceModelSpec) DeepCopyInto(out *DeviceModelSpec) {
*out = *in
if in.Properties != nil {
in, out := &in.Properties, &out.Properties
*out = make([]ModelProperty, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceModelSpec.
func (in *DeviceModelSpec) DeepCopy() *DeviceModelSpec {
if in == nil {
return nil
}
out := new(DeviceModelSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceProperty) DeepCopyInto(out *DeviceProperty) {
*out = *in
in.Desired.DeepCopyInto(&out.Desired)
in.Visitors.DeepCopyInto(&out.Visitors)
if in.PushMethod != nil {
in, out := &in.PushMethod, &out.PushMethod
*out = new(PushMethod)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceProperty.
func (in *DeviceProperty) DeepCopy() *DeviceProperty {
if in == nil {
return nil
}
out := new(DeviceProperty)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceSpec) DeepCopyInto(out *DeviceSpec) {
*out = *in
if in.DeviceModelRef != nil {
in, out := &in.DeviceModelRef, &out.DeviceModelRef
*out = new(v1.LocalObjectReference)
**out = **in
}
if in.Properties != nil {
in, out := &in.Properties, &out.Properties
*out = make([]DeviceProperty, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
in.Protocol.DeepCopyInto(&out.Protocol)
if in.Methods != nil {
in, out := &in.Methods, &out.Methods
*out = make([]DeviceMethod, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceSpec.
func (in *DeviceSpec) DeepCopy() *DeviceSpec {
if in == nil {
return nil
}
out := new(DeviceSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DeviceStatus) DeepCopyInto(out *DeviceStatus) {
*out = *in
if in.Twins != nil {
in, out := &in.Twins, &out.Twins
*out = make([]Twin, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceStatus.
func (in *DeviceStatus) DeepCopy() *DeviceStatus {
if in == nil {
return nil
}
out := new(DeviceStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Influxdb2ClientConfig) DeepCopyInto(out *Influxdb2ClientConfig) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Influxdb2ClientConfig.
func (in *Influxdb2ClientConfig) DeepCopy() *Influxdb2ClientConfig {
if in == nil {
return nil
}
out := new(Influxdb2ClientConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Influxdb2DataConfig) DeepCopyInto(out *Influxdb2DataConfig) {
*out = *in
if in.Tag != nil {
in, out := &in.Tag, &out.Tag
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Influxdb2DataConfig.
func (in *Influxdb2DataConfig) DeepCopy() *Influxdb2DataConfig {
if in == nil {
return nil
}
out := new(Influxdb2DataConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ModelProperty) DeepCopyInto(out *ModelProperty) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ModelProperty.
func (in *ModelProperty) DeepCopy() *ModelProperty {
if in == nil {
return nil
}
out := new(ModelProperty)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MySQLClientConfig) DeepCopyInto(out *MySQLClientConfig) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MySQLClientConfig.
func (in *MySQLClientConfig) DeepCopy() *MySQLClientConfig {
if in == nil {
return nil
}
out := new(MySQLClientConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProtocolConfig) DeepCopyInto(out *ProtocolConfig) {
*out = *in
if in.ConfigData != nil {
in, out := &in.ConfigData, &out.ConfigData
*out = (*in).DeepCopy()
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolConfig.
func (in *ProtocolConfig) DeepCopy() *ProtocolConfig {
if in == nil {
return nil
}
out := new(ProtocolConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PushMethod) DeepCopyInto(out *PushMethod) {
*out = *in
if in.HTTP != nil {
in, out := &in.HTTP, &out.HTTP
*out = new(PushMethodHTTP)
**out = **in
}
if in.MQTT != nil {
in, out := &in.MQTT, &out.MQTT
*out = new(PushMethodMQTT)
**out = **in
}
if in.OTEL != nil {
in, out := &in.OTEL, &out.OTEL
*out = new(PushMethodOTEL)
**out = **in
}
if in.DBMethod != nil {
in, out := &in.DBMethod, &out.DBMethod
*out = new(DBMethodConfig)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PushMethod.
func (in *PushMethod) DeepCopy() *PushMethod {
if in == nil {
return nil
}
out := new(PushMethod)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PushMethodHTTP) DeepCopyInto(out *PushMethodHTTP) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PushMethodHTTP.
func (in *PushMethodHTTP) DeepCopy() *PushMethodHTTP {
if in == nil {
return nil
}
out := new(PushMethodHTTP)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PushMethodMQTT) DeepCopyInto(out *PushMethodMQTT) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PushMethodMQTT.
func (in *PushMethodMQTT) DeepCopy() *PushMethodMQTT {
if in == nil {
return nil
}
out := new(PushMethodMQTT)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PushMethodOTEL) DeepCopyInto(out *PushMethodOTEL) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PushMethodOTEL.
func (in *PushMethodOTEL) DeepCopy() *PushMethodOTEL {
if in == nil {
return nil
}
out := new(PushMethodOTEL)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RedisClientConfig) DeepCopyInto(out *RedisClientConfig) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RedisClientConfig.
func (in *RedisClientConfig) DeepCopy() *RedisClientConfig {
if in == nil {
return nil
}
out := new(RedisClientConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TDEngineClientConfig) DeepCopyInto(out *TDEngineClientConfig) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TDEngineClientConfig.
func (in *TDEngineClientConfig) DeepCopy() *TDEngineClientConfig {
if in == nil {
return nil
}
out := new(TDEngineClientConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Twin) DeepCopyInto(out *Twin) {
*out = *in
in.Reported.DeepCopyInto(&out.Reported)
in.ObservedDesired.DeepCopyInto(&out.ObservedDesired)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Twin.
func (in *Twin) DeepCopy() *Twin {
if in == nil {
return nil
}
out := new(Twin)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TwinProperty) DeepCopyInto(out *TwinProperty) {
*out = *in
if in.Metadata != nil {
in, out := &in.Metadata, &out.Metadata
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TwinProperty.
func (in *TwinProperty) DeepCopy() *TwinProperty {
if in == nil {
return nil
}
out := new(TwinProperty)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VisitorConfig) DeepCopyInto(out *VisitorConfig) {
*out = *in
if in.ConfigData != nil {
in, out := &in.ConfigData, &out.ConfigData
*out = (*in).DeepCopy()
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VisitorConfig.
func (in *VisitorConfig) DeepCopy() *VisitorConfig {
if in == nil {
return nil
}
out := new(VisitorConfig)
in.DeepCopyInto(out)
return out
}

92
apis/dmi/services.go Normal file
View File

@ -0,0 +1,92 @@
/*
Copyright 2022 The KubeEdge 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 dmi
import (
dmiapi "github.com/kubeedge/api/apis/dmi/v1beta1"
)
// DeviceManagerService defines the public APIS for remote device management.
// The server is implemented by the module of device manager in edgecore
// and the client is implemented by the device mapper for upstreaming.
// The mapper should register itself to the device manager when it is online
// to get the list of devices. And then the mapper can report the device status to the device manager.
type DeviceManagerService interface {
// MapperRegister registers the information of the mapper to device manager
// when the mapper is online. Device manager returns the list of devices and device models which
// this mapper should manage.
MapperRegister(*dmiapi.MapperRegisterRequest) (*dmiapi.MapperRegisterResponse, error)
// ReportDeviceStatus reports the status of devices to device manager.
// When the mapper collects some properties of a device, it can make them a map of device twins
// and report it to the device manager through the interface of ReportDeviceStatus.
ReportDeviceStatus(*dmiapi.ReportDeviceStatusRequest) (*dmiapi.ReportDeviceStatusResponse, error)
// ReportDeviceStates reports the state of devices to device manager.
ReportDeviceState(*dmiapi.ReportDeviceStatesRequest) (*dmiapi.ReportDeviceStatesResponse, error)
}
// DeviceMapperService defines the public APIS for remote device management.
// The server is implemented by the device mapper
// and the client is implemented by the module of device manager in edgecore for downstreaming.
// The device manager can manage the device life cycle through these interfaces provided by DeviceMapperService.
// When device manager gets a message of device management from cloudcore, it should call the corresponding grpc interface
// to make the mapper maintain the list of device information.
type DeviceMapperService interface {
// RegisterDevice registers a device to the device mapper.
// Device manager registers a device instance with the information of device
// to the mapper through the interface of RegisterDevice.
// When the mapper gets the request of register with device information,
// it should add the device to the device list and connect to the real physical device via the specific protocol.
RegisterDevice(*dmiapi.RegisterDeviceRequest) (*dmiapi.RegisterDeviceResponse, error)
// RemoveDevice unregisters a device to the device mapper.
// Device manager unregisters a device instance with the name of device
// to the mapper through the interface of RemoveDevice.
// When the mapper gets the request of unregister with device name,
// it should remove the device from the device list and disconnect to the real physical device.
RemoveDevice(*dmiapi.RemoveDeviceRequest) (*dmiapi.RemoveDeviceResponse, error)
// UpdateDevice updates a device to the device mapper
// Device manager updates the information of a device used by the mapper
// through the interface of UpdateDevice.
// The information of a device includes the meta data and the status data of a device.
// When the mapper gets the request of updating with the information of a device,
// it should update the device of the device list and connect to the real physical device via the updated information.
UpdateDevice(*dmiapi.UpdateDeviceRequest) (*dmiapi.UpdateDeviceResponse, error)
// GetDevice get the information of a device from the device mapper.
// Device sends the request of querying device information with the device name to the mapper
// through the interface of GetDevice.
// When the mapper gets the request of querying with the device name,
// it should return the device information.
GetDevice(*dmiapi.GetDeviceRequest) (*dmiapi.GetDeviceResponse, error)
// CreateDeviceModel creates a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of CreateDeviceModel.
// When the mapper gets the request of creating with the information of device model,
// it should create a new device model to the list of device models.
CreateDeviceModel(request *dmiapi.CreateDeviceModelRequest) (*dmiapi.CreateDeviceModelResponse, error)
// RemoveDeviceModel remove a device model to the device mapper.
// Device manager sends the name of device model to the mapper
// through the interface of RemoveDeviceModel.
// When the mapper gets the request of removing with the name of device model,
// it should remove the device model to the list of device models.
RemoveDeviceModel(*dmiapi.RemoveDeviceModelRequest) (*dmiapi.RemoveDeviceModelResponse, error)
// UpdateDeviceModel update a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of UpdateDeviceModel.
// When the mapper gets the request of updating with the information of device model,
// it should update the device model to the list of device models.
UpdateDeviceModel(*dmiapi.UpdateDeviceModelRequest) (*dmiapi.UpdateDeviceModelResponse, error)
}

5218
apis/dmi/v1alpha1/api.pb.go Normal file

File diff suppressed because it is too large Load Diff

539
apis/dmi/v1alpha1/api.proto Normal file
View File

@ -0,0 +1,539 @@
/*
Copyright 2022 The KubeEdge 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.
*/
// To regenerate api.pb.go run hack/generate-dmi.sh
syntax = "proto3";
//option go_package = "path;name";
option go_package="./;v1alpha1";
package v1alpha1;
import "google/protobuf/any.proto";
// DeviceManagerService defines the public APIS for remote device management.
// The server is implemented by the module of device manager in edgecore
// and the client is implemented by the device mapper for upstreaming.
// The mapper should register itself to the device manager when it is online
// to get the list of devices. And then the mapper can report the device status to the device manager.
service DeviceManagerService {
// MapperRegister registers the information of the mapper to device manager
// when the mapper is online. Device manager returns the list of devices and device models which
// this mapper should manage.
rpc MapperRegister(MapperRegisterRequest) returns (MapperRegisterResponse) {}
// ReportDeviceStatus reports the status of devices to device manager.
// When the mapper collects some properties of a device, it can make them a map of device twins
// and report it to the device manager through the interface of ReportDeviceStatus.
rpc ReportDeviceStatus(ReportDeviceStatusRequest) returns (ReportDeviceStatusResponse) {}
}
// DeviceMapperService defines the public APIS for remote device management.
// The server is implemented by the device mapper
// and the client is implemented by the module of device manager in edgecore for downstreaming.
// The device manager can manage the device life cycle through these interfaces provided by DeviceMapperService.
// When device manager gets a message of device management from cloudcore, it should call the corresponding grpc interface
// to make the mapper maintain the list of device information.
service DeviceMapperService {
// RegisterDevice registers a device to the device mapper.
// Device manager registers a device instance with the information of device
// to the mapper through the interface of RegisterDevice.
// When the mapper gets the request of register with device information,
// it should add the device to the device list and connect to the real physical device via the specific protocol.
rpc RegisterDevice(RegisterDeviceRequest) returns (RegisterDeviceResponse) {}
// RemoveDevice unregisters a device to the device mapper.
// Device manager unregisters a device instance with the name of device
// to the mapper through the interface of RemoveDevice.
// When the mapper gets the request of unregister with device name,
// it should remove the device from the device list and disconnect to the real physical device.
rpc RemoveDevice(RemoveDeviceRequest) returns (RemoveDeviceResponse) {}
// UpdateDevice updates a device to the device mapper
// Device manager updates the information of a device used by the mapper
// through the interface of UpdateDevice.
// The information of a device includes the meta data and the status data of a device.
// When the mapper gets the request of updating with the information of a device,
// it should update the device of the device list and connect to the real physical device via the updated information.
rpc UpdateDevice(UpdateDeviceRequest) returns (UpdateDeviceResponse) {}
// CreateDeviceModel creates a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of CreateDeviceModel.
// When the mapper gets the request of creating with the information of device model,
// it should create a new device model to the list of device models.
rpc CreateDeviceModel(CreateDeviceModelRequest) returns (CreateDeviceModelResponse) {}
// RemoveDeviceModel remove a device model to the device mapper.
// Device manager sends the name of device model to the mapper
// through the interface of RemoveDeviceModel.
// When the mapper gets the request of removing with the name of device model,
// it should remove the device model to the list of device models.
rpc RemoveDeviceModel(RemoveDeviceModelRequest) returns (RemoveDeviceModelResponse) {}
// UpdateDeviceModel update a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of UpdateDeviceModel.
// When the mapper gets the request of updating with the information of device model,
// it should update the device model to the list of device models.
rpc UpdateDeviceModel(UpdateDeviceModelRequest) returns (UpdateDeviceModelResponse) {}
// UpdateDeviceStatus update a device status to the device mapper
// Device manager sends the new device status to the mapper
// through the interface of UpdateDeviceStatus.
// The device status represents the properties of device twins.
// When the mapper gets the request of updating with the new device status,
// it should update the device status of the device list and the real device status of the physical device via the updated information.
rpc UpdateDeviceStatus(UpdateDeviceStatusRequest) returns (UpdateDeviceStatusResponse) {}
// GetDevice get the information of a device from the device mapper.
// Device sends the request of querying device information with the device name to the mapper
// through the interface of GetDevice.
// When the mapper gets the request of querying with the device name,
// it should return the device information.
rpc GetDevice(GetDeviceRequest) returns (GetDeviceResponse) {}
}
message MapperRegisterRequest {
// The flag to show how device manager returns.
// True means device manager should return the device list in the response.
// False means device manager should just return nothing.
bool withData = 1;
// Mapper information to be registered to the device manager.
MapperInfo mapper = 2;
}
message MapperRegisterResponse {
// List of device models which the mapper maintains.
repeated DeviceModel modelList = 1;
// List of devices which the mapper maintains.
repeated Device deviceList = 2;
}
// DeviceModel specifies the information of a device model.
message DeviceModel {
// Name of a device model.
string name = 1;
// Specification of a device model.
DeviceModelSpec spec = 2;
}
// DeviceModelSpec is the specification of a device model.
message DeviceModelSpec {
// The properties provided by the device of this device model.
repeated DeviceProperty properties = 1;
// The commands executed by the device of this device model.
repeated DeviceCommand commands = 2;
// The protocol name used by the device of this device model.
string protocol = 3;
}
// DeviceProperty is the property of a device.
message DeviceProperty {
// The name of this property.
string name = 1;
// The description of this property.
string description = 2;
// The specific type of this property.
PropertyType type = 3;
}
// PropertyType is the type of a property.
message PropertyType {
// Property of Type Int64.
PropertyTypeInt64 int = 1;
// Property of Type String.
PropertyTypeString string = 2;
// Property of Type Double.
PropertyTypeDouble double = 3;
// Property of Type Float.
PropertyTypeFloat float = 4;
// Property of Type Boolean.
PropertyTypeBoolean boolean = 5;
// Property of Type Bytes.
PropertyTypeBytes bytes = 6;
}
// The Specification of property of Int64.
message PropertyTypeInt64 {
// The access mode of this property, ReadOnly or ReadWrite.
string accessMode = 1;
// The default value of this property.
int64 defaultValue =2;
// The minimum value of this property.
int64 minimum =3;
// The maximum value of this property.
int64 maximum = 4;
// The unit of this property.
string unit = 5;
}
// The Specification of property of String.
message PropertyTypeString {
// The access mode of this property, ReadOnly or ReadWrite.
string accessMode = 1;
// The default value of this property.
string defaultValue = 2;
}
// The Specification of property of Double.
message PropertyTypeDouble {
// The access mode of this property, ReadOnly or ReadWrite.
string accessMode = 1;
// The default value of this property.
double defaultValue = 2;
// The minimum value of this property.
double minimum = 3;
// The maximum value of this property.
double maximum = 4;
// The unit of this property.
string unit = 5;
}
// The Specification of property of Float.
message PropertyTypeFloat {
// The access mode of this property, ReadOnly or ReadWrite.
string accessMode = 1;
// The default value of this property.
float defaultValue = 2;
// The minimum value of this property.
float minimum = 3;
// The maximum value of this property.
float maximum = 4;
// The unit of this property.
string unit = 5;
}
// The Specification of property of Boolean.
message PropertyTypeBoolean {
// The access mode of this property, ReadOnly or ReadWrite.
string accessMode = 1;
// The default value of this property.
bool defaultValue = 2;
}
// The Specification of property of Bytes.
message PropertyTypeBytes {
// The access mode of this property, ReadOnly or ReadWrite.
string accessMode = 1;
}
// DeviceCommond is the description of a command which the device supports.
message DeviceCommand {
// Name of the command.
string name = 1;
// Url of the command to access.
string url = 2;
// Method of the command.
string method = 3;
// Status code list which the command can return.
repeated string status_code = 4;
// Parameter list which the command carries.
repeated string parameters = 5;
// Response examples of the command.
bytes response = 6;
}
// Device is the description of a device instance.
message Device {
// Name of the device.
string name = 1;
// Specification of the device.
DeviceSpec spec = 2;
// Status of the device.
DeviceStatus status = 3;
}
// DeviceSpec is the specification of the device.
message DeviceSpec {
// The device model which the device references.
string deviceModelReference = 1;
// The specific config of the protocol to access to the device.
ProtocolConfig protocol = 2;
// The visitor to collect the properties of the device.
repeated DevicePropertyVisitor propertyVisitors = 3;
}
// ProtocolConfig is the specific config of the protocol to access to the device.
message ProtocolConfig {
// The specific config of the protocol of OpcUA.
ProtocolConfigOpcUA opcua = 1;
// The specific config of the protocol of Modbus.
ProtocolConfigModbus modbus = 2;
// The specific config of the protocol of Bluetooth.
ProtocolConfigBluetooth bluetooth = 3;
// The common config for device.
ProtocolConfigCommon common = 4;
// The specific config of the customized protocol.
ProtocolConfigCustomized customizedProtocol = 5;
}
// ProtocolConfigOpcUA is the config of the protocol of OpcUA.
message ProtocolConfigOpcUA {
// URL of the device.
string url = 1;
// The user name to access to the device.
string userName = 2;
// The file path to store the password to access to the device like /ca/paas.
string password = 3;
// The security policy of the device like Basic256Sha256.
string securityPolicy = 4;
// The security mode of the device like Sign.
string securityMode = 5;
// The file path to store the certificate to access to the device like /ca/clientcert.pem.
string certificate = 6;
// The file path to store the private key to access to the device like /ca/clientkey.pem.
string privateKey = 7;
int64 timeout = 8;
}
// ProtocolConfigModbus is the config of the protocol of Modbus.
message ProtocolConfigModbus {
// The ID of the slave.
int64 slaveID = 1;
}
// The specific config of the protocol of Bluetooth.
message ProtocolConfigBluetooth {
// The mac address of the bluetooth device.
string macAddress = 1;
}
// The common config for device.
message ProtocolConfigCommon {
// ProtocolConfigCOM is the config of com.
ProtocolConfigCOM com = 1;
// ProtocolConfigTCP is the config of tcp.
ProtocolConfigTCP tcp = 2;
// commType is the type of the communication.
string commType = 3;
// reconnTimeout is the time out of reconnection.
int64 reconnTimeout = 4;
// reconnRetryTimes is the retry times of reconnection.
int64 reconnRetryTimes = 5;
// collectTimeout is the time out of collection.
int64 collectTimeout = 6;
// collectRetryTimes is the retry times of collection.
int64 collectRetryTimes = 7;
// collectType is the type of collection.
string collectType = 8;
// CustomizedValue is the customized value for developers.
CustomizedValue customizedValues = 9;
}
// ProtocolConfigCOM is the config of com.
message ProtocolConfigCOM {
// serialPort is the port of serial.
string serialPort = 1;
// baudRate is the rate of baud.
int64 baudRate = 2;
// dataBits is the bits of data.
int64 dataBits= 3;
// parity is the bit of parity.
string parity = 4;
// stopBits is the bit of stop.
int64 stopBits = 5;
}
// ProtocolConfigTCP is the config of tcp.
message ProtocolConfigTCP {
// IP of tcp for the device.
string ip = 1;
// port of tcp for the device.
int64 port = 2;
}
// CustomizedValue is the customized value for developers.
message CustomizedValue {
// data is the customized value and it can be any form.
map<string, google.protobuf.Any> data = 1;
}
// The specific config of the customized protocol.
message ProtocolConfigCustomized {
// the name of the customized protocol.
string protocolName = 1;
// the config data of the customized protocol.
CustomizedValue configData = 2;
}
// The visitor to collect the properties of the device.
message DevicePropertyVisitor {
// the name of the property.
string propertyName = 1;
// the cycle to report data.
int64 reportCycle = 2;
// the cycle to collect data.
int64 collectCycle = 3;
// CustomizedValue is the customized value for developers.
CustomizedValue customizedValues = 4;
// the visitor to collect the properties of the device of OPC UA.
VisitorConfigOPCUA opcua = 5;
// the visitor to collect the properties of the device of Modbus.
VisitorConfigModbus modbus = 6;
// the visitor to collect the properties of the device of Bluetooth.
VisitorConfigBluetooth bluetooth = 7;
// the visitor to collect the properties of the device of customized protocol.
VisitorConfigCustomized customizedProtocol = 8;
}
// the visitor to collect the properties of the device of OPC UA.
message VisitorConfigOPCUA {
// ID of the node.
string nodeID = 1;
// name of browse.
string browseName = 2;
}
// the visitor to collect the properties of the device of Modbus.
message VisitorConfigModbus {
// register of Modbus
string register =1;
// offset of Modbus.
int64 offset = 2;
// limit of Modbus.
int64 limit = 3;
// scale of Modbus.
double scale = 4;
// isSwap of Modbus.
bool isSwap = 5;
// isRegisterSwap of Modbus.
bool isRegisterSwap = 6;
}
// the visitor to collect the properties of the device of Bluetooth.
message VisitorConfigBluetooth {
// characteristicUUID of Bluetooth.
string characteristicUUID = 1;
// dataWrite of Bluetooth.
map<string, bytes> dataWrite = 2;
// BluetoothReadConverter of Bluetooth.
BluetoothReadConverter dataConverter =3;
}
// BluetoothReadConverter of Bluetooth.
message BluetoothReadConverter {
int64 startIndex = 1;
int64 endIndex = 2;
uint64 shiftLeft = 3;
uint64 shiftRight = 4;
repeated BluetoothOperations orderOfOperations =5;
}
// BluetoothOperations of Bluetooth.
message BluetoothOperations {
string operationType = 1;
double operationValue = 2;
}
// the visitor to collect the properties of the device of customized protocol.
message VisitorConfigCustomized {
string protocolName = 1;
CustomizedValue configData =2;
}
// MapperInfo is the information of mapper.
message MapperInfo {
// name of the mapper.
string name = 1;
// version of the mapper.
string version = 2;
// api version of the mapper.
string api_version = 3;
// the protocol of the mapper.
string protocol = 4;
// the address of the mapper. it is a unix domain socket of grpc.
bytes address = 5;
// the state of the mapper.
string state = 6;
}
message ReportDeviceStatusRequest {
string deviceName = 1;
DeviceStatus reportedDevice = 2;
}
// DeviceStatus is the status of the device.
message DeviceStatus {
// the device twins of the device.
repeated Twin twins = 1;
// the state of the device like Online or Offline.
string state = 2;
}
// Twin is the digital model of a device. It contains a series of properties.
message Twin {
// the name of the property.
string propertyName = 1;
// the desired value of the property configured by device manager.
TwinProperty desired = 2;
// the reported value of the property from the real device.
TwinProperty reported = 3;
}
// TwinProperty is the specification of the property.
message TwinProperty {
// the value of the property.
string value = 1;
// the metadata to describe this property.
map<string,string> metadata = 2;
}
message ReportDeviceStatusResponse {}
message RegisterDeviceRequest {
Device device = 1;
}
message RegisterDeviceResponse {
string deviceName = 1;
}
message CreateDeviceModelRequest {
DeviceModel model = 1;
}
message CreateDeviceModelResponse {
string deviceModelName = 1;
}
message RemoveDeviceRequest {
string deviceName =1;
}
message RemoveDeviceResponse {}
message RemoveDeviceModelRequest {
string modelName =1;
}
message RemoveDeviceModelResponse {}
message UpdateDeviceRequest {
Device device = 1;
}
message UpdateDeviceResponse {}
message UpdateDeviceModelRequest {
DeviceModel model = 1;
}
message UpdateDeviceModelResponse {}
message UpdateDeviceStatusRequest {
string deviceName = 1;
DeviceStatus desiredDevice = 2;
}
message UpdateDeviceStatusResponse {}
message GetDeviceRequest {
string deviceName = 1;
}
message GetDeviceResponse {
Device device = 1;
}

3580
apis/dmi/v1beta1/api.pb.go Normal file

File diff suppressed because it is too large Load Diff

465
apis/dmi/v1beta1/api.proto Normal file
View File

@ -0,0 +1,465 @@
/*
Copyright 2023 The KubeEdge 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.
*/
// To regenerate api.pb.go run hack/generate-dmi-proto.sh
syntax = "proto3";
//option go_package = "path;name";
option go_package = "./;v1beta1";
package v1beta1;
import "google/protobuf/any.proto";
// DeviceManagerService defines the public APIS for remote device management.
// The server is implemented by the module of device manager in edgecore
// and the client is implemented by the device mapper for upstreaming.
// The mapper should register itself to the device manager when it is online
// to get the list of devices. And then the mapper can report the device status to the device manager.
service DeviceManagerService {
// MapperRegister registers the information of the mapper to device manager
// when the mapper is online. Device manager returns the list of devices and device models which
// this mapper should manage.
rpc MapperRegister(MapperRegisterRequest) returns (MapperRegisterResponse) {}
// ReportDeviceStatus reports the status of devices to device manager.
// When the mapper collects some properties of a device, it can make them a map of device twins
// and report it to the device manager through the interface of ReportDeviceStatus.
rpc ReportDeviceStatus(ReportDeviceStatusRequest) returns (ReportDeviceStatusResponse) {}
// TODO Rename ReportDeviceStatus to ReportDeviceTwins
// ReportDeviceStates reports the state of devices to device manager.
rpc ReportDeviceStates(ReportDeviceStatesRequest) returns (ReportDeviceStatesResponse) {}
}
// DeviceMapperService defines the public APIS for remote device management.
// The server is implemented by the device mapper
// and the client is implemented by the module of device manager in edgecore for downstreaming.
// The device manager can manage the device life cycle through these interfaces provided by DeviceMapperService.
// When device manager gets a message of device management from cloudcore, it should call the corresponding grpc interface
// to make the mapper maintain the list of device information.
service DeviceMapperService {
// RegisterDevice registers a device to the device mapper.
// Device manager registers a device instance with the information of device
// to the mapper through the interface of RegisterDevice.
// When the mapper gets the request of register with device information,
// it should add the device to the device list and connect to the real physical device via the specific protocol.
rpc RegisterDevice(RegisterDeviceRequest) returns (RegisterDeviceResponse) {}
// RemoveDevice unregisters a device to the device mapper.
// Device manager unregisters a device instance with the name of device
// to the mapper through the interface of RemoveDevice.
// When the mapper gets the request of unregister with device name,
// it should remove the device from the device list and disconnect to the real physical device.
rpc RemoveDevice(RemoveDeviceRequest) returns (RemoveDeviceResponse) {}
// UpdateDevice updates a device to the device mapper
// Device manager updates the information of a device used by the mapper
// through the interface of UpdateDevice.
// The information of a device includes the meta data and the status data of a device.
// When the mapper gets the request of updating with the information of a device,
// it should update the device of the device list and connect to the real physical device via the updated information.
rpc UpdateDevice(UpdateDeviceRequest) returns (UpdateDeviceResponse) {}
// CreateDeviceModel creates a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of CreateDeviceModel.
// When the mapper gets the request of creating with the information of device model,
// it should create a new device model to the list of device models.
rpc CreateDeviceModel(CreateDeviceModelRequest) returns (CreateDeviceModelResponse) {}
// RemoveDeviceModel remove a device model to the device mapper.
// Device manager sends the name of device model to the mapper
// through the interface of RemoveDeviceModel.
// When the mapper gets the request of removing with the name of device model,
// it should remove the device model to the list of device models.
rpc RemoveDeviceModel(RemoveDeviceModelRequest) returns (RemoveDeviceModelResponse) {}
// UpdateDeviceModel update a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of UpdateDeviceModel.
// When the mapper gets the request of updating with the information of device model,
// it should update the device model to the list of device models.
rpc UpdateDeviceModel(UpdateDeviceModelRequest) returns (UpdateDeviceModelResponse) {}
// GetDevice get the information of a device from the device mapper.
// Device sends the request of querying device information with the device name to the mapper
// through the interface of GetDevice.
// When the mapper gets the request of querying with the device name,
// it should return the device information.
rpc GetDevice(GetDeviceRequest) returns (GetDeviceResponse) {}
}
message MapperRegisterRequest {
// The flag to show how device manager returns.
// True means device manager should return the device list in the response.
// False means device manager should just return nothing.
bool withData = 1;
// Mapper information to be registered to the device manager.
MapperInfo mapper = 2;
}
message MapperRegisterResponse {
// List of device models which the mapper maintains.
repeated DeviceModel modelList = 1;
// List of devices which the mapper maintains.
repeated Device deviceList = 2;
}
// DeviceModel specifies the information of a device model.
message DeviceModel {
// Name of a device model.
string name = 1;
// Specification of a device model.
DeviceModelSpec spec = 2;
// Namespace of the device model.
string namespace = 3;
}
// DeviceModelSpec is the specification of a device model.
message DeviceModelSpec {
// The properties provided by the device of this device model.
repeated ModelProperty properties = 1;
// The commands executed by the device of this device model.
repeated DeviceCommand commands = 2;
}
// ModelProperty is the property of a device.
message ModelProperty {
// The name of this property.
string name = 1;
// The description of this property.
string description = 2;
// The specific type of this property.
string type = 3;
// The access mode of this property, ReadOnly or ReadWrite.
string accessMode = 4;
// The minimum value of this property.
string minimum = 5;
// The maximum value of this property.
string maximum = 6;
// The unit of this property.
string unit = 7;
}
// DeviceCommond is the description of a command which the device supports.
message DeviceCommand {
// Name of the command.
string name = 1;
// Url of the command to access.
string url = 2;
// Method of the command.
string method = 3;
// Status code list which the command can return.
repeated string status_code = 4;
// Parameter list which the command carries.
repeated string parameters = 5;
// Response examples of the command.
bytes response = 6;
}
// Device is the description of a device instance.
message Device {
// Name of the device.
string name = 1;
// Specification of the device.
DeviceSpec spec = 2;
// Status of the device.
DeviceStatus status = 3;
// Namespace of the device.
string namespace = 4;
}
// DeviceSpec is the specification of the device.
message DeviceSpec {
// The device model which the device references.
string deviceModelReference = 1;
// The specific config of the protocol to access to the device.
ProtocolConfig protocol = 2;
// List of properties which describe the device properties.
repeated DeviceProperty properties = 3;
// List of methods which describe the device methods.
repeated DeviceMethod methods = 4;
}
// DeviceMethod describes the specifics all the methods of the device.
message DeviceMethod {
// The device method name to be accessed. It must be unique.
string name = 1;
// the description of the device method.
string description = 2;
// the list of device properties that device methods can control.
repeated string propertyNames = 3;
}
// DeviceProperty describes the specifics all the properties of the device.
message DeviceProperty {
// The device property name to be accessed. It must be unique.
string name = 1;
// the desired value of the property configured by device manager.
TwinProperty desired = 2;
// Visitors are intended to be consumed by device mappers which connect to devices
// and collect data / perform actions on the device.
VisitorConfig visitors = 3;
// Define how frequent mapper will report the value.
int64 reportCycle = 4;
// Define how frequent mapper will collect from device.
int64 collectCycle = 5;
// whether be reported to the cloud
bool reportToCloud = 6;
// PushMethod represents the protocol used to push data,
PushMethod pushMethod = 7;
}
// ProtocolConfig is the specific config of the protocol to access to the device.
message ProtocolConfig {
// the name of the customized protocol.
string protocolName = 1;
// the config data of the customized protocol.
CustomizedValue configData = 2;
}
// the visitor to collect the properties of the device of customized protocol.
message VisitorConfig {
// the name of the customized protocol.
string protocolName = 1;
// the config data of the customized protocol.
CustomizedValue configData = 2;
}
// CustomizedValue is the customized value for developers.
message CustomizedValue {
// data is the customized value and it can be any form.
map<string, google.protobuf.Any> data = 1;
}
message PushMethod {
PushMethodHTTP http = 1;
PushMethodMQTT mqtt = 2;
PushMethodOTEL otel = 4;
DBMethod dbMethod = 3;
}
message PushMethodHTTP {
string hostname = 1;
int64 port = 2;
string requestpath = 3;
int64 timeout = 4;
}
message PushMethodMQTT {
// broker address, like mqtt://127.0.0.1:1883
string address = 1;
// publish topic for mqtt
string topic = 2;
// qos of mqtt publish param
int32 qos = 3;
// Is the message retained
bool retained = 4;
}
message PushMethodOTEL {
// the target endpoint URL the Exporter will connect to, like https://localhost:4318/v1/metrics
string endpointURL = 1;
}
message DBMethod{
// the config of database .
DBMethodInfluxdb2 influxdb2 = 1;
DBMethodRedis redis = 2;
DBMethodTDEngine tdengine = 3;
DBMethodMySQL mysql = 4;
}
message DBMethodInfluxdb2{
// the config of influx database.
Influxdb2ClientConfig influxdb2ClientConfig = 1;
Influxdb2DataConfig influxdb2DataConfig = 2;
}
message Influxdb2DataConfig{
// data config when push data to influx
string measurement = 1;
map<string, string> tag = 2;
string fieldKey = 3;
}
message Influxdb2ClientConfig{
// influx database url
string url = 1;
// usr org in influx database
string org = 2;
// usr bucket in influx database
string bucket = 3;
}
message DBMethodRedis{
// data config when push data to redis
RedisClientConfig redisClientConfig = 1;
}
message RedisClientConfig{
// redis address
string addr = 1;
// number of redis db
int32 db = 2;
// number of redis poolsize
int32 poolsize = 3;
// number of redis minidleconns
int32 minIdleConns =4;
}
message DBMethodTDEngine{
// data config when push data to tdengine
TDEngineClientConfig tdEngineClientConfig = 1;
}
message TDEngineClientConfig{
// tdengine address,like 127.0.0.1:6041
string addr = 1;
// tdengine database name
string dbname = 2;
}
message DBMethodMySQL{
MySQLClientConfig mysqlClientConfig = 1;
}
message MySQLClientConfig{
//mysql address,like localhost:3306
string addr = 1;
//database name
string database = 2;
//user name
string userName = 3;
}
message DBMethodOTEL{
OTELExporterConfig otelExporterConfig = 1;
}
message OTELExporterConfig{
//the target endpoint URL the Exporter will connect to, like https://localhost:4318/v1/metrics
string endpointURL = 1;
}
// MapperInfo is the information of mapper.
message MapperInfo {
// name of the mapper.
string name = 1;
// version of the mapper.
string version = 2;
// api version of the mapper.
string api_version = 3;
// the protocol of the mapper.
string protocol = 4;
// the address of the mapper. it is a unix domain socket of grpc.
bytes address = 5;
// the state of the mapper.
string state = 6;
}
message ReportDeviceStatusRequest {
string deviceName = 1;
DeviceStatus reportedDevice = 2;
string deviceNamespace = 3;
}
message ReportDeviceStatesRequest {
string deviceName = 1;
string deviceNamespace = 2;
string state = 3;
}
// DeviceStatus is the status of the device.
message DeviceStatus {
// the device twins of the device.
repeated Twin twins = 1;
// whether be reported to the cloud
bool reportToCloud = 2;
// Define how frequent mapper will report the value.
int64 reportCycle = 3;
}
// Twin is the digital model of a device. It contains a series of properties.
message Twin {
// the name of the property.
string propertyName = 1;
// the observedDesired value of the property configured by mapper.
TwinProperty observedDesired = 2;
// the reported value of the property from the real device.
TwinProperty reported = 3;
}
// TwinProperty is the specification of the property.
message TwinProperty {
// the value of the property.
string value = 1;
// the metadata to describe this property.
map<string, string> metadata = 2;
}
message ReportDeviceStatusResponse {}
message ReportDeviceStatesResponse {}
message RegisterDeviceRequest {
Device device = 1;
}
message RegisterDeviceResponse {
string deviceName = 1;
string deviceNamespace = 2;
}
message CreateDeviceModelRequest {
DeviceModel model = 1;
}
message CreateDeviceModelResponse {
string deviceModelName = 1;
string deviceModelNamespace = 2;
}
message RemoveDeviceRequest {
string deviceName = 1;
string deviceNamespace = 2;
}
message RemoveDeviceResponse {}
message RemoveDeviceModelRequest {
string modelName = 1;
string modelNamespace = 2;
}
message RemoveDeviceModelResponse {}
message UpdateDeviceRequest {
Device device = 1;
}
message UpdateDeviceResponse {}
message UpdateDeviceModelRequest {
DeviceModel model = 1;
}
message UpdateDeviceModelResponse {}
message GetDeviceRequest {
string deviceName = 1;
string deviceNamespace = 2;
}
message GetDeviceResponse {
Device device = 1;
}

View File

@ -0,0 +1,636 @@
//
//Copyright 2023 The KubeEdge 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.
// To regenerate api.pb.go run hack/generate-dmi-proto.sh
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.4.0
// - protoc v3.15.8
// source: api.proto
package v1beta1
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.62.0 or later.
const _ = grpc.SupportPackageIsVersion8
const (
DeviceManagerService_MapperRegister_FullMethodName = "/v1beta1.DeviceManagerService/MapperRegister"
DeviceManagerService_ReportDeviceStatus_FullMethodName = "/v1beta1.DeviceManagerService/ReportDeviceStatus"
DeviceManagerService_ReportDeviceStates_FullMethodName = "/v1beta1.DeviceManagerService/ReportDeviceStates"
)
// DeviceManagerServiceClient is the client API for DeviceManagerService 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.
//
// DeviceManagerService defines the public APIS for remote device management.
// The server is implemented by the module of device manager in edgecore
// and the client is implemented by the device mapper for upstreaming.
// The mapper should register itself to the device manager when it is online
// to get the list of devices. And then the mapper can report the device status to the device manager.
type DeviceManagerServiceClient interface {
// MapperRegister registers the information of the mapper to device manager
// when the mapper is online. Device manager returns the list of devices and device models which
// this mapper should manage.
MapperRegister(ctx context.Context, in *MapperRegisterRequest, opts ...grpc.CallOption) (*MapperRegisterResponse, error)
// ReportDeviceStatus reports the status of devices to device manager.
// When the mapper collects some properties of a device, it can make them a map of device twins
// and report it to the device manager through the interface of ReportDeviceStatus.
ReportDeviceStatus(ctx context.Context, in *ReportDeviceStatusRequest, opts ...grpc.CallOption) (*ReportDeviceStatusResponse, error)
// TODO Rename ReportDeviceStatus to ReportDeviceTwins
// ReportDeviceStates reports the state of devices to device manager.
ReportDeviceStates(ctx context.Context, in *ReportDeviceStatesRequest, opts ...grpc.CallOption) (*ReportDeviceStatesResponse, error)
}
type deviceManagerServiceClient struct {
cc grpc.ClientConnInterface
}
func NewDeviceManagerServiceClient(cc grpc.ClientConnInterface) DeviceManagerServiceClient {
return &deviceManagerServiceClient{cc}
}
func (c *deviceManagerServiceClient) MapperRegister(ctx context.Context, in *MapperRegisterRequest, opts ...grpc.CallOption) (*MapperRegisterResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(MapperRegisterResponse)
err := c.cc.Invoke(ctx, DeviceManagerService_MapperRegister_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceManagerServiceClient) ReportDeviceStatus(ctx context.Context, in *ReportDeviceStatusRequest, opts ...grpc.CallOption) (*ReportDeviceStatusResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ReportDeviceStatusResponse)
err := c.cc.Invoke(ctx, DeviceManagerService_ReportDeviceStatus_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceManagerServiceClient) ReportDeviceStates(ctx context.Context, in *ReportDeviceStatesRequest, opts ...grpc.CallOption) (*ReportDeviceStatesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ReportDeviceStatesResponse)
err := c.cc.Invoke(ctx, DeviceManagerService_ReportDeviceStates_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// DeviceManagerServiceServer is the server API for DeviceManagerService service.
// All implementations must embed UnimplementedDeviceManagerServiceServer
// for forward compatibility
//
// DeviceManagerService defines the public APIS for remote device management.
// The server is implemented by the module of device manager in edgecore
// and the client is implemented by the device mapper for upstreaming.
// The mapper should register itself to the device manager when it is online
// to get the list of devices. And then the mapper can report the device status to the device manager.
type DeviceManagerServiceServer interface {
// MapperRegister registers the information of the mapper to device manager
// when the mapper is online. Device manager returns the list of devices and device models which
// this mapper should manage.
MapperRegister(context.Context, *MapperRegisterRequest) (*MapperRegisterResponse, error)
// ReportDeviceStatus reports the status of devices to device manager.
// When the mapper collects some properties of a device, it can make them a map of device twins
// and report it to the device manager through the interface of ReportDeviceStatus.
ReportDeviceStatus(context.Context, *ReportDeviceStatusRequest) (*ReportDeviceStatusResponse, error)
// TODO Rename ReportDeviceStatus to ReportDeviceTwins
// ReportDeviceStates reports the state of devices to device manager.
ReportDeviceStates(context.Context, *ReportDeviceStatesRequest) (*ReportDeviceStatesResponse, error)
mustEmbedUnimplementedDeviceManagerServiceServer()
}
// UnimplementedDeviceManagerServiceServer must be embedded to have forward compatible implementations.
type UnimplementedDeviceManagerServiceServer struct {
}
func (UnimplementedDeviceManagerServiceServer) MapperRegister(context.Context, *MapperRegisterRequest) (*MapperRegisterResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method MapperRegister not implemented")
}
func (UnimplementedDeviceManagerServiceServer) ReportDeviceStatus(context.Context, *ReportDeviceStatusRequest) (*ReportDeviceStatusResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ReportDeviceStatus not implemented")
}
func (UnimplementedDeviceManagerServiceServer) ReportDeviceStates(context.Context, *ReportDeviceStatesRequest) (*ReportDeviceStatesResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ReportDeviceStates not implemented")
}
func (UnimplementedDeviceManagerServiceServer) mustEmbedUnimplementedDeviceManagerServiceServer() {}
// UnsafeDeviceManagerServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to DeviceManagerServiceServer will
// result in compilation errors.
type UnsafeDeviceManagerServiceServer interface {
mustEmbedUnimplementedDeviceManagerServiceServer()
}
func RegisterDeviceManagerServiceServer(s grpc.ServiceRegistrar, srv DeviceManagerServiceServer) {
s.RegisterService(&DeviceManagerService_ServiceDesc, srv)
}
func _DeviceManagerService_MapperRegister_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MapperRegisterRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceManagerServiceServer).MapperRegister(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceManagerService_MapperRegister_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceManagerServiceServer).MapperRegister(ctx, req.(*MapperRegisterRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceManagerService_ReportDeviceStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ReportDeviceStatusRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceManagerServiceServer).ReportDeviceStatus(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceManagerService_ReportDeviceStatus_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceManagerServiceServer).ReportDeviceStatus(ctx, req.(*ReportDeviceStatusRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceManagerService_ReportDeviceStates_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ReportDeviceStatesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceManagerServiceServer).ReportDeviceStates(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceManagerService_ReportDeviceStates_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceManagerServiceServer).ReportDeviceStates(ctx, req.(*ReportDeviceStatesRequest))
}
return interceptor(ctx, in, info, handler)
}
// DeviceManagerService_ServiceDesc is the grpc.ServiceDesc for DeviceManagerService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var DeviceManagerService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "v1beta1.DeviceManagerService",
HandlerType: (*DeviceManagerServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "MapperRegister",
Handler: _DeviceManagerService_MapperRegister_Handler,
},
{
MethodName: "ReportDeviceStatus",
Handler: _DeviceManagerService_ReportDeviceStatus_Handler,
},
{
MethodName: "ReportDeviceStates",
Handler: _DeviceManagerService_ReportDeviceStates_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "api.proto",
}
const (
DeviceMapperService_RegisterDevice_FullMethodName = "/v1beta1.DeviceMapperService/RegisterDevice"
DeviceMapperService_RemoveDevice_FullMethodName = "/v1beta1.DeviceMapperService/RemoveDevice"
DeviceMapperService_UpdateDevice_FullMethodName = "/v1beta1.DeviceMapperService/UpdateDevice"
DeviceMapperService_CreateDeviceModel_FullMethodName = "/v1beta1.DeviceMapperService/CreateDeviceModel"
DeviceMapperService_RemoveDeviceModel_FullMethodName = "/v1beta1.DeviceMapperService/RemoveDeviceModel"
DeviceMapperService_UpdateDeviceModel_FullMethodName = "/v1beta1.DeviceMapperService/UpdateDeviceModel"
DeviceMapperService_GetDevice_FullMethodName = "/v1beta1.DeviceMapperService/GetDevice"
)
// DeviceMapperServiceClient is the client API for DeviceMapperService 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.
//
// DeviceMapperService defines the public APIS for remote device management.
// The server is implemented by the device mapper
// and the client is implemented by the module of device manager in edgecore for downstreaming.
// The device manager can manage the device life cycle through these interfaces provided by DeviceMapperService.
// When device manager gets a message of device management from cloudcore, it should call the corresponding grpc interface
// to make the mapper maintain the list of device information.
type DeviceMapperServiceClient interface {
// RegisterDevice registers a device to the device mapper.
// Device manager registers a device instance with the information of device
// to the mapper through the interface of RegisterDevice.
// When the mapper gets the request of register with device information,
// it should add the device to the device list and connect to the real physical device via the specific protocol.
RegisterDevice(ctx context.Context, in *RegisterDeviceRequest, opts ...grpc.CallOption) (*RegisterDeviceResponse, error)
// RemoveDevice unregisters a device to the device mapper.
// Device manager unregisters a device instance with the name of device
// to the mapper through the interface of RemoveDevice.
// When the mapper gets the request of unregister with device name,
// it should remove the device from the device list and disconnect to the real physical device.
RemoveDevice(ctx context.Context, in *RemoveDeviceRequest, opts ...grpc.CallOption) (*RemoveDeviceResponse, error)
// UpdateDevice updates a device to the device mapper
// Device manager updates the information of a device used by the mapper
// through the interface of UpdateDevice.
// The information of a device includes the meta data and the status data of a device.
// When the mapper gets the request of updating with the information of a device,
// it should update the device of the device list and connect to the real physical device via the updated information.
UpdateDevice(ctx context.Context, in *UpdateDeviceRequest, opts ...grpc.CallOption) (*UpdateDeviceResponse, error)
// CreateDeviceModel creates a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of CreateDeviceModel.
// When the mapper gets the request of creating with the information of device model,
// it should create a new device model to the list of device models.
CreateDeviceModel(ctx context.Context, in *CreateDeviceModelRequest, opts ...grpc.CallOption) (*CreateDeviceModelResponse, error)
// RemoveDeviceModel remove a device model to the device mapper.
// Device manager sends the name of device model to the mapper
// through the interface of RemoveDeviceModel.
// When the mapper gets the request of removing with the name of device model,
// it should remove the device model to the list of device models.
RemoveDeviceModel(ctx context.Context, in *RemoveDeviceModelRequest, opts ...grpc.CallOption) (*RemoveDeviceModelResponse, error)
// UpdateDeviceModel update a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of UpdateDeviceModel.
// When the mapper gets the request of updating with the information of device model,
// it should update the device model to the list of device models.
UpdateDeviceModel(ctx context.Context, in *UpdateDeviceModelRequest, opts ...grpc.CallOption) (*UpdateDeviceModelResponse, error)
// GetDevice get the information of a device from the device mapper.
// Device sends the request of querying device information with the device name to the mapper
// through the interface of GetDevice.
// When the mapper gets the request of querying with the device name,
// it should return the device information.
GetDevice(ctx context.Context, in *GetDeviceRequest, opts ...grpc.CallOption) (*GetDeviceResponse, error)
}
type deviceMapperServiceClient struct {
cc grpc.ClientConnInterface
}
func NewDeviceMapperServiceClient(cc grpc.ClientConnInterface) DeviceMapperServiceClient {
return &deviceMapperServiceClient{cc}
}
func (c *deviceMapperServiceClient) RegisterDevice(ctx context.Context, in *RegisterDeviceRequest, opts ...grpc.CallOption) (*RegisterDeviceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RegisterDeviceResponse)
err := c.cc.Invoke(ctx, DeviceMapperService_RegisterDevice_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceMapperServiceClient) RemoveDevice(ctx context.Context, in *RemoveDeviceRequest, opts ...grpc.CallOption) (*RemoveDeviceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RemoveDeviceResponse)
err := c.cc.Invoke(ctx, DeviceMapperService_RemoveDevice_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceMapperServiceClient) UpdateDevice(ctx context.Context, in *UpdateDeviceRequest, opts ...grpc.CallOption) (*UpdateDeviceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateDeviceResponse)
err := c.cc.Invoke(ctx, DeviceMapperService_UpdateDevice_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceMapperServiceClient) CreateDeviceModel(ctx context.Context, in *CreateDeviceModelRequest, opts ...grpc.CallOption) (*CreateDeviceModelResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CreateDeviceModelResponse)
err := c.cc.Invoke(ctx, DeviceMapperService_CreateDeviceModel_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceMapperServiceClient) RemoveDeviceModel(ctx context.Context, in *RemoveDeviceModelRequest, opts ...grpc.CallOption) (*RemoveDeviceModelResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RemoveDeviceModelResponse)
err := c.cc.Invoke(ctx, DeviceMapperService_RemoveDeviceModel_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceMapperServiceClient) UpdateDeviceModel(ctx context.Context, in *UpdateDeviceModelRequest, opts ...grpc.CallOption) (*UpdateDeviceModelResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateDeviceModelResponse)
err := c.cc.Invoke(ctx, DeviceMapperService_UpdateDeviceModel_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *deviceMapperServiceClient) GetDevice(ctx context.Context, in *GetDeviceRequest, opts ...grpc.CallOption) (*GetDeviceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetDeviceResponse)
err := c.cc.Invoke(ctx, DeviceMapperService_GetDevice_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// DeviceMapperServiceServer is the server API for DeviceMapperService service.
// All implementations must embed UnimplementedDeviceMapperServiceServer
// for forward compatibility
//
// DeviceMapperService defines the public APIS for remote device management.
// The server is implemented by the device mapper
// and the client is implemented by the module of device manager in edgecore for downstreaming.
// The device manager can manage the device life cycle through these interfaces provided by DeviceMapperService.
// When device manager gets a message of device management from cloudcore, it should call the corresponding grpc interface
// to make the mapper maintain the list of device information.
type DeviceMapperServiceServer interface {
// RegisterDevice registers a device to the device mapper.
// Device manager registers a device instance with the information of device
// to the mapper through the interface of RegisterDevice.
// When the mapper gets the request of register with device information,
// it should add the device to the device list and connect to the real physical device via the specific protocol.
RegisterDevice(context.Context, *RegisterDeviceRequest) (*RegisterDeviceResponse, error)
// RemoveDevice unregisters a device to the device mapper.
// Device manager unregisters a device instance with the name of device
// to the mapper through the interface of RemoveDevice.
// When the mapper gets the request of unregister with device name,
// it should remove the device from the device list and disconnect to the real physical device.
RemoveDevice(context.Context, *RemoveDeviceRequest) (*RemoveDeviceResponse, error)
// UpdateDevice updates a device to the device mapper
// Device manager updates the information of a device used by the mapper
// through the interface of UpdateDevice.
// The information of a device includes the meta data and the status data of a device.
// When the mapper gets the request of updating with the information of a device,
// it should update the device of the device list and connect to the real physical device via the updated information.
UpdateDevice(context.Context, *UpdateDeviceRequest) (*UpdateDeviceResponse, error)
// CreateDeviceModel creates a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of CreateDeviceModel.
// When the mapper gets the request of creating with the information of device model,
// it should create a new device model to the list of device models.
CreateDeviceModel(context.Context, *CreateDeviceModelRequest) (*CreateDeviceModelResponse, error)
// RemoveDeviceModel remove a device model to the device mapper.
// Device manager sends the name of device model to the mapper
// through the interface of RemoveDeviceModel.
// When the mapper gets the request of removing with the name of device model,
// it should remove the device model to the list of device models.
RemoveDeviceModel(context.Context, *RemoveDeviceModelRequest) (*RemoveDeviceModelResponse, error)
// UpdateDeviceModel update a device model to the device mapper.
// Device manager sends the information of device model to the mapper
// through the interface of UpdateDeviceModel.
// When the mapper gets the request of updating with the information of device model,
// it should update the device model to the list of device models.
UpdateDeviceModel(context.Context, *UpdateDeviceModelRequest) (*UpdateDeviceModelResponse, error)
// GetDevice get the information of a device from the device mapper.
// Device sends the request of querying device information with the device name to the mapper
// through the interface of GetDevice.
// When the mapper gets the request of querying with the device name,
// it should return the device information.
GetDevice(context.Context, *GetDeviceRequest) (*GetDeviceResponse, error)
mustEmbedUnimplementedDeviceMapperServiceServer()
}
// UnimplementedDeviceMapperServiceServer must be embedded to have forward compatible implementations.
type UnimplementedDeviceMapperServiceServer struct {
}
func (UnimplementedDeviceMapperServiceServer) RegisterDevice(context.Context, *RegisterDeviceRequest) (*RegisterDeviceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegisterDevice not implemented")
}
func (UnimplementedDeviceMapperServiceServer) RemoveDevice(context.Context, *RemoveDeviceRequest) (*RemoveDeviceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RemoveDevice not implemented")
}
func (UnimplementedDeviceMapperServiceServer) UpdateDevice(context.Context, *UpdateDeviceRequest) (*UpdateDeviceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UpdateDevice not implemented")
}
func (UnimplementedDeviceMapperServiceServer) CreateDeviceModel(context.Context, *CreateDeviceModelRequest) (*CreateDeviceModelResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreateDeviceModel not implemented")
}
func (UnimplementedDeviceMapperServiceServer) RemoveDeviceModel(context.Context, *RemoveDeviceModelRequest) (*RemoveDeviceModelResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RemoveDeviceModel not implemented")
}
func (UnimplementedDeviceMapperServiceServer) UpdateDeviceModel(context.Context, *UpdateDeviceModelRequest) (*UpdateDeviceModelResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UpdateDeviceModel not implemented")
}
func (UnimplementedDeviceMapperServiceServer) GetDevice(context.Context, *GetDeviceRequest) (*GetDeviceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetDevice not implemented")
}
func (UnimplementedDeviceMapperServiceServer) mustEmbedUnimplementedDeviceMapperServiceServer() {}
// UnsafeDeviceMapperServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to DeviceMapperServiceServer will
// result in compilation errors.
type UnsafeDeviceMapperServiceServer interface {
mustEmbedUnimplementedDeviceMapperServiceServer()
}
func RegisterDeviceMapperServiceServer(s grpc.ServiceRegistrar, srv DeviceMapperServiceServer) {
s.RegisterService(&DeviceMapperService_ServiceDesc, srv)
}
func _DeviceMapperService_RegisterDevice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RegisterDeviceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceMapperServiceServer).RegisterDevice(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceMapperService_RegisterDevice_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceMapperServiceServer).RegisterDevice(ctx, req.(*RegisterDeviceRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceMapperService_RemoveDevice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RemoveDeviceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceMapperServiceServer).RemoveDevice(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceMapperService_RemoveDevice_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceMapperServiceServer).RemoveDevice(ctx, req.(*RemoveDeviceRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceMapperService_UpdateDevice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateDeviceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceMapperServiceServer).UpdateDevice(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceMapperService_UpdateDevice_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceMapperServiceServer).UpdateDevice(ctx, req.(*UpdateDeviceRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceMapperService_CreateDeviceModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateDeviceModelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceMapperServiceServer).CreateDeviceModel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceMapperService_CreateDeviceModel_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceMapperServiceServer).CreateDeviceModel(ctx, req.(*CreateDeviceModelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceMapperService_RemoveDeviceModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RemoveDeviceModelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceMapperServiceServer).RemoveDeviceModel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceMapperService_RemoveDeviceModel_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceMapperServiceServer).RemoveDeviceModel(ctx, req.(*RemoveDeviceModelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceMapperService_UpdateDeviceModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateDeviceModelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceMapperServiceServer).UpdateDeviceModel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceMapperService_UpdateDeviceModel_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceMapperServiceServer).UpdateDeviceModel(ctx, req.(*UpdateDeviceModelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _DeviceMapperService_GetDevice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetDeviceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DeviceMapperServiceServer).GetDevice(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: DeviceMapperService_GetDevice_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(DeviceMapperServiceServer).GetDevice(ctx, req.(*GetDeviceRequest))
}
return interceptor(ctx, in, info, handler)
}
// DeviceMapperService_ServiceDesc is the grpc.ServiceDesc for DeviceMapperService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var DeviceMapperService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "v1beta1.DeviceMapperService",
HandlerType: (*DeviceMapperServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RegisterDevice",
Handler: _DeviceMapperService_RegisterDevice_Handler,
},
{
MethodName: "RemoveDevice",
Handler: _DeviceMapperService_RemoveDevice_Handler,
},
{
MethodName: "UpdateDevice",
Handler: _DeviceMapperService_UpdateDevice_Handler,
},
{
MethodName: "CreateDeviceModel",
Handler: _DeviceMapperService_CreateDeviceModel_Handler,
},
{
MethodName: "RemoveDeviceModel",
Handler: _DeviceMapperService_RemoveDeviceModel_Handler,
},
{
MethodName: "UpdateDeviceModel",
Handler: _DeviceMapperService_UpdateDeviceModel_Handler,
},
{
MethodName: "GetDevice",
Handler: _DeviceMapperService_GetDevice_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "api.proto",
}

View File

@ -0,0 +1,31 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1
const (
BackingUpState State = "BackingUp"
)
var BackupRule = map[string]State{
"/Init/Success": TaskChecking,
"Checking/Check/Success": BackingUpState,
"Checking/Check/Failure": TaskFailed,
"BackingUp/Backup/Success": TaskSuccessful,
"BackingUp/Backup/Failure": TaskFailed,
}

46
apis/fsm/v1alpha1/fsm.go Normal file
View File

@ -0,0 +1,46 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1
type State string
type Action string
const (
NodeAvailable State = "Available"
NodeUpgrading State = "Upgrading"
NodeRollingBack State = "RollingBack"
NodeConfigUpdating State = "ConfigUpdating"
)
const (
TaskInit State = "Init"
TaskChecking State = "Checking"
TaskSuccessful State = "Successful"
TaskFailed State = "Failed"
TaskPause State = "Pause"
)
const (
ActionSuccess Action = "Success"
ActionFailure Action = "Failure"
ActionConfirmation Action = "Confirmation"
)
const (
EventTimeOut = "TimeOut"
)

View File

@ -0,0 +1,42 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1
const (
PullingState State = "Pulling"
)
// CurrentState/Event/Action: NextState
var PrePullRule = map[string]State{
"Init/Init/Success": TaskChecking,
"Init/Init/Failure": TaskFailed,
"Init/TimeOut/Failure": TaskFailed,
"Checking/Check/Success": PullingState,
"Checking/Check/Failure": TaskFailed,
"Checking/TimeOut/Failure": TaskFailed,
"Pulling/Pull/Success": TaskSuccessful,
"Pulling/Pull/Failure": TaskFailed,
"Pulling/TimeOut/Failure": TaskFailed,
}
var PrePullStageSequence = map[State]State{
"": TaskChecking,
TaskInit: TaskChecking,
TaskChecking: PullingState,
}

View File

@ -0,0 +1,31 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1
const (
RollingBackState State = "RollingBack"
)
var RollbackRule = map[string]State{
"/Init/Success": TaskChecking,
"Checking/Check/Success": RollingBackState,
"Checking/Check/Failure": TaskFailed,
"RollingBack/Rollback/Failure": TaskFailed,
"RollingBack/Rollback/Success": TaskFailed,
}

View File

@ -0,0 +1,61 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1
const (
UpgradingState State = "Upgrading"
)
// CurrentState/Event/Action: NextState
var UpgradeRule = map[string]State{
"Init/Init/Success": TaskChecking,
"Init/Init/Failure": TaskFailed,
"Init/TimeOut/Failure": TaskFailed,
"Init/Upgrade/Success": TaskSuccessful,
"Checking/Check/Success": BackingUpState,
"Checking/Check/Failure": TaskFailed,
"Checking/TimeOut/Failure": TaskFailed,
"BackingUp/Backup/Success": UpgradingState,
"BackingUp/Backup/Failure": TaskFailed,
"BackingUp/TimeOut/Failure": TaskFailed,
"Upgrading/Upgrade/Success": TaskSuccessful,
"Upgrading/Upgrade/Failure": TaskFailed,
"Upgrading/TimeOut/Failure": TaskFailed,
// TODO provide options for task failure, such as successful node upgrade rollback.
"RollingBack/Rollback/Failure": TaskFailed,
"RollingBack/TimeOut/Failure": TaskFailed,
"RollingBack/Rollback/Success": TaskFailed,
"Upgrading/Rollback/Failure": TaskFailed,
"Upgrading/Rollback/Success": TaskFailed,
//TODO delete in version 1.18
"Init/Rollback/Failure": TaskFailed,
"Init/Rollback/Success": TaskFailed,
}
var UpdateStageSequence = map[State]State{
"": TaskChecking,
TaskInit: TaskChecking,
TaskChecking: BackingUpState,
BackingUpState: UpgradingState,
UpgradingState: RollingBackState,
}

View File

@ -0,0 +1,19 @@
/*
Copyright 2022 The KubeEdge 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.
*/
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package
package v1alpha1

View File

@ -0,0 +1,164 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
api "github.com/kubeedge/api/apis/fsm/v1alpha1"
)
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ImagePrePullJob is used to prepull images on edge node.
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Cluster
type ImagePrePullJob struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Spec represents the specification of the desired behavior of ImagePrePullJob.
// +required
Spec ImagePrePullJobSpec `json:"spec"`
// Status represents the status of ImagePrePullJob.
// +optional
Status ImagePrePullJobStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ImagePrePullJobList is a list of ImagePrePullJob.
type ImagePrePullJobList struct {
// Standard type metadata.
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
metav1.ListMeta `json:"metadata,omitempty"`
// List of ImagePrePullJob.
Items []ImagePrePullJob `json:"items"`
}
// ImagePrePullSpec represents the specification of the desired behavior of ImagePrePullJob.
type ImagePrePullJobSpec struct {
// ImagePrepullTemplate represents original templates of imagePrePull
ImagePrePullTemplate ImagePrePullTemplate `json:"imagePrePullTemplate,omitempty"`
}
// ImagePrePullTemplate represents original templates of imagePrePull
type ImagePrePullTemplate struct {
// Images is the image list to be prepull
Images []string `json:"images,omitempty"`
// NodeNames is a request to select some specific nodes. If it is non-empty,
// the upgrade job simply select these edge nodes to do upgrade operation.
// Please note that sets of NodeNames and LabelSelector are ORed.
// Users must set one and can only set one.
// +optional
NodeNames []string `json:"nodeNames,omitempty"`
// LabelSelector is a filter to select member clusters by labels.
// It must match a node's labels for the NodeUpgradeJob to be operated on that node.
// Please note that sets of NodeNames and LabelSelector are ORed.
// Users must set one and can only set one.
// +optional
LabelSelector *metav1.LabelSelector `json:"labelSelector,omitempty"`
// CheckItems specifies the items need to be checked before the task is executed.
// The default CheckItems value is disk.
// +optional
CheckItems []string `json:"checkItems,omitempty"`
// FailureTolerate specifies the task tolerance failure ratio.
// The default FailureTolerate value is 0.1.
// +optional
FailureTolerate string `json:"failureTolerate,omitempty"`
// Concurrency specifies the maximum number of edge nodes that can pull images at the same time.
// The default Concurrency value is 1.
// +optional
Concurrency int32 `json:"concurrency,omitempty"`
// TimeoutSeconds limits the duration of the node prepull job on each edgenode.
// Default to 300.
// If set to 0, we'll use the default value 300.
// +optional
TimeoutSeconds *uint32 `json:"timeoutSeconds,omitempty"`
// ImageSecret specifies the secret for image pull if private registry used.
// Use {namespace}/{secretName} in format.
// +optional
ImageSecret string `json:"imageSecrets,omitempty"`
// RetryTimes specifies the retry times if image pull failed on each edgenode.
// Default to 0
// +optional
RetryTimes int32 `json:"retryTimes,omitempty"`
}
// ImagePrePullJobStatus stores the status of ImagePrePullJob.
// contains images prepull status on multiple edge nodes.
// +kubebuilder:validation:Type=object
type ImagePrePullJobStatus struct {
// State represents for the state phase of the ImagePrePullJob.
// There are five possible state values: "", checking, pulling, successful, failed.
State api.State `json:"state,omitempty"`
// Event represents for the event of the ImagePrePullJob.
// There are four possible event values: Init, Check, Pull, TimeOut.
Event string `json:"event,omitempty"`
// Action represents for the action of the ImagePrePullJob.
// There are two possible action values: Success, Failure.
Action api.Action `json:"action,omitempty"`
// Reason represents for the reason of the ImagePrePullJob.
Reason string `json:"reason,omitempty"`
// Time represents for the running time of the ImagePrePullJob.
Time string `json:"time,omitempty"`
// Status contains image prepull status for each edge node.
Status []ImagePrePullStatus `json:"status,omitempty"`
}
// ImagePrePullStatus stores image prepull status for each edge node.
// +kubebuilder:validation:Type=object
type ImagePrePullStatus struct {
// TaskStatus represents the status for each node
*TaskStatus `json:"nodeStatus,omitempty"`
// ImageStatus represents the prepull status for each image
ImageStatus []ImageStatus `json:"imageStatus,omitempty"`
}
// ImageStatus stores the prepull status for each image.
// +kubebuilder:validation:Type=object
type ImageStatus struct {
// Image is the name of the image
Image string `json:"image,omitempty"`
// State represents for the state phase of this image pull on the edge node
// There are two possible state values: successful, failed.
State api.State `json:"state,omitempty"`
// Reason represents the fail reason if image pull failed
// +optional
Reason string `json:"reason,omitempty"`
}

View File

@ -0,0 +1,73 @@
/*
Copyright 2022 The KubeEdge 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.
*/
// NOTE: Boilerplate only. Ignore this file.
// Package v1alpha1 contains API Schema definitions for the Operations v1alpha1 API group
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=kubeedge/pkg/apis/operations
// +k8s:defaulter-gen=TypeMeta
// +groupName=operations.kubeedge.io
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
const (
// GroupName is the group name use in this package.
GroupName = "operations.kubeedge.io"
// Version is the API version.
Version = "v1alpha1"
)
var (
// SchemeGroupVersion is the group version used to register these objects.
SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: Version}
)
func init() {
// 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.
localSchemeBuilder.Register(addKnownTypes)
}
// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&NodeUpgradeJob{},
&NodeUpgradeJobList{},
&ImagePrePullJob{},
&ImagePrePullJobList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -0,0 +1,180 @@
/*
Copyright 2022 The KubeEdge 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 v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
api "github.com/kubeedge/api/apis/fsm/v1alpha1"
)
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// NodeUpgradeJob is used to upgrade edge node from cloud side.
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Cluster
type NodeUpgradeJob struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Specification of the desired behavior of NodeUpgradeJob.
// +optional
Spec NodeUpgradeJobSpec `json:"spec,omitempty"`
// Most recently observed status of the NodeUpgradeJob.
// +optional
Status NodeUpgradeJobStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// NodeUpgradeJobList is a list of NodeUpgradeJob.
type NodeUpgradeJobList struct {
// Standard type metadata.
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
metav1.ListMeta `json:"metadata,omitempty"`
// List of NodeUpgradeJobs.
Items []NodeUpgradeJob `json:"items"`
}
// NodeUpgradeJobSpec is the specification of the desired behavior of the NodeUpgradeJob.
type NodeUpgradeJobSpec struct {
// +Required: Version is the EdgeCore version to upgrade.
Version string `json:"version,omitempty"`
// TimeoutSeconds limits the duration of the node upgrade job.
// Default to 300.
// If set to 0, we'll use the default value 300.
// +optional
TimeoutSeconds *uint32 `json:"timeoutSeconds,omitempty"`
// NodeNames is a request to select some specific nodes. If it is non-empty,
// the upgrade job simply select these edge nodes to do upgrade operation.
// Please note that sets of NodeNames and LabelSelector are ORed.
// Users must set one and can only set one.
// +optional
NodeNames []string `json:"nodeNames,omitempty"`
// LabelSelector is a filter to select member clusters by labels.
// It must match a node's labels for the NodeUpgradeJob to be operated on that node.
// Please note that sets of NodeNames and LabelSelector are ORed.
// Users must set one and can only set one.
// +optional
LabelSelector *metav1.LabelSelector `json:"labelSelector,omitempty"`
// Image specifies a container image name, the image contains: keadm and edgecore.
// keadm is used as upgradetool, to install the new version of edgecore.
// The image name consists of registry hostname and repository name,
// if it includes the tag or digest, the tag or digest will be overwritten by Version field above.
// If the registry hostname is empty, docker.io will be used as default.
// The default image name is: kubeedge/installation-package.
// +optional
Image string `json:"image,omitempty"`
// ImageDigestGatter define registry v2 interface access configuration.
// As a transition, it is not required at first, and the image digest is checked when this field is set.
// +optional
ImageDigestGatter *ImageDigestGatter `json:"imageDigestGatter"`
// Concurrency specifies the max number of edge nodes that can be upgraded at the same time.
// The default Concurrency value is 1.
// +optional
Concurrency int32 `json:"concurrency,omitempty"`
// CheckItems specifies the items need to be checked before the task is executed.
// The default CheckItems value is nil.
// +optional
CheckItems []string `json:"checkItems,omitempty"`
// FailureTolerate specifies the task tolerance failure ratio.
// The default FailureTolerate value is 0.1.
// +optional
FailureTolerate string `json:"failureTolerate,omitempty"`
// RequireConfirmation specifies whether you need to confirm the upgrade.
// The default RequireConfirmation value is false.
// +optional
RequireConfirmation bool `json:"requireConfirmation,omitempty"`
}
// ImageDigestGatter used to define a method for getting the image digest
type ImageDigestGatter struct {
// Value used to directly set a value to check image
// +optional
Value *string `json:"value,omitempty"`
// RegistryAPI define registry v2 interface access configuration
// +optional
RegistryAPI *RegistryAPI `json:"registryAPI,omitempty"`
}
// RegistryAPI used to define registry v2 interface access configuration
type RegistryAPI struct {
Host string `json:"host"`
Token string `json:"token"`
}
// NodeUpgradeJobStatus stores the status of NodeUpgradeJob.
// contains multiple edge nodes upgrade status.
// +kubebuilder:validation:Type=object
type NodeUpgradeJobStatus struct {
// State represents for the state phase of the NodeUpgradeJob.
// There are several possible state values: "", Upgrading, BackingUp, RollingBack and Checking.
State api.State `json:"state,omitempty"`
// CurrentVersion represents for the current status of the EdgeCore.
CurrentVersion string `json:"currentVersion,omitempty"`
// HistoricVersion represents for the historic status of the EdgeCore.
HistoricVersion string `json:"historicVersion,omitempty"`
// Event represents for the event of the ImagePrePullJob.
// There are six possible event values: Init, Check, BackUp, Upgrade, TimeOut, Rollback.
Event string `json:"event,omitempty"`
// Action represents for the action of the ImagePrePullJob.
// There are two possible action values: Success, Failure.
Action api.Action `json:"action,omitempty"`
// Reason represents for the reason of the ImagePrePullJob.
Reason string `json:"reason,omitempty"`
// Time represents for the running time of the ImagePrePullJob.
Time string `json:"time,omitempty"`
// Status contains upgrade Status for each edge node.
Status []TaskStatus `json:"nodeStatus,omitempty"`
}
// TaskStatus stores the status of Upgrade for each edge node.
// +kubebuilder:validation:Type=object
type TaskStatus struct {
// NodeName is the name of edge node.
NodeName string `json:"nodeName,omitempty"`
// State represents for the upgrade state phase of the edge node.
// There are several possible state values: "", Upgrading, BackingUp, RollingBack and Checking.
State api.State `json:"state,omitempty"`
// Event represents for the event of the ImagePrePullJob.
// There are three possible event values: Init, Check, Pull.
Event string `json:"event,omitempty"`
// Action represents for the action of the ImagePrePullJob.
// There are three possible action values: Success, Failure, TimeOut.
Action api.Action `json:"action,omitempty"`
// Reason represents for the reason of the ImagePrePullJob.
Reason string `json:"reason,omitempty"`
// Time represents for the running time of the ImagePrePullJob.
Time string `json:"time,omitempty"`
}

View File

@ -0,0 +1,392 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The KubeEdge 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 deepcopy-gen. DO NOT EDIT.
package v1alpha1
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImageDigestGatter) DeepCopyInto(out *ImageDigestGatter) {
*out = *in
if in.Value != nil {
in, out := &in.Value, &out.Value
*out = new(string)
**out = **in
}
if in.RegistryAPI != nil {
in, out := &in.RegistryAPI, &out.RegistryAPI
*out = new(RegistryAPI)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageDigestGatter.
func (in *ImageDigestGatter) DeepCopy() *ImageDigestGatter {
if in == nil {
return nil
}
out := new(ImageDigestGatter)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImagePrePullJob) DeepCopyInto(out *ImagePrePullJob) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePrePullJob.
func (in *ImagePrePullJob) DeepCopy() *ImagePrePullJob {
if in == nil {
return nil
}
out := new(ImagePrePullJob)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ImagePrePullJob) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImagePrePullJobList) DeepCopyInto(out *ImagePrePullJobList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ImagePrePullJob, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePrePullJobList.
func (in *ImagePrePullJobList) DeepCopy() *ImagePrePullJobList {
if in == nil {
return nil
}
out := new(ImagePrePullJobList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ImagePrePullJobList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImagePrePullJobSpec) DeepCopyInto(out *ImagePrePullJobSpec) {
*out = *in
in.ImagePrePullTemplate.DeepCopyInto(&out.ImagePrePullTemplate)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePrePullJobSpec.
func (in *ImagePrePullJobSpec) DeepCopy() *ImagePrePullJobSpec {
if in == nil {
return nil
}
out := new(ImagePrePullJobSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImagePrePullJobStatus) DeepCopyInto(out *ImagePrePullJobStatus) {
*out = *in
if in.Status != nil {
in, out := &in.Status, &out.Status
*out = make([]ImagePrePullStatus, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePrePullJobStatus.
func (in *ImagePrePullJobStatus) DeepCopy() *ImagePrePullJobStatus {
if in == nil {
return nil
}
out := new(ImagePrePullJobStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImagePrePullStatus) DeepCopyInto(out *ImagePrePullStatus) {
*out = *in
if in.TaskStatus != nil {
in, out := &in.TaskStatus, &out.TaskStatus
*out = new(TaskStatus)
**out = **in
}
if in.ImageStatus != nil {
in, out := &in.ImageStatus, &out.ImageStatus
*out = make([]ImageStatus, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePrePullStatus.
func (in *ImagePrePullStatus) DeepCopy() *ImagePrePullStatus {
if in == nil {
return nil
}
out := new(ImagePrePullStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImagePrePullTemplate) DeepCopyInto(out *ImagePrePullTemplate) {
*out = *in
if in.Images != nil {
in, out := &in.Images, &out.Images
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.NodeNames != nil {
in, out := &in.NodeNames, &out.NodeNames
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.LabelSelector != nil {
in, out := &in.LabelSelector, &out.LabelSelector
*out = new(v1.LabelSelector)
(*in).DeepCopyInto(*out)
}
if in.CheckItems != nil {
in, out := &in.CheckItems, &out.CheckItems
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.TimeoutSeconds != nil {
in, out := &in.TimeoutSeconds, &out.TimeoutSeconds
*out = new(uint32)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePrePullTemplate.
func (in *ImagePrePullTemplate) DeepCopy() *ImagePrePullTemplate {
if in == nil {
return nil
}
out := new(ImagePrePullTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImageStatus) DeepCopyInto(out *ImageStatus) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageStatus.
func (in *ImageStatus) DeepCopy() *ImageStatus {
if in == nil {
return nil
}
out := new(ImageStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeUpgradeJob) DeepCopyInto(out *NodeUpgradeJob) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeUpgradeJob.
func (in *NodeUpgradeJob) DeepCopy() *NodeUpgradeJob {
if in == nil {
return nil
}
out := new(NodeUpgradeJob)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *NodeUpgradeJob) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeUpgradeJobList) DeepCopyInto(out *NodeUpgradeJobList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]NodeUpgradeJob, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeUpgradeJobList.
func (in *NodeUpgradeJobList) DeepCopy() *NodeUpgradeJobList {
if in == nil {
return nil
}
out := new(NodeUpgradeJobList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *NodeUpgradeJobList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeUpgradeJobSpec) DeepCopyInto(out *NodeUpgradeJobSpec) {
*out = *in
if in.TimeoutSeconds != nil {
in, out := &in.TimeoutSeconds, &out.TimeoutSeconds
*out = new(uint32)
**out = **in
}
if in.NodeNames != nil {
in, out := &in.NodeNames, &out.NodeNames
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.LabelSelector != nil {
in, out := &in.LabelSelector, &out.LabelSelector
*out = new(v1.LabelSelector)
(*in).DeepCopyInto(*out)
}
if in.ImageDigestGatter != nil {
in, out := &in.ImageDigestGatter, &out.ImageDigestGatter
*out = new(ImageDigestGatter)
(*in).DeepCopyInto(*out)
}
if in.CheckItems != nil {
in, out := &in.CheckItems, &out.CheckItems
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeUpgradeJobSpec.
func (in *NodeUpgradeJobSpec) DeepCopy() *NodeUpgradeJobSpec {
if in == nil {
return nil
}
out := new(NodeUpgradeJobSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NodeUpgradeJobStatus) DeepCopyInto(out *NodeUpgradeJobStatus) {
*out = *in
if in.Status != nil {
in, out := &in.Status, &out.Status
*out = make([]TaskStatus, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeUpgradeJobStatus.
func (in *NodeUpgradeJobStatus) DeepCopy() *NodeUpgradeJobStatus {
if in == nil {
return nil
}
out := new(NodeUpgradeJobStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RegistryAPI) DeepCopyInto(out *RegistryAPI) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistryAPI.
func (in *RegistryAPI) DeepCopy() *RegistryAPI {
if in == nil {
return nil
}
out := new(RegistryAPI)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TaskStatus) DeepCopyInto(out *TaskStatus) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskStatus.
func (in *TaskStatus) DeepCopy() *TaskStatus {
if in == nil {
return nil
}
out := new(TaskStatus)
in.DeepCopyInto(out)
return out
}

View File

@ -0,0 +1,21 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1 is the v1alpha1 version of the API.
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +groupName=policy.kubeedge.io
package v1alpha1

View File

@ -0,0 +1,61 @@
// Copyright 2023 The KubeEdge 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 v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
const (
// GroupName is the group name use in this package.
GroupName = "policy.kubeedge.io"
// Version is the API version.
Version = "v1alpha1"
)
var (
// SchemeGroupVersion is the group version used to register these objects.
SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: Version}
)
func init() {
// 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.
localSchemeBuilder.Register(addKnownTypes)
}
// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&ServiceAccountAccess{},
&ServiceAccountAccessList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -0,0 +1,88 @@
/*
Copyright 2023 The KubeEdge 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 v1alpha1
import (
corev1 "k8s.io/api/core/v1"
rbac "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:shortName=saaccess
// ServiceAccountAccess is the Schema for the ServiceAccountAccess API
type ServiceAccountAccess struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Spec represents the specification of rbac.
// +required
Spec AccessSpec `json:"spec,omitempty"`
// Status represents the node list which store the rules.
// +optional
Status AccessStatus `json:"status,omitempty"`
}
// AccessStatus defines the observed state of ServiceAccountAccess
type AccessStatus struct {
// NodeList represents the node name which store the rules.
NodeList []string `json:"nodeList,omitempty"`
}
// +kubebuilder:object:root=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ServiceAccountAccessList contains a list of ServiceAccountAccess
type ServiceAccountAccessList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []ServiceAccountAccess `json:"items"`
}
// AccessSpec defines the desired state of AccessSpec
type AccessSpec struct {
// ServiceAccount is one-to-one corresponding relations with the serviceaccountaccess.
ServiceAccount corev1.ServiceAccount `json:"serviceAccount,omitempty"`
// ServiceAccountUID is the uid of serviceaccount.
ServiceAccountUID types.UID `json:"serviceAccountUid,omitempty"`
// AccessRoleBinding represents rbac rolebinding plus detailed role info.
AccessRoleBinding []AccessRoleBinding `json:"accessRoleBinding,omitempty"`
// AccessClusterRoleBinding represents rbac ClusterRoleBinding plus detailed ClusterRole info.
AccessClusterRoleBinding []AccessClusterRoleBinding `json:"accessClusterRoleBinding,omitempty"`
}
// AccessRoleBinding represents rbac rolebinding plus detailed role info.
type AccessRoleBinding struct {
// RoleBinding represents rbac rolebinding.
RoleBinding rbac.RoleBinding `json:"roleBinding,omitempty"`
// Rules contains role rules.
Rules []rbac.PolicyRule `json:"rules,omitempty"`
}
// AccessClusterRoleBinding represents rbac ClusterRoleBinding plus detailed ClusterRole info.
type AccessClusterRoleBinding struct {
// ClusterRoleBinding represents rbac ClusterRoleBinding.
ClusterRoleBinding rbac.ClusterRoleBinding `json:"clusterRoleBinding,omitempty"`
// Rules contains role rules.
Rules []rbac.PolicyRule `json:"rules,omitempty"`
}

View File

@ -0,0 +1,188 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The KubeEdge 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 deepcopy-gen. DO NOT EDIT.
package v1alpha1
import (
v1 "k8s.io/api/rbac/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AccessClusterRoleBinding) DeepCopyInto(out *AccessClusterRoleBinding) {
*out = *in
in.ClusterRoleBinding.DeepCopyInto(&out.ClusterRoleBinding)
if in.Rules != nil {
in, out := &in.Rules, &out.Rules
*out = make([]v1.PolicyRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccessClusterRoleBinding.
func (in *AccessClusterRoleBinding) DeepCopy() *AccessClusterRoleBinding {
if in == nil {
return nil
}
out := new(AccessClusterRoleBinding)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AccessRoleBinding) DeepCopyInto(out *AccessRoleBinding) {
*out = *in
in.RoleBinding.DeepCopyInto(&out.RoleBinding)
if in.Rules != nil {
in, out := &in.Rules, &out.Rules
*out = make([]v1.PolicyRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccessRoleBinding.
func (in *AccessRoleBinding) DeepCopy() *AccessRoleBinding {
if in == nil {
return nil
}
out := new(AccessRoleBinding)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AccessSpec) DeepCopyInto(out *AccessSpec) {
*out = *in
in.ServiceAccount.DeepCopyInto(&out.ServiceAccount)
if in.AccessRoleBinding != nil {
in, out := &in.AccessRoleBinding, &out.AccessRoleBinding
*out = make([]AccessRoleBinding, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.AccessClusterRoleBinding != nil {
in, out := &in.AccessClusterRoleBinding, &out.AccessClusterRoleBinding
*out = make([]AccessClusterRoleBinding, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccessSpec.
func (in *AccessSpec) DeepCopy() *AccessSpec {
if in == nil {
return nil
}
out := new(AccessSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AccessStatus) DeepCopyInto(out *AccessStatus) {
*out = *in
if in.NodeList != nil {
in, out := &in.NodeList, &out.NodeList
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccessStatus.
func (in *AccessStatus) DeepCopy() *AccessStatus {
if in == nil {
return nil
}
out := new(AccessStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ServiceAccountAccess) DeepCopyInto(out *ServiceAccountAccess) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceAccountAccess.
func (in *ServiceAccountAccess) DeepCopy() *ServiceAccountAccess {
if in == nil {
return nil
}
out := new(ServiceAccountAccess)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ServiceAccountAccess) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ServiceAccountAccessList) DeepCopyInto(out *ServiceAccountAccessList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ServiceAccountAccess, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceAccountAccessList.
func (in *ServiceAccountAccessList) DeepCopy() *ServiceAccountAccessList {
if in == nil {
return nil
}
out := new(ServiceAccountAccessList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ServiceAccountAccessList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}

View File

@ -0,0 +1,21 @@
/*
Copyright 2020 The KubeEdge 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.
*/
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// Package v1alpha1 is the v1alpha1 version of the API.
// +groupName=reliablesyncs.kubeedge.io
package v1alpha1

View File

@ -0,0 +1,63 @@
// Copyright 2020 The KubeEdge 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 v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
const (
// GroupName is the group name use in this package.
GroupName = "reliablesyncs.kubeedge.io"
// Version is the API version.
Version = "v1alpha1"
)
var (
// SchemeGroupVersion is the group version used to register these objects.
SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: Version}
)
func init() {
// 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.
localSchemeBuilder.Register(addKnownTypes)
}
// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&ObjectSync{},
&ObjectSyncList{},
&ClusterObjectSync{},
&ClusterObjectSyncList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -0,0 +1,103 @@
/*
Copyright 2020 The KubeEdge 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 v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ClusterObjectSync stores the state of the cluster level, nonNamespaced object that was successfully persisted to the edge node.
// ClusterObjectSync name is a concatenation of the node name which receiving the object and the object UUID.
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Cluster
type ClusterObjectSync struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ObjectSyncSpec `json:"spec,omitempty"`
Status ObjectSyncStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ClusterObjectSyncList is a list of ObjectSync.
type ClusterObjectSyncList struct {
// Standard type metadata.
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
metav1.ListMeta `json:"metadata,omitempty"`
// List of ClusterObjectSync.
Items []ClusterObjectSync `json:"items"`
}
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ObjectSync stores the state of the namespaced object that was successfully persisted to the edge node.
// ObjectSync name is a concatenation of the node name which receiving the object and the object UUID.
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
type ObjectSync struct {
// Standard Kubernetes type metadata.
metav1.TypeMeta `json:",inline"`
// Standard Kubernetes object's metadata.
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ObjectSyncSpec `json:"spec,omitempty"`
Status ObjectSyncStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ObjectSyncList is a list of ObjectSync.
type ObjectSyncList struct {
// Standard type metadata.
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
metav1.ListMeta `json:"metadata,omitempty"`
// List of ObjectSync.
Items []ObjectSync `json:"items"`
}
// ObjectSyncSpec stores the details of objects that persist to the edge.
type ObjectSyncSpec struct {
// ObjectAPIVersion is the APIVersion of the object
// that was successfully persist to the edge node.
ObjectAPIVersion string `json:"objectAPIVersion,omitempty"`
// ObjectType is the kind of the object
// that was successfully persist to the edge node.
ObjectKind string `json:"objectKind,omitempty"`
// ObjectName is the name of the object
// that was successfully persist to the edge node.
ObjectName string `json:"objectName,omitempty"`
}
// ObjectSyncStatus stores the resourceversion of objects that persist to the edge.
type ObjectSyncStatus struct {
// ObjectResourceVersion is the resourceversion of the object
// that was successfully persist to the edge node.
ObjectResourceVersion string `json:"objectResourceVersion,omitempty"`
}

View File

@ -0,0 +1,180 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The KubeEdge 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 deepcopy-gen. DO NOT EDIT.
package v1alpha1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterObjectSync) DeepCopyInto(out *ClusterObjectSync) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
out.Status = in.Status
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterObjectSync.
func (in *ClusterObjectSync) DeepCopy() *ClusterObjectSync {
if in == nil {
return nil
}
out := new(ClusterObjectSync)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ClusterObjectSync) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterObjectSyncList) DeepCopyInto(out *ClusterObjectSyncList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ClusterObjectSync, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterObjectSyncList.
func (in *ClusterObjectSyncList) DeepCopy() *ClusterObjectSyncList {
if in == nil {
return nil
}
out := new(ClusterObjectSyncList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ClusterObjectSyncList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ObjectSync) DeepCopyInto(out *ObjectSync) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
out.Status = in.Status
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectSync.
func (in *ObjectSync) DeepCopy() *ObjectSync {
if in == nil {
return nil
}
out := new(ObjectSync)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ObjectSync) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ObjectSyncList) DeepCopyInto(out *ObjectSyncList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ObjectSync, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectSyncList.
func (in *ObjectSyncList) DeepCopy() *ObjectSyncList {
if in == nil {
return nil
}
out := new(ObjectSyncList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ObjectSyncList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ObjectSyncSpec) DeepCopyInto(out *ObjectSyncSpec) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectSyncSpec.
func (in *ObjectSyncSpec) DeepCopy() *ObjectSyncSpec {
if in == nil {
return nil
}
out := new(ObjectSyncSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ObjectSyncStatus) DeepCopyInto(out *ObjectSyncStatus) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectSyncStatus.
func (in *ObjectSyncStatus) DeepCopy() *ObjectSyncStatus {
if in == nil {
return nil
}
out := new(ObjectSyncStatus)
in.DeepCopyInto(out)
return out
}

4
apis/rules/v1/doc.go Normal file
View File

@ -0,0 +1,4 @@
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package
// +groupName=rules.kubeedge.io
package v1

71
apis/rules/v1/register.go Normal file
View File

@ -0,0 +1,71 @@
/*
Copyright 2019 The KubeEdge 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 contains API Schema definitions for the rules v1 API group
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=kubeedge/cloud/pkg/apis/rules
// +k8s:defaulter-gen=TypeMeta
// +groupName=rules.kubeedge.io
package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
const (
// GroupName is the group name use in this package.
GroupName = "rules.kubeedge.io"
// Version is the API version.
Version = "v1"
)
var (
// SchemeGroupVersion is the group version used to register these objects.
SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: Version}
)
func init() {
// 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.
localSchemeBuilder.Register(addKnownTypes)
}
// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Rule{},
&RuleList{},
&RuleEndpoint{},
&RuleEndpointList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

93
apis/rules/v1/types.go Normal file
View File

@ -0,0 +1,93 @@
package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// RuleSpec defines rule of message delivery.
type RuleSpec struct {
// Source represents where the messages come from. Its value is the same with ruleendpoint name.
// For example, rest or eventbus.
Source string `json:"source"`
// SourceResource is a map representing the resource info of source. For rest
// ruleendpoint type its value is {"path":"/a/b"}. For eventbus ruleendpoint type its
// value is {"topic":"<user define string>","node_name":"xxxx"}
SourceResource map[string]string `json:"sourceResource"`
// Target represents where the messages go to. its value is the same with ruleendpoint name.
// For example, eventbus or api or servicebus.
Target string `json:"target"`
// targetResource is a map representing the resource info of target. For api
// ruleendpoint type its value is {"resource":"http://a.com"}. For eventbus ruleendpoint
// type its value is {"topic":"/xxxx"}. For servicebus ruleendpoint type its value is {"path":"/request_path"}.
TargetResource map[string]string `json:"targetResource"`
}
// RuleStatus defines status of message delivery.
type RuleStatus struct {
// SuccessMessages represents success count of message delivery of rule.
SuccessMessages int64 `json:"successMessages"`
// FailMessages represents failed count of message delivery of rule.
FailMessages int64 `json:"failMessages"`
// Errors represents failed reasons of message delivery of rule.
Errors []string `json:"errors"`
}
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Rule is the Schema for the rules API
// +k8s:openapi-gen=true
type Rule struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec RuleSpec `json:"spec"`
Status RuleStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// RuleList contains a list of Rule
type RuleList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Rule `json:"items"`
}
// RuleEndpointSpec defines endpoint of rule.
type RuleEndpointSpec struct {
// RuleEndpointType defines type: servicebus, rest
RuleEndpointType RuleEndpointTypeDef `json:"ruleEndpointType"`
// Properties: properties of endpoint. for example:
// servicebus:
// {"service_port":"8080"}
Properties map[string]string `json:"properties,omitempty"`
}
// RuleEndpointTypeDef defines ruleEndpoint's type
type RuleEndpointTypeDef string
// RuleEndpoint's types.
const (
RuleEndpointTypeRest RuleEndpointTypeDef = "rest"
RuleEndpointTypeEventBus RuleEndpointTypeDef = "eventbus"
RuleEndpointTypeServiceBus RuleEndpointTypeDef = "servicebus"
)
// +genclient
// +genclient:noStatus
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// RuleEndpoint is the Schema for the ruleendpoints API
// +k8s:openapi-gen=true
type RuleEndpoint struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec RuleEndpointSpec `json:"spec"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// RuleEndpointList contains a list of RuleEndpoint
type RuleEndpointList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []RuleEndpoint `json:"items"`
}

View File

@ -0,0 +1,221 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The KubeEdge 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 deepcopy-gen. DO NOT EDIT.
package v1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Rule) DeepCopyInto(out *Rule) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Rule.
func (in *Rule) DeepCopy() *Rule {
if in == nil {
return nil
}
out := new(Rule)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Rule) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleEndpoint) DeepCopyInto(out *RuleEndpoint) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleEndpoint.
func (in *RuleEndpoint) DeepCopy() *RuleEndpoint {
if in == nil {
return nil
}
out := new(RuleEndpoint)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *RuleEndpoint) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleEndpointList) DeepCopyInto(out *RuleEndpointList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]RuleEndpoint, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleEndpointList.
func (in *RuleEndpointList) DeepCopy() *RuleEndpointList {
if in == nil {
return nil
}
out := new(RuleEndpointList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *RuleEndpointList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleEndpointSpec) DeepCopyInto(out *RuleEndpointSpec) {
*out = *in
if in.Properties != nil {
in, out := &in.Properties, &out.Properties
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleEndpointSpec.
func (in *RuleEndpointSpec) DeepCopy() *RuleEndpointSpec {
if in == nil {
return nil
}
out := new(RuleEndpointSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleList) DeepCopyInto(out *RuleList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Rule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleList.
func (in *RuleList) DeepCopy() *RuleList {
if in == nil {
return nil
}
out := new(RuleList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *RuleList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleSpec) DeepCopyInto(out *RuleSpec) {
*out = *in
if in.SourceResource != nil {
in, out := &in.SourceResource, &out.SourceResource
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.TargetResource != nil {
in, out := &in.TargetResource, &out.TargetResource
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleSpec.
func (in *RuleSpec) DeepCopy() *RuleSpec {
if in == nil {
return nil
}
out := new(RuleSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleStatus) DeepCopyInto(out *RuleStatus) {
*out = *in
if in.Errors != nil {
in, out := &in.Errors, &out.Errors
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleStatus.
func (in *RuleStatus) DeepCopy() *RuleStatus {
if in == nil {
return nil
}
out := new(RuleStatus)
in.DeepCopyInto(out)
return out
}

129
apis/util/flag/flags.go Normal file
View File

@ -0,0 +1,129 @@
/*
Copyright 2020 The KubeEdge 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 flag
import (
"fmt"
"os"
"strconv"
"github.com/spf13/pflag"
"k8s.io/klog/v2"
"sigs.k8s.io/yaml"
)
type ConfigValue int
const (
ConfigFalse ConfigValue = 0
ConfigTrue ConfigValue = 1
)
func (m *ConfigValue) IsBoolFlag() bool {
return true
}
func (m *ConfigValue) Get() interface{} {
return ConfigValue(*m)
}
func (m *ConfigValue) Set(s string) error {
boolVal, err := strconv.ParseBool(s)
if boolVal {
*m = ConfigTrue
} else {
*m = ConfigFalse
}
return err
}
func (m *ConfigValue) String() string {
return fmt.Sprintf("%v", bool(*m == ConfigTrue))
}
// The type of the flag as required by the pflag.Value interface
func (m *ConfigValue) Type() string {
return "config"
}
func ConfigVar(p *ConfigValue, name string, value ConfigValue, usage string) {
*p = value
pflag.Var(p, name, usage)
pflag.Lookup(name).NoOptDefVal = "true"
}
func Config(name string, value ConfigValue, usage string) *ConfigValue {
p := new(ConfigValue)
ConfigVar(p, name, value, usage)
return p
}
const minConfigFlagName = "minconfig"
const defaultConfigFlagName = "defaultconfig"
var (
minConfigFlag = Config(minConfigFlagName, ConfigFalse, "Print min configuration for reference, users can refer to it to create their own configuration files, it is suitable for beginners.")
defaultConfigFlag = Config(defaultConfigFlagName, ConfigFalse, "Print default configuration for reference, users can refer to it to create their own configuration files, it is suitable for advanced users.")
)
// AddFlags registers this package's flags on arbitrary FlagSets, such that they point to the
// same value as the global flags.
func AddFlags(fs *pflag.FlagSet) {
fs.AddFlag(pflag.Lookup(minConfigFlagName))
fs.AddFlag(pflag.Lookup(defaultConfigFlagName))
}
// PrintMinConfigAndExitIfRequested will check if the -minconfig flag was passed
// and, if so, print the min config and exit.
func PrintMinConfigAndExitIfRequested(config interface{}) {
if *minConfigFlag == ConfigTrue {
data, err := yaml.Marshal(config)
if err != nil {
fmt.Printf("Marshal min config to yaml error %v\n", err)
os.Exit(1)
}
fmt.Println("# With --minconfig , you can easily used this configurations as reference.")
fmt.Println("# It's useful to users who are new to KubeEdge, and you can modify/create your own configs accordingly. ")
fmt.Println("# This configuration is suitable for beginners.")
fmt.Printf("\n%v\n\n", string(data))
os.Exit(0)
}
}
// PrintDefaultConfigAndExitIfRequested will check if the --defaultconfig flag was passed
// and, if so, print the default config and exit.
func PrintDefaultConfigAndExitIfRequested(config interface{}) {
if *defaultConfigFlag == ConfigTrue {
data, err := yaml.Marshal(config)
if err != nil {
fmt.Printf("Marshal default config to yaml error %v\n", err)
os.Exit(1)
}
fmt.Println("# With --defaultconfig flag, users can easily get a default full config file as reference, with all fields (and field descriptions) included and default values set. ")
fmt.Println("# Users can modify/create their own configs accordingly as reference. ")
fmt.Println("# Because it is a full configuration, it is more suitable for advanced users.")
fmt.Printf("\n%v\n\n", string(data))
os.Exit(0)
}
}
// PrintFlags logs the flags in the flagset
func PrintFlags(flags *pflag.FlagSet) {
flags.VisitAll(func(flag *pflag.Flag) {
klog.V(1).Infof("FLAG: --%s=%q", flag.Name, flag.Value)
})
}

139
apis/util/fsm/fsm.go Normal file
View File

@ -0,0 +1,139 @@
/*
Copyright 2023 The KubeEdge 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 fsm
import (
"fmt"
"k8s.io/klog/v2"
api "github.com/kubeedge/api/apis/fsm/v1alpha1"
)
type FSM struct {
id string
nodeName string
lastState api.State
currentFunc func(id, nodeName string) (api.State, error)
updateFunc func(id, nodeName string, state api.State, event Event) error
guard map[string]api.State
stageSequence map[api.State]api.State
}
func (F *FSM) NodeName(nodeName string) *FSM {
F.nodeName = nodeName
return F
}
type Event struct {
Type string
Action api.Action
Msg string
ExternalMessage string
}
func (e Event) UniqueName() string {
return e.Type + "/" + string(e.Action)
}
func (F *FSM) ID(id string) *FSM {
F.id = id
return F
}
func (F *FSM) LastState(lastState api.State) {
F.lastState = lastState
}
func (F *FSM) CurrentFunc(currentFunc func(id, nodeName string) (api.State, error)) *FSM {
F.currentFunc = currentFunc
return F
}
func (F *FSM) UpdateFunc(updateFunc func(id, nodeName string, state api.State, event Event) error) *FSM {
F.updateFunc = updateFunc
return F
}
func (F *FSM) Guard(guard map[string]api.State) *FSM {
F.guard = guard
return F
}
func (F *FSM) StageSequence(stageSequence map[api.State]api.State) *FSM {
F.stageSequence = stageSequence
return F
}
func (F *FSM) CurrentState() (api.State, error) {
if F.currentFunc == nil {
return "", fmt.Errorf("currentFunc is nil")
}
return F.currentFunc(F.id, F.nodeName)
}
func (F *FSM) transitCheck(event Event) (api.State, api.State, error) {
currentState, err := F.CurrentState()
if err != nil {
return "", "", err
}
if F.guard == nil {
return "", "", fmt.Errorf("guard is nil ")
}
nextState, ok := F.guard[string(currentState)+"/"+event.UniqueName()]
if !ok {
return "", "", fmt.Errorf(string(currentState)+"/"+event.UniqueName(), " unsupported event")
}
return currentState, nextState, nil
}
func (F *FSM) AllowTransit(event Event) error {
_, _, err := F.transitCheck(event)
return err
}
func (F *FSM) Transit(event Event) error {
currentState, nextState, err := F.transitCheck(event)
if err != nil {
return err
}
if F.updateFunc == nil {
return fmt.Errorf("updateFunc is nil")
}
err = F.updateFunc(F.id, F.nodeName, nextState, event)
if err != nil {
return err
}
F.lastState = currentState
return nil
}
func TaskFinish(state api.State) bool {
return state == api.TaskFailed || state == api.TaskSuccessful
}
func (F *FSM) TaskStagCompleted(state api.State) bool {
currentState, err := F.CurrentState()
if err != nil {
klog.Errorf("get %s current state failed: %s", F.id, err.Error())
return false
}
if F.stageSequence[currentState] == state || TaskFinish(state) {
return true
}
return false
}

View File

@ -0,0 +1,22 @@
package passthrough
type passRequest string
const (
versionRequest passRequest = "/version::get"
healthRequest passRequest = "/healthz::get" // deprecated: TODO remove this once it is gone
liveRequest passRequest = "/livez::get"
readyRequest passRequest = "/readyz::get"
)
var passThroughMap = map[passRequest]bool{
versionRequest: true,
healthRequest: true,
liveRequest: true,
readyRequest: true,
}
// IsPassThroughPath determining whether the uri can be passed through
func IsPassThroughPath(path, verb string) bool {
return passThroughMap[passRequest(path+"::"+verb)]
}

View File

@ -0,0 +1,61 @@
package passthrough
import "testing"
func TestIsPassThroughPath(t *testing.T) {
tests := []struct {
name string
path string
verb string
want bool
}{
{
name: "/version::post is not pass through path",
path: "/version",
verb: "post",
want: false,
}, {
name: "/version::get is pass through path",
path: "/version",
verb: "get",
want: true,
}, {
name: "/healthz::put is not pass through path",
path: "/healthz",
verb: "put",
want: false,
}, {
name: "/healthz::get is pass through path",
path: "/healthz",
verb: "get",
want: true,
}, {
name: "/livez::patch is not pass through path",
path: "/livez",
verb: "patch",
want: false,
}, {
name: "/livez::get is pass through path",
path: "/livez",
verb: "get",
want: true,
}, {
name: "/readyz::delete is not pass through path",
path: "/readyz",
verb: "delete",
want: false,
}, {
name: "/readyz::get is pass through path",
path: "/readyz",
verb: "get",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsPassThroughPath(tt.path, tt.verb); got != tt.want {
t.Errorf("IsPassThroughPath() = %v, want %v", got, tt.want)
}
})
}
}

158
apis/util/util.go Normal file
View File

@ -0,0 +1,158 @@
/*
Copyright 2018 The KubeEdge 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 util
import (
"bytes"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
utilnet "k8s.io/apimachinery/pkg/util/net"
nodeutil "k8s.io/component-helpers/node/util"
"k8s.io/kubernetes/pkg/apis/core/validation"
"github.com/kubeedge/api/apis/common/constants"
)
func GetLocalIP(hostName string) (string, error) {
var ipAddr net.IP
var err error
// If looks up host failed, will use utilnet.ChooseHostInterface() below,
// So ignore the error here
addrs, _ := net.LookupIP(hostName)
for _, addr := range addrs {
if err := ValidateNodeIP(addr); err != nil {
continue
}
if addr.To4() != nil {
ipAddr = addr
break
}
if ipAddr == nil && addr.To16() != nil {
ipAddr = addr
}
}
if ipAddr == nil {
ipAddr, err = utilnet.ChooseHostInterface()
if err != nil {
return "", err
}
}
return ipAddr.String(), nil
}
// ValidateNodeIP validates given node IP belongs to the current host
func ValidateNodeIP(nodeIP net.IP) error {
// Honor IP limitations set in setNodeStatus()
if nodeIP.To4() == nil && nodeIP.To16() == nil {
return fmt.Errorf("nodeIP must be a valid IP address")
}
if nodeIP.IsLoopback() {
return fmt.Errorf("nodeIP can't be loopback address")
}
if nodeIP.IsMulticast() {
return fmt.Errorf("nodeIP can't be a multicast address")
}
if nodeIP.IsLinkLocalUnicast() {
return fmt.Errorf("nodeIP can't be a link-local unicast address")
}
if nodeIP.IsUnspecified() {
return fmt.Errorf("nodeIP can't be an all zeros address")
}
addrs, err := net.InterfaceAddrs()
if err != nil {
return err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip != nil && ip.Equal(nodeIP) {
return nil
}
}
return fmt.Errorf("node IP: %q not found in the host's network interfaces", nodeIP.String())
}
// Command executes command and returns output
func Command(name string, arg []string) (string, error) {
cmd := exec.Command(name, arg...)
ret, err := cmd.Output()
if err != nil {
return string(ret), err
}
return strings.Trim(string(ret), "\n"), nil
}
// GetCurPath returns filepath
func GetCurPath() string {
file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
rst := filepath.Dir(path)
return rst
}
func SpliceErrors(errors []error) string {
if len(errors) == 0 {
return ""
}
var stb strings.Builder
stb.WriteString("[\n")
for _, err := range errors {
stb.WriteString(fmt.Sprintf(" %s\n", err.Error()))
}
stb.WriteString("]\n")
return stb.String()
}
// GetHostname returns a reasonable hostname
func GetHostname() string {
hostnameOverride, err := nodeutil.GetHostname("")
if err != nil {
return constants.DefaultHostnameOverride
}
msgs := validation.ValidateNodeName(hostnameOverride, false)
if len(msgs) > 0 {
return constants.DefaultHostnameOverride
}
return hostnameOverride
}
// ConcatStrings use bytes.buffer to concatenate string variable
func ConcatStrings(ss ...string) string {
var bff bytes.Buffer
for _, s := range ss {
bff.WriteString(s)
}
return bff.String()
}
// GetResourceID return resource ID
func GetResourceID(namespace, name string) string {
return namespace + "/" + name
}

165
apis/util/util_test.go Normal file
View File

@ -0,0 +1,165 @@
package util
import (
"errors"
"fmt"
"net"
"reflect"
"strings"
"testing"
)
func TestValidateNodeIP(t *testing.T) {
hostnameOverride := GetHostname()
localIP, _ := GetLocalIP(hostnameOverride)
cases := []struct {
name string
ip net.IP
expected error
}{
{
name: "case1",
ip: nil,
expected: fmt.Errorf("nodeIP must be a valid IP address"),
},
{
name: "case2",
ip: net.IPv4(127, 0, 0, 1),
expected: fmt.Errorf("nodeIP can't be loopback address"),
},
{
name: "case3",
ip: net.IPv4(239, 0, 0, 254),
expected: fmt.Errorf("nodeIP can't be a multicast address"),
},
{
name: "case4",
ip: net.IPv4(169, 254, 0, 0),
expected: fmt.Errorf("nodeIP can't be a link-local unicast address"),
},
{
name: "case5",
ip: net.IPv4(0, 0, 0, 0),
expected: fmt.Errorf("nodeIP can't be an all zeros address"),
},
{
name: "case 6",
ip: net.ParseIP(localIP),
expected: nil,
},
{
name: "case 7",
ip: net.IPv4(114, 114, 114, 114),
expected: fmt.Errorf("node IP: %q not found in the host's network interfaces", "114.114.114.114"),
},
}
for _, c := range cases {
err := ValidateNodeIP(c.ip)
if !reflect.DeepEqual(err, c.expected) {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, err)
}
}
}
func TestCommand(t *testing.T) {
cases := []struct {
name string
command string
expected bool
}{
{
name: "case1",
command: "fake_command_test",
expected: false,
},
{
name: "case2",
command: "ls",
expected: true,
},
}
for _, c := range cases {
_, err := Command(c.command, nil)
isSuccess := err == nil
if isSuccess != c.expected {
t.Errorf("%v: expected %v, but got %v", c.name, c.expected, isSuccess)
}
}
}
func TestGetCurPath(t *testing.T) {
path := GetCurPath()
if path == "" {
t.Errorf("failed to get current path")
}
}
func TestGetHostname(t *testing.T) {
name := GetHostname()
if name == "" {
t.Errorf("get host name failed")
}
}
func TestGetLocalIP(t *testing.T) {
_, err := GetLocalIP(GetHostname())
if err != nil {
t.Errorf("get local ip failed")
}
}
func TestSpliceErrors(t *testing.T) {
err1 := errors.New("this is error 1")
err2 := errors.New("this is error 2")
err3 := errors.New("this is error 3")
const head = "[\n"
var line1 = fmt.Sprintf(" %s\n", err1)
var line2 = fmt.Sprintf(" %s\n", err2)
var line3 = fmt.Sprintf(" %s\n", err3)
const tail = "]\n"
sliceOutput := SpliceErrors([]error{err1, err2, err3})
if strings.Index(sliceOutput, head) != 0 ||
strings.Index(sliceOutput, line1) != len(head) ||
strings.Index(sliceOutput, line2) != len(head+line1) ||
strings.Index(sliceOutput, line3) != len(head+line1+line2) ||
strings.Index(sliceOutput, tail) != len(head+line1+line2+line3) {
t.Error("the func format the multiple elements error slice unexpected")
return
}
if SpliceErrors([]error{}) != "" || SpliceErrors(nil) != "" {
t.Error("the func format the zero-length error slice unexpected")
return
}
}
func TestConcatStrings(t *testing.T) {
cases := []struct {
args []string
expect string
}{
{
args: []string{},
expect: "",
},
{
args: nil,
expect: "",
},
{
args: []string{"a", "", "b"},
expect: "ab",
},
}
var s string
for _, c := range cases {
s = ConcatStrings(c.args...)
if s != c.expect {
t.Errorf("the func return failed. expect: %s, actual: %s\n", c.expect, s)
return
}
}
}

View File

@ -0,0 +1,14 @@
package validation
import (
"os"
)
// FileIsExist check file is exist
func FileIsExist(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
return os.IsExist(err)
}

View File

@ -0,0 +1,25 @@
package validation
import (
"os"
"path/filepath"
"testing"
)
func TestFileIsExist(t *testing.T) {
dir := t.TempDir()
ef, err := os.CreateTemp(dir, "CheckFileIsExist")
if err == nil {
if !FileIsExist(ef.Name()) {
t.Fatalf("file %v should exist", ef.Name())
}
}
nonexistentDir := filepath.Join(dir, "not_exist_dir")
notExistFile := filepath.Join(nonexistentDir, "not_exist_file")
if FileIsExist(notExistFile) {
t.Fatalf("file %v should not exist", notExistFile)
}
}

View File

@ -0,0 +1,44 @@
/*
Copyright 2019 The KubeEdge 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 validation
import (
"fmt"
"net"
)
// IsValidIP tests that the argument is a valid IP address.
func IsValidIP(value string) []string {
if net.ParseIP(value) == nil {
return []string{"must be a valid IP address, (e.g. 10.9.8.7)"}
}
return nil
}
// IsValidPortNum tests that the argument is a valid, non-zero port number.
func IsValidPortNum(port int) []string {
if 1 <= port && port <= 65535 {
return nil
}
return []string{InclusiveRangeError(1, 65535)}
}
// InclusiveRangeError returns a string explanation of a numeric "must be
// between" validation failure.
func InclusiveRangeError(lo, hi int) string {
return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi)
}

View File

@ -0,0 +1,96 @@
package validation
import (
"reflect"
"testing"
)
func TestIsValidIP(t *testing.T) {
cases := []struct {
Name string
IP string
Expect bool
}{
{
Name: "valid ip",
IP: "1.1.1.1",
Expect: true,
},
{
Name: "invalid have port",
IP: "1.1.1.1:1234",
Expect: false,
},
{
Name: "invalid ip1",
IP: "1.1.1.",
Expect: false,
},
{
Name: "invalid unit socket",
IP: "unix:///var/run/docker.sock",
Expect: false,
},
{
Name: "invalid http",
IP: "http://127.0.0.1",
Expect: false,
},
}
for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
v := IsValidIP(c.IP)
get := len(v) == 0
if get != c.Expect {
t.Errorf("Input %s Expect %v while get %v", c.IP, c.Expect, v)
}
})
}
}
func TestIsValidPortNum(t *testing.T) {
cases := []struct {
Name string
Port int
Expect []string
}{
{
Name: "invalid port",
Port: 0,
Expect: []string{"must be between 1 and 65535, inclusive"},
},
{
Name: "valid port",
Port: 1,
Expect: nil,
},
{
Name: "valid port",
Port: 65535,
Expect: nil,
},
{
Name: "invalid port",
Port: 65536,
Expect: []string{"must be between 1 and 65535, inclusive"},
},
}
for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
v := IsValidPortNum(c.Port)
if !reflect.DeepEqual(v, c.Expect) {
t.Errorf("Input %d Expect %v while get %v", c.Port, c.Expect, v)
}
})
}
}
func TestInclusiveRangeError(t *testing.T) {
result := InclusiveRangeError(1, 65535)
expect := "must be between 1 and 65535, inclusive"
if !reflect.DeepEqual(result, expect) {
t.Errorf("Expected %v while get %v", expect, result)
}
}

View File

@ -0,0 +1,185 @@
/*
Copyright The KubeEdge 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 versioned
import (
"fmt"
"net/http"
appsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/apps/v1alpha1"
devicesv1beta1 "github.com/kubeedge/api/client/clientset/versioned/typed/devices/v1beta1"
operationsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/operations/v1alpha1"
policyv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/policy/v1alpha1"
reliablesyncsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/reliablesyncs/v1alpha1"
rulesv1 "github.com/kubeedge/api/client/clientset/versioned/typed/rules/v1"
discovery "k8s.io/client-go/discovery"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
)
type Interface interface {
Discovery() discovery.DiscoveryInterface
AppsV1alpha1() appsv1alpha1.AppsV1alpha1Interface
DevicesV1beta1() devicesv1beta1.DevicesV1beta1Interface
OperationsV1alpha1() operationsv1alpha1.OperationsV1alpha1Interface
PolicyV1alpha1() policyv1alpha1.PolicyV1alpha1Interface
ReliablesyncsV1alpha1() reliablesyncsv1alpha1.ReliablesyncsV1alpha1Interface
RulesV1() rulesv1.RulesV1Interface
}
// Clientset contains the clients for groups.
type Clientset struct {
*discovery.DiscoveryClient
appsV1alpha1 *appsv1alpha1.AppsV1alpha1Client
devicesV1beta1 *devicesv1beta1.DevicesV1beta1Client
operationsV1alpha1 *operationsv1alpha1.OperationsV1alpha1Client
policyV1alpha1 *policyv1alpha1.PolicyV1alpha1Client
reliablesyncsV1alpha1 *reliablesyncsv1alpha1.ReliablesyncsV1alpha1Client
rulesV1 *rulesv1.RulesV1Client
}
// AppsV1alpha1 retrieves the AppsV1alpha1Client
func (c *Clientset) AppsV1alpha1() appsv1alpha1.AppsV1alpha1Interface {
return c.appsV1alpha1
}
// DevicesV1beta1 retrieves the DevicesV1beta1Client
func (c *Clientset) DevicesV1beta1() devicesv1beta1.DevicesV1beta1Interface {
return c.devicesV1beta1
}
// OperationsV1alpha1 retrieves the OperationsV1alpha1Client
func (c *Clientset) OperationsV1alpha1() operationsv1alpha1.OperationsV1alpha1Interface {
return c.operationsV1alpha1
}
// PolicyV1alpha1 retrieves the PolicyV1alpha1Client
func (c *Clientset) PolicyV1alpha1() policyv1alpha1.PolicyV1alpha1Interface {
return c.policyV1alpha1
}
// ReliablesyncsV1alpha1 retrieves the ReliablesyncsV1alpha1Client
func (c *Clientset) ReliablesyncsV1alpha1() reliablesyncsv1alpha1.ReliablesyncsV1alpha1Interface {
return c.reliablesyncsV1alpha1
}
// RulesV1 retrieves the RulesV1Client
func (c *Clientset) RulesV1() rulesv1.RulesV1Interface {
return c.rulesV1
}
// 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.
// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),
// where httpClient was generated with rest.HTTPClientFor(c).
func NewForConfig(c *rest.Config) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.UserAgent == "" {
configShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()
}
// share the transport between all clients
httpClient, err := rest.HTTPClientFor(&configShallowCopy)
if err != nil {
return nil, err
}
return NewForConfigAndClient(&configShallowCopy, httpClient)
}
// NewForConfigAndClient creates a new Clientset for the given config and http client.
// Note the http client provided takes precedence over the configured transport values.
// If config's RateLimiter is not set and QPS and Burst are acceptable,
// NewForConfigAndClient will generate a rate-limiter in configShallowCopy.
func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*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.appsV1alpha1, err = appsv1alpha1.NewForConfigAndClient(&configShallowCopy, httpClient)
if err != nil {
return nil, err
}
cs.devicesV1beta1, err = devicesv1beta1.NewForConfigAndClient(&configShallowCopy, httpClient)
if err != nil {
return nil, err
}
cs.operationsV1alpha1, err = operationsv1alpha1.NewForConfigAndClient(&configShallowCopy, httpClient)
if err != nil {
return nil, err
}
cs.policyV1alpha1, err = policyv1alpha1.NewForConfigAndClient(&configShallowCopy, httpClient)
if err != nil {
return nil, err
}
cs.reliablesyncsV1alpha1, err = reliablesyncsv1alpha1.NewForConfigAndClient(&configShallowCopy, httpClient)
if err != nil {
return nil, err
}
cs.rulesV1, err = rulesv1.NewForConfigAndClient(&configShallowCopy, httpClient)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(&configShallowCopy, httpClient)
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 {
cs, err := NewForConfig(c)
if err != nil {
panic(err)
}
return cs
}
// New creates a new Clientset for the given RESTClient.
func New(c rest.Interface) *Clientset {
var cs Clientset
cs.appsV1alpha1 = appsv1alpha1.New(c)
cs.devicesV1beta1 = devicesv1beta1.New(c)
cs.operationsV1alpha1 = operationsv1alpha1.New(c)
cs.policyV1alpha1 = policyv1alpha1.New(c)
cs.reliablesyncsV1alpha1 = reliablesyncsv1alpha1.New(c)
cs.rulesV1 = rulesv1.New(c)
cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
return &cs
}

View File

@ -0,0 +1,120 @@
/*
Copyright The KubeEdge 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 fake
import (
clientset "github.com/kubeedge/api/client/clientset/versioned"
appsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/apps/v1alpha1"
fakeappsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/apps/v1alpha1/fake"
devicesv1beta1 "github.com/kubeedge/api/client/clientset/versioned/typed/devices/v1beta1"
fakedevicesv1beta1 "github.com/kubeedge/api/client/clientset/versioned/typed/devices/v1beta1/fake"
operationsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/operations/v1alpha1"
fakeoperationsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/operations/v1alpha1/fake"
policyv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/policy/v1alpha1"
fakepolicyv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/policy/v1alpha1/fake"
reliablesyncsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/reliablesyncs/v1alpha1"
fakereliablesyncsv1alpha1 "github.com/kubeedge/api/client/clientset/versioned/typed/reliablesyncs/v1alpha1/fake"
rulesv1 "github.com/kubeedge/api/client/clientset/versioned/typed/rules/v1"
fakerulesv1 "github.com/kubeedge/api/client/clientset/versioned/typed/rules/v1/fake"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/discovery"
fakediscovery "k8s.io/client-go/discovery/fake"
"k8s.io/client-go/testing"
)
// NewSimpleClientset returns a clientset that will respond with the provided objects.
// It's backed by a very simple object tracker that processes creates, updates and deletions as-is,
// without applying any validations and/or defaults. It shouldn't be considered a replacement
// for a real clientset and is mostly useful in simple unit tests.
func NewSimpleClientset(objects ...runtime.Object) *Clientset {
o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())
for _, obj := range objects {
if err := o.Add(obj); err != nil {
panic(err)
}
}
cs := &Clientset{tracker: o}
cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake}
cs.AddReactor("*", "*", testing.ObjectReaction(o))
cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) {
gvr := action.GetResource()
ns := action.GetNamespace()
watch, err := o.Watch(gvr, ns)
if err != nil {
return false, nil, err
}
return true, watch, nil
})
return cs
}
// Clientset implements clientset.Interface. Meant to be embedded into a
// struct to get a default implementation. This makes faking out just the method
// you want to test easier.
type Clientset struct {
testing.Fake
discovery *fakediscovery.FakeDiscovery
tracker testing.ObjectTracker
}
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
return c.discovery
}
func (c *Clientset) Tracker() testing.ObjectTracker {
return c.tracker
}
var (
_ clientset.Interface = &Clientset{}
_ testing.FakeClient = &Clientset{}
)
// AppsV1alpha1 retrieves the AppsV1alpha1Client
func (c *Clientset) AppsV1alpha1() appsv1alpha1.AppsV1alpha1Interface {
return &fakeappsv1alpha1.FakeAppsV1alpha1{Fake: &c.Fake}
}
// DevicesV1beta1 retrieves the DevicesV1beta1Client
func (c *Clientset) DevicesV1beta1() devicesv1beta1.DevicesV1beta1Interface {
return &fakedevicesv1beta1.FakeDevicesV1beta1{Fake: &c.Fake}
}
// OperationsV1alpha1 retrieves the OperationsV1alpha1Client
func (c *Clientset) OperationsV1alpha1() operationsv1alpha1.OperationsV1alpha1Interface {
return &fakeoperationsv1alpha1.FakeOperationsV1alpha1{Fake: &c.Fake}
}
// PolicyV1alpha1 retrieves the PolicyV1alpha1Client
func (c *Clientset) PolicyV1alpha1() policyv1alpha1.PolicyV1alpha1Interface {
return &fakepolicyv1alpha1.FakePolicyV1alpha1{Fake: &c.Fake}
}
// ReliablesyncsV1alpha1 retrieves the ReliablesyncsV1alpha1Client
func (c *Clientset) ReliablesyncsV1alpha1() reliablesyncsv1alpha1.ReliablesyncsV1alpha1Interface {
return &fakereliablesyncsv1alpha1.FakeReliablesyncsV1alpha1{Fake: &c.Fake}
}
// RulesV1 retrieves the RulesV1Client
func (c *Clientset) RulesV1() rulesv1.RulesV1Interface {
return &fakerulesv1.FakeRulesV1{Fake: &c.Fake}
}

View File

@ -0,0 +1,20 @@
/*
Copyright The KubeEdge 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.
// This package has the automatically generated fake clientset.
package fake

View File

@ -0,0 +1,66 @@
/*
Copyright The KubeEdge 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 fake
import (
appsv1alpha1 "github.com/kubeedge/api/apis/apps/v1alpha1"
devicesv1beta1 "github.com/kubeedge/api/apis/devices/v1beta1"
operationsv1alpha1 "github.com/kubeedge/api/apis/operations/v1alpha1"
policyv1alpha1 "github.com/kubeedge/api/apis/policy/v1alpha1"
reliablesyncsv1alpha1 "github.com/kubeedge/api/apis/reliablesyncs/v1alpha1"
rulesv1 "github.com/kubeedge/api/apis/rules/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
var scheme = runtime.NewScheme()
var codecs = serializer.NewCodecFactory(scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
appsv1alpha1.AddToScheme,
devicesv1beta1.AddToScheme,
operationsv1alpha1.AddToScheme,
policyv1alpha1.AddToScheme,
reliablesyncsv1alpha1.AddToScheme,
rulesv1.AddToScheme,
}
// AddToScheme adds all types of this clientset into the given scheme. This allows composition
// of clientsets, like in:
//
// import (
// "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kubernetes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// )
//
// kclientset, _ := kubernetes.NewForConfig(c)
// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
//
// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types
// correctly.
var AddToScheme = localSchemeBuilder.AddToScheme
func init() {
v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(AddToScheme(scheme))
}

View File

@ -0,0 +1,20 @@
/*
Copyright The KubeEdge 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.
// This package contains the scheme of the automatically generated clientset.
package scheme

View File

@ -0,0 +1,66 @@
/*
Copyright The KubeEdge 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 scheme
import (
appsv1alpha1 "github.com/kubeedge/api/apis/apps/v1alpha1"
devicesv1beta1 "github.com/kubeedge/api/apis/devices/v1beta1"
operationsv1alpha1 "github.com/kubeedge/api/apis/operations/v1alpha1"
policyv1alpha1 "github.com/kubeedge/api/apis/policy/v1alpha1"
reliablesyncsv1alpha1 "github.com/kubeedge/api/apis/reliablesyncs/v1alpha1"
rulesv1 "github.com/kubeedge/api/apis/rules/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
var Scheme = runtime.NewScheme()
var Codecs = serializer.NewCodecFactory(Scheme)
var ParameterCodec = runtime.NewParameterCodec(Scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
appsv1alpha1.AddToScheme,
devicesv1beta1.AddToScheme,
operationsv1alpha1.AddToScheme,
policyv1alpha1.AddToScheme,
reliablesyncsv1alpha1.AddToScheme,
rulesv1.AddToScheme,
}
// AddToScheme adds all types of this clientset into the given scheme. This allows composition
// of clientsets, like in:
//
// import (
// "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kubernetes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// )
//
// kclientset, _ := kubernetes.NewForConfig(c)
// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
//
// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types
// correctly.
var AddToScheme = localSchemeBuilder.AddToScheme
func init() {
v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(AddToScheme(Scheme))
}

View File

@ -0,0 +1,112 @@
/*
Copyright The KubeEdge 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 v1alpha1
import (
"net/http"
v1alpha1 "github.com/kubeedge/api/apis/apps/v1alpha1"
"github.com/kubeedge/api/client/clientset/versioned/scheme"
rest "k8s.io/client-go/rest"
)
type AppsV1alpha1Interface interface {
RESTClient() rest.Interface
EdgeApplicationsGetter
NodeGroupsGetter
}
// AppsV1alpha1Client is used to interact with features provided by the apps.kubeedge.io group.
type AppsV1alpha1Client struct {
restClient rest.Interface
}
func (c *AppsV1alpha1Client) EdgeApplications(namespace string) EdgeApplicationInterface {
return newEdgeApplications(c, namespace)
}
func (c *AppsV1alpha1Client) NodeGroups() NodeGroupInterface {
return newNodeGroups(c)
}
// NewForConfig creates a new AppsV1alpha1Client for the given config.
// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),
// where httpClient was generated with rest.HTTPClientFor(c).
func NewForConfig(c *rest.Config) (*AppsV1alpha1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
httpClient, err := rest.HTTPClientFor(&config)
if err != nil {
return nil, err
}
return NewForConfigAndClient(&config, httpClient)
}
// NewForConfigAndClient creates a new AppsV1alpha1Client for the given config and http client.
// Note the http client provided takes precedence over the configured transport values.
func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1alpha1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientForConfigAndClient(&config, h)
if err != nil {
return nil, err
}
return &AppsV1alpha1Client{client}, nil
}
// NewForConfigOrDie creates a new AppsV1alpha1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *AppsV1alpha1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new AppsV1alpha1Client for the given RESTClient.
func New(c rest.Interface) *AppsV1alpha1Client {
return &AppsV1alpha1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1alpha1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
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 *AppsV1alpha1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}

View File

@ -0,0 +1,20 @@
/*
Copyright The KubeEdge 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.
// This package has the automatically generated typed clients.
package v1alpha1

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