diff --git a/api/v1alpha1/virtualservice_methods.go b/api/v1alpha1/virtualservice_methods.go index d98c6ff8..d6c8fa4e 100644 --- a/api/v1alpha1/virtualservice_methods.go +++ b/api/v1alpha1/virtualservice_methods.go @@ -19,6 +19,9 @@ package v1alpha1 import ( "context" "encoding/json" + "fmt" + "github.com/kaasops/envoy-xds-controller/pkg/utils/k8s" + "slices" "strings" "github.com/kaasops/envoy-xds-controller/pkg/errors" @@ -140,6 +143,101 @@ func (vs *VirtualService) getHash() (*uint32, error) { return &hash, nil } +func (vs *VirtualService) GetAll(ctx context.Context, namespace string, cl client.Client) ([]string, error) { + vsList := &VirtualServiceList{} + options := []client.ListOption{} + + if namespace != "" { + options = append(options, client.InNamespace(namespace)) + } + + if err := cl.List(ctx, vsList, options...); err != nil { + return nil, fmt.Errorf("failed to list VirtualServices: %w", err) + } + + names := []string{} + for _, item := range vsList.Items { + names = append(names, item.Name) + } + + return names, nil +} + +func (vs *VirtualService) GetAllWithWrongState(ctx context.Context, namespace string, cl client.Client) ([]string, error) { + vsList := &VirtualServiceList{} + options := []client.ListOption{} + + if namespace != "" { + options = append(options, client.InNamespace(namespace)) + } + + if err := cl.List(ctx, vsList, options...); err != nil { + return nil, fmt.Errorf("failed to list VirtualServices: %w", err) + } + + wrongVsNames := []string{} + + for _, item := range vsList.Items { + if (item.Status.Valid != nil && !*item.Status.Valid) || item.Status.Error != nil { + wrongVsNames = append(wrongVsNames, item.Name) + } + } + return wrongVsNames, nil +} + +func (vs *VirtualService) Get(ctx context.Context, name, namespace string, cl client.Client) (*VirtualService, error) { + item := &VirtualService{} + if err := cl.Get(ctx, client.ObjectKey{Name: name, Namespace: namespace}, item); err != nil { + return nil, fmt.Errorf("failed to get VirtualService: %w", err) + } + return item, nil +} + +func (vs *VirtualService) GetByNameAndNodeId(ctx context.Context, name, nodeId, namespace string, cl client.Client) (*VirtualService, error) { + vsList := &VirtualServiceList{} + + if err := cl.List(ctx, vsList, client.InNamespace(namespace)); err != nil { + return nil, fmt.Errorf("failed to list VirtualServices: %w", err) + } + + for _, item := range vsList.Items { + if item.Name == name { + nodeIDs := k8s.NodeIDs(&item) + if slices.Contains(nodeIDs, nodeId) { + return &item, nil + } + } + } + + return nil, fmt.Errorf("VirtualService not found") +} + +func (vs *VirtualService) CreateVirtualService(ctx context.Context, item *VirtualService, cl client.Client) error { + if err := cl.Create(ctx, item); err != nil { + return fmt.Errorf("failed to create VirtualService: %w", err) + } + return nil +} + +func (vs *VirtualService) UpdateVirtualService(ctx context.Context, item *VirtualService, cl client.Client) error { + if err := cl.Update(ctx, item); err != nil { + return fmt.Errorf("failed to update VirtualService: %w", err) + } + return nil +} + +func (vs *VirtualService) DeleteVirtualService(ctx context.Context, name, namespace string, cl client.Client) error { + item := &VirtualService{} + if err := cl.Get(ctx, client.ObjectKey{Name: name, Namespace: namespace}, item); err != nil { + return fmt.Errorf("failed to get VirtualService: %w", err) + } + + if err := cl.Delete(ctx, item); err != nil { + return fmt.Errorf("failed to delete VirtualService: %w", err) + } + return nil +} + /** TlsConfig Methods **/ diff --git a/docs/kubeRestAPI/kube_docs.go b/docs/kubeRestAPI/kube_docs.go new file mode 100644 index 00000000..e66dd45f --- /dev/null +++ b/docs/kubeRestAPI/kube_docs.go @@ -0,0 +1,657 @@ +// Package kubeRestAPI Code generated by swaggo/swag. DO NOT EDIT +package kubeRestAPI + +import "github.com/swaggo/swag" + +const docTemplatekube = `{ + "schemes": {{ marshal .Schemes }}, + "swagger": "2.0", + "info": { + "description": "{{escape .Description}}", + "title": "{{.Title}}", + "contact": {}, + "version": "{{.Version}}" + }, + "host": "{{.Host}}", + "basePath": "{{.BasePath}}", + "paths": { + "/virtualservices": { + "get": { + "description": "Get names of all Virtual Services", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Get all Virtual Services", + "parameters": [ + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + }, + "put": { + "description": "Update an existing Virtual Service", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Update an existing Virtual Service", + "parameters": [ + { + "description": "Virtual Service object", + "name": "virtualservice", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + }, + "post": { + "description": "Create a new Virtual Service", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Create a new Virtual Service", + "parameters": [ + { + "description": "Virtual Service object", + "name": "virtualservice", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + }, + "/virtualservices/search": { + "get": { + "description": "Search in which Virtual Service a specific domain is described", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Search for a Virtual Service by name and nodeID", + "parameters": [ + { + "type": "string", + "description": "Virtual Service Name", + "name": "name", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Node ID", + "name": "nodeId", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + }, + "/virtualservices/wrong-state": { + "get": { + "description": "Get names of all Virtual Services that have an erroneous state", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Get all Virtual Services with erroneous state", + "parameters": [ + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + }, + "/virtualservices/{name}": { + "get": { + "description": "Get a specific Virtual Service by name", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Get a specific Virtual Service", + "parameters": [ + { + "type": "string", + "description": "Virtual Service Name", + "name": "name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Delete a Virtual Service", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Delete a Virtual Service", + "parameters": [ + { + "type": "string", + "description": "Virtual Service Name", + "name": "name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "runtime.RawExtension": { + "type": "object" + }, + "types.ErrorResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer" + }, + "message": { + "type": "string" + } + } + }, + "v1.FieldsV1": { + "type": "object" + }, + "v1.ManagedFieldsEntry": { + "type": "object", + "properties": { + "apiVersion": { + "description": "APIVersion defines the version of this resource that this field set\napplies to. The format is \"group/version\" just like the top-level\nAPIVersion field. It is necessary to track the version of a field\nset because it cannot be automatically converted.", + "type": "string" + }, + "fieldsType": { + "description": "FieldsType is the discriminator for the different fields format and version.\nThere is currently only one possible value: \"FieldsV1\"", + "type": "string" + }, + "fieldsV1": { + "description": "FieldsV1 holds the first JSON version format as described in the \"FieldsV1\" type.\n+optional", + "allOf": [ + { + "$ref": "#/definitions/v1.FieldsV1" + } + ] + }, + "manager": { + "description": "Manager is an identifier of the workflow managing these fields.", + "type": "string" + }, + "operation": { + "description": "Operation is the type of operation which lead to this ManagedFieldsEntry being created.\nThe only valid values for this field are 'Apply' and 'Update'.", + "allOf": [ + { + "$ref": "#/definitions/v1.ManagedFieldsOperationType" + } + ] + }, + "subresource": { + "description": "Subresource is the name of the subresource used to update that object, or\nempty string if the object was updated through the main resource. The\nvalue of this field is used to distinguish between managers, even if they\nshare the same name. For example, a status update will be distinct from a\nregular update using the same manager name.\nNote that the APIVersion field is not related to the Subresource field and\nit always corresponds to the version of the main resource.", + "type": "string" + }, + "time": { + "description": "Time is the timestamp of when the ManagedFields entry was added. The\ntimestamp will also be updated if a field is added, the manager\nchanges any of the owned fields value or removes a field. The\ntimestamp does not update when a field is removed from the entry\nbecause another manager took it over.\n+optional", + "type": "string" + } + } + }, + "v1.ManagedFieldsOperationType": { + "type": "string", + "enum": [ + "Apply", + "Update" + ], + "x-enum-varnames": [ + "ManagedFieldsOperationApply", + "ManagedFieldsOperationUpdate" + ] + }, + "v1.ObjectMeta": { + "type": "object", + "properties": { + "annotations": { + "description": "Annotations is an unstructured key value map stored with a resource that may be\nset by external tools to store and retrieve arbitrary metadata. They are not\nqueryable and should be preserved when modifying objects.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations\n+optional", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "creationTimestamp": { + "description": "CreationTimestamp is a timestamp representing the server time when this object was\ncreated. It is not guaranteed to be set in happens-before order across separate operations.\nClients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system.\nRead-only.\nNull for lists.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\n+optional", + "type": "string" + }, + "deletionGracePeriodSeconds": { + "description": "Number of seconds allowed for this object to gracefully terminate before\nit will be removed from the system. Only set when deletionTimestamp is also set.\nMay only be shortened.\nRead-only.\n+optional", + "type": "integer" + }, + "deletionTimestamp": { + "description": "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This\nfield is set by the server when a graceful deletion is requested by the user, and is not\ndirectly settable by a client. The resource is expected to be deleted (no longer visible\nfrom resource lists, and not reachable by name) after the time in this field, once the\nfinalizers list is empty. As long as the finalizers list contains items, deletion is blocked.\nOnce the deletionTimestamp is set, this value may not be unset or be set further into the\nfuture, although it may be shortened or the resource may be deleted prior to this time.\nFor example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react\nby sending a graceful termination signal to the containers in the pod. After that 30 seconds,\nthe Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup,\nremove the pod from the API. In the presence of network partitions, this object may still\nexist after this timestamp, until an administrator or automated process can determine the\nresource is fully terminated.\nIf not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested.\nRead-only.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\n+optional", + "type": "string" + }, + "finalizers": { + "description": "Must be empty before the object is deleted from the registry. Each entry\nis an identifier for the responsible component that will remove the entry\nfrom the list. If the deletionTimestamp of the object is non-nil, entries\nin this list can only be removed.\nFinalizers may be processed and removed in any order. Order is NOT enforced\nbecause it introduces significant risk of stuck finalizers.\nfinalizers is a shared field, any actor with permission can reorder it.\nIf the finalizer list is processed in order, then this can lead to a situation\nin which the component responsible for the first finalizer in the list is\nwaiting for a signal (field value, external system, or other) produced by a\ncomponent responsible for a finalizer later in the list, resulting in a deadlock.\nWithout enforced ordering finalizers are free to order amongst themselves and\nare not vulnerable to ordering changes in the list.\n+optional\n+patchStrategy=merge", + "type": "array", + "items": { + "type": "string" + } + }, + "generateName": { + "description": "GenerateName is an optional prefix, used by the server, to generate a unique\nname ONLY IF the Name field has not been provided.\nIf this field is used, the name returned to the client will be different\nthan the name passed. This value will also be combined with a unique suffix.\nThe provided value has the same validation rules as the Name field,\nand may be truncated by the length of the suffix required to make the value\nunique on the server.\n\nIf this field is specified and the generated name exists, the server will return a 409.\n\nApplied only if Name is not specified.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency\n+optional", + "type": "string" + }, + "generation": { + "description": "A sequence number representing a specific generation of the desired state.\nPopulated by the system. Read-only.\n+optional", + "type": "integer" + }, + "labels": { + "description": "Map of string keys and values that can be used to organize and categorize\n(scope and select) objects. May match selectors of replication controllers\nand services.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels\n+optional", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "managedFields": { + "description": "ManagedFields maps workflow-id and version to the set of fields\nthat are managed by that workflow. This is mostly for internal\nhousekeeping, and users typically shouldn't need to set or\nunderstand this field. A workflow can be the user's name, a\ncontroller's name, or the name of a specific apply path like\n\"ci-cd\". The set of fields is always in the version that the\nworkflow used when modifying the object.\n\n+optional", + "type": "array", + "items": { + "$ref": "#/definitions/v1.ManagedFieldsEntry" + } + }, + "name": { + "description": "Name must be unique within a namespace. Is required when creating resources, although\nsome resources may allow a client to request the generation of an appropriate name\nautomatically. Name is primarily intended for creation idempotence and configuration\ndefinition.\nCannot be updated.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names\n+optional", + "type": "string" + }, + "namespace": { + "description": "Namespace defines the space within which each name must be unique. An empty namespace is\nequivalent to the \"default\" namespace, but \"default\" is the canonical representation.\nNot all objects are required to be scoped to a namespace - the value of this field for\nthose objects will be empty.\n\nMust be a DNS_LABEL.\nCannot be updated.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces\n+optional", + "type": "string" + }, + "ownerReferences": { + "description": "List of objects depended by this object. If ALL objects in the list have\nbeen deleted, this object will be garbage collected. If this object is managed by a controller,\nthen an entry in this list will point to this controller, with the controller field set to true.\nThere cannot be more than one managing controller.\n+optional\n+patchMergeKey=uid\n+patchStrategy=merge", + "type": "array", + "items": { + "$ref": "#/definitions/v1.OwnerReference" + } + }, + "resourceVersion": { + "description": "An opaque value that represents the internal version of this object that can\nbe used by clients to determine when objects have changed. May be used for optimistic\nconcurrency, change detection, and the watch operation on a resource or set of resources.\nClients must treat these values as opaque and passed unmodified back to the server.\nThey may only be valid for a particular resource or set of resources.\n\nPopulated by the system.\nRead-only.\nValue must be treated as opaque by clients and .\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency\n+optional", + "type": "string" + }, + "selfLink": { + "description": "Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.\n+optional", + "type": "string" + }, + "uid": { + "description": "UID is the unique in time and space value for this object. It is typically generated by\nthe server on successful creation of a resource and is not allowed to change on PUT\noperations.\n\nPopulated by the system.\nRead-only.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids\n+optional", + "type": "string" + } + } + }, + "v1.OwnerReference": { + "type": "object", + "properties": { + "apiVersion": { + "description": "API version of the referent.", + "type": "string" + }, + "blockOwnerDeletion": { + "description": "If true, AND if the owner has the \"foregroundDeletion\" finalizer, then\nthe owner cannot be deleted from the key-value store until this\nreference is removed.\nSee https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion\nfor how the garbage collector interacts with this field and enforces the foreground deletion.\nDefaults to false.\nTo set this field, a user needs \"delete\" permission of the owner,\notherwise 422 (Unprocessable Entity) will be returned.\n+optional", + "type": "boolean" + }, + "controller": { + "description": "If true, this reference points to the managing controller.\n+optional", + "type": "boolean" + }, + "kind": { + "description": "Kind of the referent.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "name": { + "description": "Name of the referent.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names", + "type": "string" + }, + "uid": { + "description": "UID of the referent.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", + "type": "string" + } + } + }, + "v1alpha1.ResourceRef": { + "type": "object", + "properties": { + "name": { + "type": "string" + } + } + }, + "v1alpha1.TlsConfig": { + "type": "object", + "properties": { + "autoDiscovery": { + "description": "Find secret with domain in annotation \"envoy.kaasops.io/domains\"", + "type": "boolean" + }, + "secretRef": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + } + }, + "v1alpha1.VirtualService": { + "type": "object", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object.\nServers should convert recognized schemas to the latest internal value, and\nmay reject unrecognized values.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources\n+optional", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents.\nServers may infer this from the endpoint the client submits requests to.\nCannot be updated.\nIn CamelCase.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds\n+optional", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta" + }, + "spec": { + "$ref": "#/definitions/v1alpha1.VirtualServiceSpec" + }, + "status": { + "$ref": "#/definitions/v1alpha1.VirtualServiceStatus" + } + } + }, + "v1alpha1.VirtualServiceSpec": { + "type": "object", + "properties": { + "accessLog": { + "$ref": "#/definitions/runtime.RawExtension" + }, + "accessLogConfig": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + }, + "additionalHttpFilters": { + "type": "array", + "items": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + }, + "additionalRoutes": { + "type": "array", + "items": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + }, + "httpFilters": { + "description": "HTTPFilters for use custom HTTP filters", + "type": "array", + "items": { + "$ref": "#/definitions/runtime.RawExtension" + } + }, + "listener": { + "description": "+kubebuilder:validation:Required", + "allOf": [ + { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + ] + }, + "tlsConfig": { + "$ref": "#/definitions/v1alpha1.TlsConfig" + }, + "upgradeConfigs": { + "description": "UpgradeConfigs - https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#envoy-v3-api-msg-extensions-filters-network-http-connection-manager-v3-httpconnectionmanager-upgradeconfig", + "type": "array", + "items": { + "$ref": "#/definitions/runtime.RawExtension" + } + }, + "useRemoteAddress": { + "description": "Controller HCM Extentions (https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto)\nUseRemoteAddress - use remote address for x-forwarded-for header (https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#extensions-filters-network-http-connection-manager-v3-httpconnectionmanager)", + "type": "boolean" + }, + "virtualHost": { + "$ref": "#/definitions/runtime.RawExtension" + } + } + }, + "v1alpha1.VirtualServiceStatus": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "lastAppliedHash": { + "type": "integer" + }, + "valid": { + "type": "boolean" + } + } + } + } +}` + +// SwaggerInfokube holds exported Swagger Info so clients can modify it +var SwaggerInfokube = &swag.Spec{ + Version: "", + Host: "", + BasePath: "", + Schemes: []string{}, + Title: "", + Description: "", + InfoInstanceName: "kube", + SwaggerTemplate: docTemplatekube, + LeftDelim: "{{", + RightDelim: "}}", +} + +func init() { + swag.Register(SwaggerInfokube.InstanceName(), SwaggerInfokube) +} diff --git a/docs/kubeRestAPI/kube_swagger.json b/docs/kubeRestAPI/kube_swagger.json new file mode 100644 index 00000000..0e5fb730 --- /dev/null +++ b/docs/kubeRestAPI/kube_swagger.json @@ -0,0 +1,628 @@ +{ + "swagger": "2.0", + "info": { + "contact": {} + }, + "paths": { + "/virtualservices": { + "get": { + "description": "Get names of all Virtual Services", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Get all Virtual Services", + "parameters": [ + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + }, + "put": { + "description": "Update an existing Virtual Service", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Update an existing Virtual Service", + "parameters": [ + { + "description": "Virtual Service object", + "name": "virtualservice", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + }, + "post": { + "description": "Create a new Virtual Service", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Create a new Virtual Service", + "parameters": [ + { + "description": "Virtual Service object", + "name": "virtualservice", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + }, + "/virtualservices/search": { + "get": { + "description": "Search in which Virtual Service a specific domain is described", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Search for a Virtual Service by name and nodeID", + "parameters": [ + { + "type": "string", + "description": "Virtual Service Name", + "name": "name", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Node ID", + "name": "nodeId", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + }, + "/virtualservices/wrong-state": { + "get": { + "description": "Get names of all Virtual Services that have an erroneous state", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Get all Virtual Services with erroneous state", + "parameters": [ + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + }, + "/virtualservices/{name}": { + "get": { + "description": "Get a specific Virtual Service by name", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Get a specific Virtual Service", + "parameters": [ + { + "type": "string", + "description": "Virtual Service Name", + "name": "name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1alpha1.VirtualService" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Delete a Virtual Service", + "produces": [ + "application/json" + ], + "tags": [ + "virtualservices" + ], + "summary": "Delete a Virtual Service", + "parameters": [ + { + "type": "string", + "description": "Virtual Service Name", + "name": "name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Namespace", + "name": "namespace", + "in": "query" + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/types.ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "runtime.RawExtension": { + "type": "object" + }, + "types.ErrorResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer" + }, + "message": { + "type": "string" + } + } + }, + "v1.FieldsV1": { + "type": "object" + }, + "v1.ManagedFieldsEntry": { + "type": "object", + "properties": { + "apiVersion": { + "description": "APIVersion defines the version of this resource that this field set\napplies to. The format is \"group/version\" just like the top-level\nAPIVersion field. It is necessary to track the version of a field\nset because it cannot be automatically converted.", + "type": "string" + }, + "fieldsType": { + "description": "FieldsType is the discriminator for the different fields format and version.\nThere is currently only one possible value: \"FieldsV1\"", + "type": "string" + }, + "fieldsV1": { + "description": "FieldsV1 holds the first JSON version format as described in the \"FieldsV1\" type.\n+optional", + "allOf": [ + { + "$ref": "#/definitions/v1.FieldsV1" + } + ] + }, + "manager": { + "description": "Manager is an identifier of the workflow managing these fields.", + "type": "string" + }, + "operation": { + "description": "Operation is the type of operation which lead to this ManagedFieldsEntry being created.\nThe only valid values for this field are 'Apply' and 'Update'.", + "allOf": [ + { + "$ref": "#/definitions/v1.ManagedFieldsOperationType" + } + ] + }, + "subresource": { + "description": "Subresource is the name of the subresource used to update that object, or\nempty string if the object was updated through the main resource. The\nvalue of this field is used to distinguish between managers, even if they\nshare the same name. For example, a status update will be distinct from a\nregular update using the same manager name.\nNote that the APIVersion field is not related to the Subresource field and\nit always corresponds to the version of the main resource.", + "type": "string" + }, + "time": { + "description": "Time is the timestamp of when the ManagedFields entry was added. The\ntimestamp will also be updated if a field is added, the manager\nchanges any of the owned fields value or removes a field. The\ntimestamp does not update when a field is removed from the entry\nbecause another manager took it over.\n+optional", + "type": "string" + } + } + }, + "v1.ManagedFieldsOperationType": { + "type": "string", + "enum": [ + "Apply", + "Update" + ], + "x-enum-varnames": [ + "ManagedFieldsOperationApply", + "ManagedFieldsOperationUpdate" + ] + }, + "v1.ObjectMeta": { + "type": "object", + "properties": { + "annotations": { + "description": "Annotations is an unstructured key value map stored with a resource that may be\nset by external tools to store and retrieve arbitrary metadata. They are not\nqueryable and should be preserved when modifying objects.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations\n+optional", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "creationTimestamp": { + "description": "CreationTimestamp is a timestamp representing the server time when this object was\ncreated. It is not guaranteed to be set in happens-before order across separate operations.\nClients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system.\nRead-only.\nNull for lists.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\n+optional", + "type": "string" + }, + "deletionGracePeriodSeconds": { + "description": "Number of seconds allowed for this object to gracefully terminate before\nit will be removed from the system. Only set when deletionTimestamp is also set.\nMay only be shortened.\nRead-only.\n+optional", + "type": "integer" + }, + "deletionTimestamp": { + "description": "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This\nfield is set by the server when a graceful deletion is requested by the user, and is not\ndirectly settable by a client. The resource is expected to be deleted (no longer visible\nfrom resource lists, and not reachable by name) after the time in this field, once the\nfinalizers list is empty. As long as the finalizers list contains items, deletion is blocked.\nOnce the deletionTimestamp is set, this value may not be unset or be set further into the\nfuture, although it may be shortened or the resource may be deleted prior to this time.\nFor example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react\nby sending a graceful termination signal to the containers in the pod. After that 30 seconds,\nthe Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup,\nremove the pod from the API. In the presence of network partitions, this object may still\nexist after this timestamp, until an administrator or automated process can determine the\nresource is fully terminated.\nIf not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested.\nRead-only.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\n+optional", + "type": "string" + }, + "finalizers": { + "description": "Must be empty before the object is deleted from the registry. Each entry\nis an identifier for the responsible component that will remove the entry\nfrom the list. If the deletionTimestamp of the object is non-nil, entries\nin this list can only be removed.\nFinalizers may be processed and removed in any order. Order is NOT enforced\nbecause it introduces significant risk of stuck finalizers.\nfinalizers is a shared field, any actor with permission can reorder it.\nIf the finalizer list is processed in order, then this can lead to a situation\nin which the component responsible for the first finalizer in the list is\nwaiting for a signal (field value, external system, or other) produced by a\ncomponent responsible for a finalizer later in the list, resulting in a deadlock.\nWithout enforced ordering finalizers are free to order amongst themselves and\nare not vulnerable to ordering changes in the list.\n+optional\n+patchStrategy=merge", + "type": "array", + "items": { + "type": "string" + } + }, + "generateName": { + "description": "GenerateName is an optional prefix, used by the server, to generate a unique\nname ONLY IF the Name field has not been provided.\nIf this field is used, the name returned to the client will be different\nthan the name passed. This value will also be combined with a unique suffix.\nThe provided value has the same validation rules as the Name field,\nand may be truncated by the length of the suffix required to make the value\nunique on the server.\n\nIf this field is specified and the generated name exists, the server will return a 409.\n\nApplied only if Name is not specified.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency\n+optional", + "type": "string" + }, + "generation": { + "description": "A sequence number representing a specific generation of the desired state.\nPopulated by the system. Read-only.\n+optional", + "type": "integer" + }, + "labels": { + "description": "Map of string keys and values that can be used to organize and categorize\n(scope and select) objects. May match selectors of replication controllers\nand services.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels\n+optional", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "managedFields": { + "description": "ManagedFields maps workflow-id and version to the set of fields\nthat are managed by that workflow. This is mostly for internal\nhousekeeping, and users typically shouldn't need to set or\nunderstand this field. A workflow can be the user's name, a\ncontroller's name, or the name of a specific apply path like\n\"ci-cd\". The set of fields is always in the version that the\nworkflow used when modifying the object.\n\n+optional", + "type": "array", + "items": { + "$ref": "#/definitions/v1.ManagedFieldsEntry" + } + }, + "name": { + "description": "Name must be unique within a namespace. Is required when creating resources, although\nsome resources may allow a client to request the generation of an appropriate name\nautomatically. Name is primarily intended for creation idempotence and configuration\ndefinition.\nCannot be updated.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names\n+optional", + "type": "string" + }, + "namespace": { + "description": "Namespace defines the space within which each name must be unique. An empty namespace is\nequivalent to the \"default\" namespace, but \"default\" is the canonical representation.\nNot all objects are required to be scoped to a namespace - the value of this field for\nthose objects will be empty.\n\nMust be a DNS_LABEL.\nCannot be updated.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces\n+optional", + "type": "string" + }, + "ownerReferences": { + "description": "List of objects depended by this object. If ALL objects in the list have\nbeen deleted, this object will be garbage collected. If this object is managed by a controller,\nthen an entry in this list will point to this controller, with the controller field set to true.\nThere cannot be more than one managing controller.\n+optional\n+patchMergeKey=uid\n+patchStrategy=merge", + "type": "array", + "items": { + "$ref": "#/definitions/v1.OwnerReference" + } + }, + "resourceVersion": { + "description": "An opaque value that represents the internal version of this object that can\nbe used by clients to determine when objects have changed. May be used for optimistic\nconcurrency, change detection, and the watch operation on a resource or set of resources.\nClients must treat these values as opaque and passed unmodified back to the server.\nThey may only be valid for a particular resource or set of resources.\n\nPopulated by the system.\nRead-only.\nValue must be treated as opaque by clients and .\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency\n+optional", + "type": "string" + }, + "selfLink": { + "description": "Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.\n+optional", + "type": "string" + }, + "uid": { + "description": "UID is the unique in time and space value for this object. It is typically generated by\nthe server on successful creation of a resource and is not allowed to change on PUT\noperations.\n\nPopulated by the system.\nRead-only.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids\n+optional", + "type": "string" + } + } + }, + "v1.OwnerReference": { + "type": "object", + "properties": { + "apiVersion": { + "description": "API version of the referent.", + "type": "string" + }, + "blockOwnerDeletion": { + "description": "If true, AND if the owner has the \"foregroundDeletion\" finalizer, then\nthe owner cannot be deleted from the key-value store until this\nreference is removed.\nSee https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion\nfor how the garbage collector interacts with this field and enforces the foreground deletion.\nDefaults to false.\nTo set this field, a user needs \"delete\" permission of the owner,\notherwise 422 (Unprocessable Entity) will be returned.\n+optional", + "type": "boolean" + }, + "controller": { + "description": "If true, this reference points to the managing controller.\n+optional", + "type": "boolean" + }, + "kind": { + "description": "Kind of the referent.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "name": { + "description": "Name of the referent.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names", + "type": "string" + }, + "uid": { + "description": "UID of the referent.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", + "type": "string" + } + } + }, + "v1alpha1.ResourceRef": { + "type": "object", + "properties": { + "name": { + "type": "string" + } + } + }, + "v1alpha1.TlsConfig": { + "type": "object", + "properties": { + "autoDiscovery": { + "description": "Find secret with domain in annotation \"envoy.kaasops.io/domains\"", + "type": "boolean" + }, + "secretRef": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + } + }, + "v1alpha1.VirtualService": { + "type": "object", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object.\nServers should convert recognized schemas to the latest internal value, and\nmay reject unrecognized values.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources\n+optional", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents.\nServers may infer this from the endpoint the client submits requests to.\nCannot be updated.\nIn CamelCase.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds\n+optional", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta" + }, + "spec": { + "$ref": "#/definitions/v1alpha1.VirtualServiceSpec" + }, + "status": { + "$ref": "#/definitions/v1alpha1.VirtualServiceStatus" + } + } + }, + "v1alpha1.VirtualServiceSpec": { + "type": "object", + "properties": { + "accessLog": { + "$ref": "#/definitions/runtime.RawExtension" + }, + "accessLogConfig": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + }, + "additionalHttpFilters": { + "type": "array", + "items": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + }, + "additionalRoutes": { + "type": "array", + "items": { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + }, + "httpFilters": { + "description": "HTTPFilters for use custom HTTP filters", + "type": "array", + "items": { + "$ref": "#/definitions/runtime.RawExtension" + } + }, + "listener": { + "description": "+kubebuilder:validation:Required", + "allOf": [ + { + "$ref": "#/definitions/v1alpha1.ResourceRef" + } + ] + }, + "tlsConfig": { + "$ref": "#/definitions/v1alpha1.TlsConfig" + }, + "upgradeConfigs": { + "description": "UpgradeConfigs - https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#envoy-v3-api-msg-extensions-filters-network-http-connection-manager-v3-httpconnectionmanager-upgradeconfig", + "type": "array", + "items": { + "$ref": "#/definitions/runtime.RawExtension" + } + }, + "useRemoteAddress": { + "description": "Controller HCM Extentions (https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto)\nUseRemoteAddress - use remote address for x-forwarded-for header (https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#extensions-filters-network-http-connection-manager-v3-httpconnectionmanager)", + "type": "boolean" + }, + "virtualHost": { + "$ref": "#/definitions/runtime.RawExtension" + } + } + }, + "v1alpha1.VirtualServiceStatus": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "lastAppliedHash": { + "type": "integer" + }, + "valid": { + "type": "boolean" + } + } + } + } +} \ No newline at end of file diff --git a/docs/kubeRestAPI/kube_swagger.yaml b/docs/kubeRestAPI/kube_swagger.yaml new file mode 100644 index 00000000..aa514b54 --- /dev/null +++ b/docs/kubeRestAPI/kube_swagger.yaml @@ -0,0 +1,599 @@ +definitions: + runtime.RawExtension: + type: object + types.ErrorResponse: + properties: + code: + type: integer + message: + type: string + type: object + v1.FieldsV1: + type: object + v1.ManagedFieldsEntry: + properties: + apiVersion: + description: |- + APIVersion defines the version of this resource that this field set + applies to. The format is "group/version" just like the top-level + APIVersion field. It is necessary to track the version of a field + set because it cannot be automatically converted. + type: string + fieldsType: + description: |- + FieldsType is the discriminator for the different fields format and version. + There is currently only one possible value: "FieldsV1" + type: string + fieldsV1: + allOf: + - $ref: '#/definitions/v1.FieldsV1' + description: |- + FieldsV1 holds the first JSON version format as described in the "FieldsV1" type. + +optional + manager: + description: Manager is an identifier of the workflow managing these fields. + type: string + operation: + allOf: + - $ref: '#/definitions/v1.ManagedFieldsOperationType' + description: |- + Operation is the type of operation which lead to this ManagedFieldsEntry being created. + The only valid values for this field are 'Apply' and 'Update'. + subresource: + description: |- + Subresource is the name of the subresource used to update that object, or + empty string if the object was updated through the main resource. The + value of this field is used to distinguish between managers, even if they + share the same name. For example, a status update will be distinct from a + regular update using the same manager name. + Note that the APIVersion field is not related to the Subresource field and + it always corresponds to the version of the main resource. + type: string + time: + description: |- + Time is the timestamp of when the ManagedFields entry was added. The + timestamp will also be updated if a field is added, the manager + changes any of the owned fields value or removes a field. The + timestamp does not update when a field is removed from the entry + because another manager took it over. + +optional + type: string + type: object + v1.ManagedFieldsOperationType: + enum: + - Apply + - Update + type: string + x-enum-varnames: + - ManagedFieldsOperationApply + - ManagedFieldsOperationUpdate + v1.ObjectMeta: + properties: + annotations: + additionalProperties: + type: string + description: |- + Annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations + +optional + type: object + creationTimestamp: + description: |- + CreationTimestamp is a timestamp representing the server time when this object was + created. It is not guaranteed to be set in happens-before order across separate operations. + Clients may not set this value. It is represented in RFC3339 form and is in UTC. + + Populated by the system. + Read-only. + Null for lists. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + +optional + type: string + deletionGracePeriodSeconds: + description: |- + Number of seconds allowed for this object to gracefully terminate before + it will be removed from the system. Only set when deletionTimestamp is also set. + May only be shortened. + Read-only. + +optional + type: integer + deletionTimestamp: + description: |- + DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This + field is set by the server when a graceful deletion is requested by the user, and is not + directly settable by a client. The resource is expected to be deleted (no longer visible + from resource lists, and not reachable by name) after the time in this field, once the + finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. + Once the deletionTimestamp is set, this value may not be unset or be set further into the + future, although it may be shortened or the resource may be deleted prior to this time. + For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react + by sending a graceful termination signal to the containers in the pod. After that 30 seconds, + the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, + remove the pod from the API. In the presence of network partitions, this object may still + exist after this timestamp, until an administrator or automated process can determine the + resource is fully terminated. + If not set, graceful deletion of the object has not been requested. + + Populated by the system when a graceful deletion is requested. + Read-only. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + +optional + type: string + finalizers: + description: |- + Must be empty before the object is deleted from the registry. Each entry + is an identifier for the responsible component that will remove the entry + from the list. If the deletionTimestamp of the object is non-nil, entries + in this list can only be removed. + Finalizers may be processed and removed in any order. Order is NOT enforced + because it introduces significant risk of stuck finalizers. + finalizers is a shared field, any actor with permission can reorder it. + If the finalizer list is processed in order, then this can lead to a situation + in which the component responsible for the first finalizer in the list is + waiting for a signal (field value, external system, or other) produced by a + component responsible for a finalizer later in the list, resulting in a deadlock. + Without enforced ordering finalizers are free to order amongst themselves and + are not vulnerable to ordering changes in the list. + +optional + +patchStrategy=merge + items: + type: string + type: array + generateName: + description: |- + GenerateName is an optional prefix, used by the server, to generate a unique + name ONLY IF the Name field has not been provided. + If this field is used, the name returned to the client will be different + than the name passed. This value will also be combined with a unique suffix. + The provided value has the same validation rules as the Name field, + and may be truncated by the length of the suffix required to make the value + unique on the server. + + If this field is specified and the generated name exists, the server will return a 409. + + Applied only if Name is not specified. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency + +optional + type: string + generation: + description: |- + A sequence number representing a specific generation of the desired state. + Populated by the system. Read-only. + +optional + type: integer + labels: + additionalProperties: + type: string + description: |- + Map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels + +optional + type: object + managedFields: + description: |- + ManagedFields maps workflow-id and version to the set of fields + that are managed by that workflow. This is mostly for internal + housekeeping, and users typically shouldn't need to set or + understand this field. A workflow can be the user's name, a + controller's name, or the name of a specific apply path like + "ci-cd". The set of fields is always in the version that the + workflow used when modifying the object. + + +optional + items: + $ref: '#/definitions/v1.ManagedFieldsEntry' + type: array + name: + description: |- + Name must be unique within a namespace. Is required when creating resources, although + some resources may allow a client to request the generation of an appropriate name + automatically. Name is primarily intended for creation idempotence and configuration + definition. + Cannot be updated. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names + +optional + type: string + namespace: + description: |- + Namespace defines the space within which each name must be unique. An empty namespace is + equivalent to the "default" namespace, but "default" is the canonical representation. + Not all objects are required to be scoped to a namespace - the value of this field for + those objects will be empty. + + Must be a DNS_LABEL. + Cannot be updated. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces + +optional + type: string + ownerReferences: + description: |- + List of objects depended by this object. If ALL objects in the list have + been deleted, this object will be garbage collected. If this object is managed by a controller, + then an entry in this list will point to this controller, with the controller field set to true. + There cannot be more than one managing controller. + +optional + +patchMergeKey=uid + +patchStrategy=merge + items: + $ref: '#/definitions/v1.OwnerReference' + type: array + resourceVersion: + description: |- + An opaque value that represents the internal version of this object that can + be used by clients to determine when objects have changed. May be used for optimistic + concurrency, change detection, and the watch operation on a resource or set of resources. + Clients must treat these values as opaque and passed unmodified back to the server. + They may only be valid for a particular resource or set of resources. + + Populated by the system. + Read-only. + Value must be treated as opaque by clients and . + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency + +optional + type: string + selfLink: + description: |- + Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. + +optional + type: string + uid: + description: |- + UID is the unique in time and space value for this object. It is typically generated by + the server on successful creation of a resource and is not allowed to change on PUT + operations. + + Populated by the system. + Read-only. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids + +optional + type: string + type: object + v1.OwnerReference: + properties: + apiVersion: + description: API version of the referent. + type: string + blockOwnerDeletion: + description: |- + If true, AND if the owner has the "foregroundDeletion" finalizer, then + the owner cannot be deleted from the key-value store until this + reference is removed. + See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion + for how the garbage collector interacts with this field and enforces the foreground deletion. + Defaults to false. + To set this field, a user needs "delete" permission of the owner, + otherwise 422 (Unprocessable Entity) will be returned. + +optional + type: boolean + controller: + description: |- + If true, this reference points to the managing controller. + +optional + type: boolean + kind: + description: |- + Kind of the referent. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + name: + description: |- + Name of the referent. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names + type: string + uid: + description: |- + UID of the referent. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids + type: string + type: object + v1alpha1.ResourceRef: + properties: + name: + type: string + type: object + v1alpha1.TlsConfig: + properties: + autoDiscovery: + description: Find secret with domain in annotation "envoy.kaasops.io/domains" + type: boolean + secretRef: + $ref: '#/definitions/v1alpha1.ResourceRef' + type: object + v1alpha1.VirtualService: + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + +optional + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + +optional + type: string + metadata: + $ref: '#/definitions/v1.ObjectMeta' + spec: + $ref: '#/definitions/v1alpha1.VirtualServiceSpec' + status: + $ref: '#/definitions/v1alpha1.VirtualServiceStatus' + type: object + v1alpha1.VirtualServiceSpec: + properties: + accessLog: + $ref: '#/definitions/runtime.RawExtension' + accessLogConfig: + $ref: '#/definitions/v1alpha1.ResourceRef' + additionalHttpFilters: + items: + $ref: '#/definitions/v1alpha1.ResourceRef' + type: array + additionalRoutes: + items: + $ref: '#/definitions/v1alpha1.ResourceRef' + type: array + httpFilters: + description: HTTPFilters for use custom HTTP filters + items: + $ref: '#/definitions/runtime.RawExtension' + type: array + listener: + allOf: + - $ref: '#/definitions/v1alpha1.ResourceRef' + description: +kubebuilder:validation:Required + tlsConfig: + $ref: '#/definitions/v1alpha1.TlsConfig' + upgradeConfigs: + description: UpgradeConfigs - https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#envoy-v3-api-msg-extensions-filters-network-http-connection-manager-v3-httpconnectionmanager-upgradeconfig + items: + $ref: '#/definitions/runtime.RawExtension' + type: array + useRemoteAddress: + description: |- + Controller HCM Extentions (https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto) + UseRemoteAddress - use remote address for x-forwarded-for header (https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#extensions-filters-network-http-connection-manager-v3-httpconnectionmanager) + type: boolean + virtualHost: + $ref: '#/definitions/runtime.RawExtension' + type: object + v1alpha1.VirtualServiceStatus: + properties: + error: + type: string + lastAppliedHash: + type: integer + valid: + type: boolean + type: object +info: + contact: {} +paths: + /virtualservices: + get: + description: Get names of all Virtual Services + parameters: + - description: Namespace + in: query + name: namespace + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + type: string + type: array + "400": + description: Bad Request + schema: + $ref: '#/definitions/types.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/types.ErrorResponse' + summary: Get all Virtual Services + tags: + - virtualservices + post: + consumes: + - application/json + description: Create a new Virtual Service + parameters: + - description: Virtual Service object + in: body + name: virtualservice + required: true + schema: + $ref: '#/definitions/v1alpha1.VirtualService' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/v1alpha1.VirtualService' + "400": + description: Bad Request + schema: + $ref: '#/definitions/types.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/types.ErrorResponse' + summary: Create a new Virtual Service + tags: + - virtualservices + put: + consumes: + - application/json + description: Update an existing Virtual Service + parameters: + - description: Virtual Service object + in: body + name: virtualservice + required: true + schema: + $ref: '#/definitions/v1alpha1.VirtualService' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/v1alpha1.VirtualService' + "400": + description: Bad Request + schema: + $ref: '#/definitions/types.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/types.ErrorResponse' + summary: Update an existing Virtual Service + tags: + - virtualservices + /virtualservices/{name}: + delete: + description: Delete a Virtual Service + parameters: + - description: Virtual Service Name + in: path + name: name + required: true + type: string + - description: Namespace + in: query + name: namespace + type: string + produces: + - application/json + responses: + "204": + description: No Content + "400": + description: Bad Request + schema: + $ref: '#/definitions/types.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/types.ErrorResponse' + summary: Delete a Virtual Service + tags: + - virtualservices + get: + description: Get a specific Virtual Service by name + parameters: + - description: Virtual Service Name + in: path + name: name + required: true + type: string + - description: Namespace + in: query + name: namespace + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/v1alpha1.VirtualService' + "400": + description: Bad Request + schema: + $ref: '#/definitions/types.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/types.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/types.ErrorResponse' + summary: Get a specific Virtual Service + tags: + - virtualservices + /virtualservices/search: + get: + description: Search in which Virtual Service a specific domain is described + parameters: + - description: Virtual Service Name + in: query + name: name + required: true + type: string + - description: Node ID + in: query + name: nodeId + required: true + type: string + - description: Namespace + in: query + name: namespace + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/v1alpha1.VirtualService' + "400": + description: Bad Request + schema: + $ref: '#/definitions/types.ErrorResponse' + "404": + description: Not Found + schema: + $ref: '#/definitions/types.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/types.ErrorResponse' + summary: Search for a Virtual Service by name and nodeID + tags: + - virtualservices + /virtualservices/wrong-state: + get: + description: Get names of all Virtual Services that have an erroneous state + parameters: + - description: Namespace + in: query + name: namespace + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + type: string + type: array + "400": + description: Bad Request + schema: + $ref: '#/definitions/types.ErrorResponse' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/types.ErrorResponse' + summary: Get all Virtual Services with erroneous state + tags: + - virtualservices +swagger: "2.0" diff --git a/main.go b/main.go index b830f9ae..d1da21e7 100644 --- a/main.go +++ b/main.go @@ -19,6 +19,7 @@ package main import ( "context" "flag" + "github.com/kaasops/envoy-xds-controller/pkg/kube/api" "os" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) @@ -79,6 +80,10 @@ func main() { var cacheAPIPort int var cacheAPIScheme string var cacheAPIAddr string + var enableKubeAPI bool + var kubeAPIScheme string + var kubeAPIPort int + var kubeAPIAddr string flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") flag.BoolVar(&enableLeaderElection, "leader-elect", false, @@ -88,6 +93,10 @@ func main() { flag.IntVar(&cacheAPIPort, "cache-api-port", 9999, "Cache API port") flag.StringVar(&cacheAPIScheme, "cache-api-scheme", "http", "Cache API scheme") flag.StringVar(&cacheAPIAddr, "cache-api-addr", "localhost:9999", "Cache API address") + flag.BoolVar(&enableKubeAPI, "enable-kube-api", true, "Enable Kube API, for debug") + flag.IntVar(&kubeAPIPort, "kube-api-port", 9998, "Kube API port") + flag.StringVar(&kubeAPIScheme, "kube-api-scheme", "http", "Kube API scheme") + flag.StringVar(&kubeAPIAddr, "kube-api-addr", "localhost:9998", "Kube API address") cfg, err := config.New() if err != nil { @@ -210,6 +219,16 @@ func main() { }() } + if enableKubeAPI { + go func() { + c := mgr.GetClient() + if err := api.NewServer(&c, cfg).Run(kubeAPIPort, kubeAPIScheme, kubeAPIAddr); err != nil { + setupLog.Error(err, "cannot run http kube server") + os.Exit(1) + } + }() + } + if err = (&controllers.ClusterReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), diff --git a/pkg/kube/api/main.go b/pkg/kube/api/main.go new file mode 100644 index 00000000..eef943dc --- /dev/null +++ b/pkg/kube/api/main.go @@ -0,0 +1,50 @@ +package api + +import ( + "fmt" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + _ "github.com/kaasops/envoy-xds-controller/docs/kubeRestAPI" + "github.com/kaasops/envoy-xds-controller/pkg/config" + v1 "github.com/kaasops/envoy-xds-controller/pkg/kube/api/v1" + swaggerFiles "github.com/swaggo/files" + ginSwagger "github.com/swaggo/gin-swagger" + "sigs.k8s.io/controller-runtime/pkg/client" + + "log" + "time" +) + +type Server struct { + Client *client.Client + Config *config.Config +} + +func NewServer(Client *client.Client, config *config.Config) *Server { + return &Server{Client: Client, Config: config} +} + +func (s *Server) Run(port int, scheme, addr string) error { + server := gin.Default() + // CORS configuration + server.Use(cors.New(cors.Config{ + AllowOrigins: []string{"*"}, + AllowMethods: []string{"GET"}, + AllowHeaders: []string{"*"}, + AllowCredentials: true, + MaxAge: 12 * time.Hour, + })) + + apiV1 := server.Group("/api/v1") + v1.RegisterRoutes(apiV1, s.Client, s.Config) + server.Static("/docs", "./docs") + + kubeAPIUrl := ginSwagger.URL(fmt.Sprintf("%v://%v/docs/kubeRestAPI/kube_swagger.json", scheme, addr)) + server.GET("/swagger/kube/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, kubeAPIUrl, ginSwagger.InstanceName("kubeSwagger"))) + + if err := server.Run(fmt.Sprintf(":%d", port)); err != nil { + log.Fatalf("Failed to run server: %v", err) + } + + return nil +} diff --git a/pkg/kube/api/v1/handlers/virtualservices.go b/pkg/kube/api/v1/handlers/virtualservices.go new file mode 100644 index 00000000..6570827f --- /dev/null +++ b/pkg/kube/api/v1/handlers/virtualservices.go @@ -0,0 +1,276 @@ +package handlers + +import ( + "fmt" + "github.com/kaasops/envoy-xds-controller/api/v1alpha1" + "github.com/kaasops/envoy-xds-controller/pkg/config" + "github.com/kaasops/envoy-xds-controller/pkg/kube/api/v1/types" + _ "k8s.io/apimachinery/pkg/apis/meta/v1" + "net/http" + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/gin-gonic/gin" +) + +type VirtualServiceHandler struct { + Client client.Client + Config *config.Config +} + +func NewVirtualServiceHandler(client client.Client, config *config.Config) *VirtualServiceHandler { + return &VirtualServiceHandler{Client: client, Config: config} +} + +// GetAllVirtualServices gets the names of all Virtual Services. +// @Summary Get all Virtual Services +// @Description Get names of all Virtual Services +// @Tags virtualservices +// @Produce json +// @Param namespace query string false "Namespace" +// @Success 200 {array} string +// @Failure 400 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Router /virtualservices [get] +func (h *VirtualServiceHandler) GetAllVirtualServices(c *gin.Context) { + namespace, err := h.getNamespace(c) + if err != nil { + respondWithError(c, http.StatusBadRequest, err.Error()) + return + } + + vs := v1alpha1.VirtualService{} + names, err := vs.GetAll(c, namespace, h.Client) + if err != nil { + respondWithError(c, http.StatusInternalServerError, err.Error()) + return + } + c.JSON(http.StatusOK, names) +} + +// GetAllVirtualServicesWithWrongState gets the names of all Virtual Services with an erroneous state. +// @Summary Get all Virtual Services with erroneous state +// @Description Get names of all Virtual Services that have an erroneous state +// @Tags virtualservices +// @Produce json +// @Param namespace query string false "Namespace" +// @Success 200 {array} string +// @Failure 400 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Router /virtualservices/wrong-state [get] +func (h *VirtualServiceHandler) GetAllVirtualServicesWithWrongState(c *gin.Context) { + namespace, err := h.getNamespace(c) + if err != nil { + respondWithError(c, http.StatusBadRequest, err.Error()) + return + } + + vs := v1alpha1.VirtualService{} + names, err := vs.GetAllWithWrongState(c, namespace, h.Client) + if err != nil { + respondWithError(c, http.StatusInternalServerError, err.Error()) + return + } + c.JSON(http.StatusOK, names) +} + +// GetVirtualService gets a specific Virtual Service by name. +// @Summary Get a specific Virtual Service +// @Description Get a specific Virtual Service by name +// @Tags virtualservices +// @Produce json +// @Param name path string true "Virtual Service Name" +// @Param namespace query string false "Namespace" +// @Success 200 {object} v1alpha1.VirtualService +// @Failure 400 {object} types.ErrorResponse +// @Failure 404 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Router /virtualservices/{name} [get] +func (h *VirtualServiceHandler) GetVirtualService(c *gin.Context) { + name := c.Param("name") + if name == "" { + respondWithError(c, http.StatusBadRequest, "Name is required") + return + } + + namespace, err := h.getNamespace(c) + if err != nil { + respondWithError(c, http.StatusBadRequest, err.Error()) + return + } + + vs := v1alpha1.VirtualService{} + item, err := vs.Get(c, name, namespace, h.Client) + if err != nil { + respondWithError(c, http.StatusInternalServerError, err.Error()) + return + } + c.JSON(http.StatusOK, item) +} + +// GetVirtualServiceByNameAndNodeId searches for a Virtual Service by name and nodeID. +// @Summary Search for a Virtual Service by name and nodeID +// @Description Search in which Virtual Service a specific domain is described +// @Tags virtualservices +// @Produce json +// @Param name query string true "Virtual Service Name" +// @Param nodeId query string true "Node ID" +// @Param namespace query string false "Namespace" +// @Success 200 {object} v1alpha1.VirtualService +// @Failure 400 {object} types.ErrorResponse +// @Failure 404 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Router /virtualservices/search [get] +func (h *VirtualServiceHandler) GetVirtualServiceByNameAndNodeId(c *gin.Context) { + name := c.Query("name") + nodeId := c.Query("nodeId") + + if name == "" || nodeId == "" { + respondWithError(c, http.StatusBadRequest, "Name and nodeId are required") + return + } + + namespace, err := h.getNamespace(c) + if err != nil { + respondWithError(c, http.StatusBadRequest, err.Error()) + return + } + vs := v1alpha1.VirtualService{} + item, err := vs.GetByNameAndNodeId(c, name, nodeId, namespace, h.Client) + if err != nil { + respondWithError(c, http.StatusInternalServerError, err.Error()) + return + } + c.JSON(http.StatusOK, item) +} + +// CreateVirtualService creates a new Virtual Service. +// @Summary Create a new Virtual Service +// @Description Create a new Virtual Service +// @Tags virtualservices +// @Accept json +// @Produce json +// @Param virtualservice body v1alpha1.VirtualService true "Virtual Service object" +// @Success 201 {object} v1alpha1.VirtualService +// @Failure 400 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Router /virtualservices [post] +func (h *VirtualServiceHandler) CreateVirtualService(c *gin.Context) { + var vs v1alpha1.VirtualService + if err := c.ShouldBindJSON(&vs); err != nil { + respondWithError(c, http.StatusBadRequest, err.Error()) + return + } + + // Ensure the name is provided + if vs.Name == "" { + respondWithError(c, http.StatusBadRequest, "Name is required") + return + } + + if vs.Namespace == "" { + if h.Config.WatchNamespace != "" { + vs.Namespace = h.Config.WatchNamespace + } else { + respondWithError(c, http.StatusBadRequest, "Namespace is required") + return + } + } + + s := v1alpha1.VirtualService{} + if err := s.CreateVirtualService(c, &vs, h.Client); err != nil { + respondWithError(c, http.StatusInternalServerError, err.Error()) + return + } + c.JSON(http.StatusCreated, vs) +} + +// UpdateVirtualService updates an existing Virtual Service. +// @Summary Update an existing Virtual Service +// @Description Update an existing Virtual Service +// @Tags virtualservices +// @Accept json +// @Produce json +// @Param virtualservice body v1alpha1.VirtualService true "Virtual Service object" +// @Success 200 {object} v1alpha1.VirtualService +// @Failure 400 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Router /virtualservices [put] +func (h *VirtualServiceHandler) UpdateVirtualService(c *gin.Context) { + var vs v1alpha1.VirtualService + if err := c.ShouldBindJSON(&vs); err != nil { + respondWithError(c, http.StatusBadRequest, err.Error()) + return + } + // Ensure the name is provided + if vs.Name == "" { + respondWithError(c, http.StatusBadRequest, "Name is required") + return + } + + // Default to "default" namespace if not provided + if vs.Namespace == "" { + if h.Config.WatchNamespace != "" { + vs.Namespace = h.Config.WatchNamespace + } else { + respondWithError(c, http.StatusBadRequest, "Namespace is required") + return + } + } + + s := v1alpha1.VirtualService{} + if err := s.UpdateVirtualService(c, &vs, h.Client); err != nil { + respondWithError(c, http.StatusInternalServerError, err.Error()) + return + } + c.JSON(http.StatusOK, vs) +} + +// DeleteVirtualService deletes a Virtual Service. +// @Summary Delete a Virtual Service +// @Description Delete a Virtual Service +// @Tags virtualservices +// @Produce json +// @Param name path string true "Virtual Service Name" +// @Param namespace query string false "Namespace" +// @Success 204 +// @Failure 400 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Router /virtualservices/{name} [delete] +func (h *VirtualServiceHandler) DeleteVirtualService(c *gin.Context) { + name := c.Param("name") + if name == "" { + respondWithError(c, http.StatusBadRequest, "Name is required") + return + } + + namespace, err := h.getNamespace(c) + if err != nil { + respondWithError(c, http.StatusBadRequest, err.Error()) + return + } + + s := v1alpha1.VirtualService{} + if err := s.DeleteVirtualService(c, name, namespace, h.Client); err != nil { + respondWithError(c, http.StatusInternalServerError, err.Error()) + return + } + c.Status(http.StatusNoContent) +} + +func (h *VirtualServiceHandler) getNamespace(c *gin.Context) (string, error) { + namespace := c.Query("namespace") + if namespace == "" && h.Config.WatchNamespace == "" { + return "", fmt.Errorf("namespace is required") + } + if namespace == "" { + namespace = h.Config.WatchNamespace + } + return namespace, nil +} + +func respondWithError(c *gin.Context, code int, message string) { + c.JSON(code, types.ErrorResponse{ + Code: code, + Message: message, + }) +} diff --git a/pkg/kube/api/v1/router.go b/pkg/kube/api/v1/router.go new file mode 100644 index 00000000..aef4cb04 --- /dev/null +++ b/pkg/kube/api/v1/router.go @@ -0,0 +1,20 @@ +package v1 + +import ( + "github.com/gin-gonic/gin" + "github.com/kaasops/envoy-xds-controller/pkg/config" + "github.com/kaasops/envoy-xds-controller/pkg/kube/api/v1/handlers" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func RegisterRoutes(router *gin.RouterGroup, client *client.Client, cfg *config.Config) { + handler := handlers.NewVirtualServiceHandler(*client, cfg) + + router.GET("/virtualservices", handler.GetAllVirtualServices) + router.GET("/virtualservices/wrong-state", handler.GetAllVirtualServicesWithWrongState) + router.GET("/virtualservices/:name", handler.GetVirtualService) + router.GET("/virtualservices/search", handler.GetVirtualServiceByNameAndNodeId) + router.POST("/virtualservices", handler.CreateVirtualService) + router.PUT("/virtualservices", handler.UpdateVirtualService) + router.DELETE("/virtualservices/:name", handler.DeleteVirtualService) +} diff --git a/pkg/kube/api/v1/types/response.go b/pkg/kube/api/v1/types/response.go new file mode 100644 index 00000000..88d9303c --- /dev/null +++ b/pkg/kube/api/v1/types/response.go @@ -0,0 +1,6 @@ +package types + +type ErrorResponse struct { + Code int `json:"code"` + Message string `json:"message"` +} diff --git a/tools/make/common.mk b/tools/make/common.mk index 0a7f11e5..c84643f2 100644 --- a/tools/make/common.mk +++ b/tools/make/common.mk @@ -62,6 +62,7 @@ include tools/make/image.mk include tools/make/kind.mk include tools/make/kube.mk include tools/make/tests.mk +include tools/make/swagger.mk include tools/make/helm.mk include tools/make/tools.mk diff --git a/tools/make/swagger.mk b/tools/make/swagger.mk new file mode 100644 index 00000000..df31439e --- /dev/null +++ b/tools/make/swagger.mk @@ -0,0 +1,5 @@ +# This is a wrapper to generate swagger documentation + +.PHONY: swagger-kube +swagger-kube: + swag init -o ./docs/kubeRestAPI --instanceName kube --exclude ./pkg/xds/api --parseDependency \ No newline at end of file