diff --git a/pkg/kube_resource/generator/testdata/all_of_pattern/crd.golden.yaml b/pkg/kube_resource/generator/testdata/all_of_pattern/crd.golden.yaml new file mode 100644 index 0000000..796f82e --- /dev/null +++ b/pkg/kube_resource/generator/testdata/all_of_pattern/crd.golden.yaml @@ -0,0 +1,425 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + creationTimestamp: null + name: ec2nodeclasses.karpenter.k8s.aws +spec: + group: karpenter.k8s.aws + names: + categories: + - karpenter + kind: EC2NodeClass + listKind: EC2NodeClassList + plural: ec2nodeclasses + shortNames: + - ec2nc + - ec2ncs + singular: ec2nodeclass + scope: Cluster + versions: + - name: v1beta1 + schema: + openAPIV3Schema: + description: EC2NodeClass is the Schema for the EC2NodeClass API + 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' + 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' + type: string + metadata: + type: object + spec: + description: EC2NodeClassSpec is the top level specification for the AWS + Karpenter Provider. This will contain configuration necessary to launch + instances in AWS. + properties: + amiFamily: + description: AMIFamily is the AMI family that instances use. + enum: + - AL2 + - Bottlerocket + - Ubuntu + - Custom + - Windows2019 + - Windows2022 + type: string + amiSelectorTerms: + description: AMISelectorTerms is a list of or ami selector terms. + The terms are ORed. + items: + description: AMISelectorTerm defines selection logic for an ami + used by Karpenter to launch nodes. If multiple fields are used + for selection, the requirements are ANDed. + properties: + id: + description: ID is the ami id in EC2 + pattern: ami-[0-9a-z]+ + type: string + name: + description: Name is the ami name in EC2. This value is the + name field, which is different from the name tag. + type: string + owner: + description: Owner is the owner for the ami. You can specify + a combination of AWS account IDs, "self", "amazon", and "aws-marketplace" + type: string + tags: + additionalProperties: + type: string + description: Tags is a map of key/value tags used to select + subnets Specifying '*' for a value selects all values for + a given tag key. + maxProperties: 20 + type: object + type: object + maxItems: 30 + type: array + blockDeviceMappings: + description: BlockDeviceMappings to be applied to provisioned nodes. + items: + properties: + deviceName: + description: The device name (for example, /dev/sdh or xvdh). + type: string + ebs: + description: EBS contains parameters used to automatically set + up EBS volumes when an instance is launched. + properties: + deleteOnTermination: + description: DeleteOnTermination indicates whether the EBS + volume is deleted on instance termination. + type: boolean + encrypted: + description: Encrypted indicates whether the EBS volume + is encrypted. Encrypted volumes can only be attached to + instances that support Amazon EBS encryption. If you are + creating a volume from a snapshot, you can't specify an + encryption value. + type: boolean + iops: + description: "IOPS is the number of I/O operations per second + (IOPS). For gp3, io1, and io2 volumes, this represents + the number of IOPS that are provisioned for the volume. + For gp2 volumes, this represents the baseline performance + of the volume and the rate at which the volume accumulates + I/O credits for bursting. \n The following are the supported + values for each volume type: \n * gp3: 3,000-16,000 IOPS + \n * io1: 100-64,000 IOPS \n * io2: 100-64,000 IOPS \n + For io1 and io2 volumes, we guarantee 64,000 IOPS only + for Instances built on the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + Other instance families guarantee performance up to 32,000 + IOPS. \n This parameter is supported for io1, io2, and + gp3 volumes only. This parameter is not supported for + gp2, st1, sc1, or standard volumes." + format: int64 + type: integer + kmsKeyID: + description: KMSKeyID (ARN) of the symmetric Key Management + Service (KMS) CMK used for encryption. + type: string + snapshotID: + description: SnapshotID is the ID of an EBS snapshot + type: string + throughput: + description: 'Throughput to provision for a gp3 volume, + with a maximum of 1,000 MiB/s. Valid Range: Minimum value + of 125. Maximum value of 1000.' + format: int64 + type: integer + volumeSize: + allOf: + - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + - pattern: ^((?:[1-9][0-9]{0,3}|[1-4][0-9]{4}|[5][0-8][0-9]{3}|59000)Gi|(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|[6][0-3][0-9]{3}|64000)G|([1-9]||[1-5][0-7]|58)Ti|([1-9]||[1-5][0-9]|6[0-3]|64)T)$ + anyOf: + - type: integer + - type: string + description: "VolumeSize in `Gi`, `G`, `Ti`, or `T`. You + must specify either a snapshot ID or a volume size. The + following are the supported volumes sizes for each volume + type: \n * gp2 and gp3: 1-16,384 \n * io1 and io2: 4-16,384 + \n * st1 and sc1: 125-16,384 \n * standard: 1-1,024" + x-kubernetes-int-or-string: true + volumeType: + description: VolumeType of the block device. For more information, + see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) + in the Amazon Elastic Compute Cloud User Guide. + enum: + - standard + - io1 + - io2 + - gp2 + - sc1 + - st1 + - gp3 + type: string + type: object + rootVolume: + description: RootVolume is a flag indicating if this device + is mounted as kubelet root dir. You can configure at most + one root volume in BlockDeviceMappings. + type: boolean + type: object + maxItems: 50 + type: array + context: + description: Context is a Reserved field in EC2 APIs https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet.html + type: string + detailedMonitoring: + description: DetailedMonitoring controls if detailed monitoring is + enabled for instances that are launched + type: boolean + metadataOptions: + default: + httpEndpoint: enabled + httpProtocolIPv6: disabled + httpPutResponseHopLimit: 2 + httpTokens: required + description: "MetadataOptions for the generated launch template of + provisioned nodes. \n This specifies the exposure of the Instance + Metadata Service to provisioned EC2 nodes. For more information, + see Instance Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) + in the Amazon Elastic Compute Cloud User Guide. \n Refer to recommended, + security best practices (https://aws.github.io/aws-eks-best-practices/security/docs/iam/#restrict-access-to-the-instance-profile-assigned-to-the-worker-node) + for limiting exposure of Instance Metadata and User Data to pods. + If omitted, defaults to httpEndpoint enabled, with httpProtocolIPv6 + disabled, with httpPutResponseLimit of 2, and with httpTokens required." + properties: + httpEndpoint: + default: enabled + description: "HTTPEndpoint enables or disables the HTTP metadata + endpoint on provisioned nodes. If metadata options is non-nil, + but this parameter is not specified, the default state is \"enabled\". + \n If you specify a value of \"disabled\", instance metadata + will not be accessible on the node." + enum: + - enabled + - disabled + type: string + httpProtocolIPv6: + default: disabled + description: HTTPProtocolIPv6 enables or disables the IPv6 endpoint + for the instance metadata service on provisioned nodes. If metadata + options is non-nil, but this parameter is not specified, the + default state is "disabled". + enum: + - enabled + - disabled + type: string + httpPutResponseHopLimit: + default: 2 + description: HTTPPutResponseHopLimit is the desired HTTP PUT response + hop limit for instance metadata requests. The larger the number, + the further instance metadata requests can travel. Possible + values are integers from 1 to 64. If metadata options is non-nil, + but this parameter is not specified, the default value is 2. + format: int64 + maximum: 64 + minimum: 1 + type: integer + httpTokens: + default: required + description: "HTTPTokens determines the state of token usage for + instance metadata requests. If metadata options is non-nil, + but this parameter is not specified, the default state is \"required\". + \n If the state is optional, one can choose to retrieve instance + metadata with or without a signed token header on the request. + If one retrieves the IAM role credentials without a token, the + version 1.0 role credentials are returned. If one retrieves + the IAM role credentials using a valid signed token, the version + 2.0 role credentials are returned. \n If the state is \"required\", + one must send a signed token header with any instance metadata + retrieval requests. In this state, retrieving the IAM role credentials + always returns the version 2.0 credentials; the version 1.0 + credentials are not available." + enum: + - required + - optional + type: string + type: object + role: + description: Role is the AWS identity that nodes use. This field is + immutable. Marking this field as immutable avoids concerns around + terminating managed instance profiles from running instances. This + field may be made mutable in the future, assuming the correct garbage + collection and drift handling is implemented for the old instance + profiles on an update. + type: string + securityGroupSelectorTerms: + description: SecurityGroupSelectorTerms is a list of or security group + selector terms. The terms are ORed. + items: + description: SecurityGroupSelectorTerm defines selection logic for + a security group used by Karpenter to launch nodes. If multiple + fields are used for selection, the requirements are ANDed. + properties: + id: + description: ID is the security group id in EC2 + pattern: sg-[0-9a-z]+ + type: string + name: + description: Name is the security group name in EC2. This value + is the name field, which is different from the name tag. + type: string + tags: + additionalProperties: + type: string + description: Tags is a map of key/value tags used to select + subnets Specifying '*' for a value selects all values for + a given tag key. + maxProperties: 20 + type: object + type: object + maxItems: 30 + type: array + subnetSelectorTerms: + description: SubnetSelectorTerms is a list of or subnet selector terms. + The terms are ORed. + items: + description: SubnetSelectorTerm defines selection logic for a subnet + used by Karpenter to launch nodes. If multiple fields are used + for selection, the requirements are ANDed. + properties: + id: + description: ID is the subnet id in EC2 + pattern: subnet-[0-9a-z]+ + type: string + tags: + additionalProperties: + type: string + description: Tags is a map of key/value tags used to select + subnets Specifying '*' for a value selects all values for + a given tag key. + maxProperties: 20 + type: object + type: object + maxItems: 30 + type: array + tags: + additionalProperties: + type: string + description: Tags to be applied on ec2 resources like instances and + launch templates. + type: object + userData: + description: UserData to be applied to the provisioned nodes. It must + be in the appropriate format based on the AMIFamily in use. Karpenter + will merge certain fields into this UserData to ensure nodes are + being provisioned with the correct configuration. + type: string + required: + - amiFamily + - role + - securityGroupSelectorTerms + - subnetSelectorTerms + type: object + status: + description: EC2NodeClassStatus contains the resolved state of the EC2NodeClass + properties: + amis: + description: AMI contains the current AMI values that are available + to the cluster under the AMI selectors. + items: + description: AMI contains resolved AMI selector values utilized + for node launch + properties: + id: + description: ID of the AMI + type: string + name: + description: Name of the AMI + type: string + requirements: + description: Requirements of the AMI to be utilized on an instance + type + items: + description: A node selector requirement is a selector that + contains values, a key, and an operator that relates the + key and values. + properties: + key: + description: The label key that the selector applies to. + type: string + operator: + description: Represents a key's relationship to a set + of values. Valid operators are In, NotIn, Exists, DoesNotExist. + Gt, and Lt. + type: string + values: + description: An array of string values. If the operator + is In or NotIn, the values array must be non-empty. + If the operator is Exists or DoesNotExist, the values + array must be empty. If the operator is Gt or Lt, the + values array must have a single element, which will + be interpreted as an integer. This array is replaced + during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + required: + - id + - requirements + type: object + type: array + instanceProfile: + description: InstanceProfile contains the resolved instance profile + for the role + type: string + securityGroups: + description: SecurityGroups contains the current Security Groups values + that are available to the cluster under the SecurityGroups selectors. + items: + description: SecurityGroup contains resolved SecurityGroup selector + values utilized for node launch + properties: + id: + description: ID of the security group + type: string + name: + description: Name of the security group + type: string + required: + - id + type: object + type: array + subnets: + description: Subnets contains the current Subnet values that are available + to the cluster under the subnet selectors. + items: + description: Subnet contains resolved Subnet selector values utilized + for node launch + properties: + id: + description: ID of the subnet + type: string + zone: + description: The associated availability zone + type: string + required: + - id + - zone + type: object + type: array + type: object + type: object + served: true + storage: true + subresources: + status: {} +status: + acceptedNames: + kind: "" + plural: "" + conditions: null + storedVersions: + - v1beta1 diff --git a/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/managed_fields_entry.k b/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/managed_fields_entry.k new file mode 100644 index 0000000..8d20935 --- /dev/null +++ b/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/managed_fields_entry.k @@ -0,0 +1,41 @@ +""" +This is the managed_fields_entry module in k8s.apimachinery.pkg.apis.meta.v1 package. +This file was generated by the KCL auto-gen tool. DO NOT EDIT. +Editing this file might prove futile when you re-run the KCL auto-gen generate command. +""" + + +schema ManagedFieldsEntry: + """ + ManagedFieldsEntry is a workflow-id, a FieldSet and the group version of the resource that the fieldset applies to. + + Attributes + ---------- + apiVersion : str, default is Undefined, optional + 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. + fieldsType : str, default is Undefined, optional + FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: "FieldsV1" + fieldsV1 : any, default is Undefined, optional + FieldsV1 holds the first JSON version format as described in the "FieldsV1" type. + manager : str, default is Undefined, optional + Manager is an identifier of the workflow managing these fields. + operation : str, default is Undefined, optional + Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. + time : str, default is Undefined, optional + Time is timestamp of when these fields were set. It should always be empty if Operation is 'Apply' + """ + + + apiVersion?: str + + fieldsType?: str + + fieldsV1?: any + + manager?: str + + operation?: str + + time?: str + + diff --git a/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/object_meta.k b/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/object_meta.k new file mode 100644 index 0000000..c84b5e3 --- /dev/null +++ b/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/object_meta.k @@ -0,0 +1,97 @@ +""" +This is the object_meta module in k8s.apimachinery.pkg.apis.meta.v1 package. +This file was generated by the KCL auto-gen tool. DO NOT EDIT. +Editing this file might prove futile when you re-run the KCL auto-gen generate command. +""" + + +schema ObjectMeta: + """ + ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create. + + Attributes + ---------- + annotations : {str:str}, default is Undefined, optional + 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: http://kubernetes.io/docs/user-guide/annotations + clusterName : str, default is Undefined, optional + The name of the cluster which the object belongs to. This is used to distinguish resources with same name and namespace in different clusters. This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request. + creationTimestamp : str, default is Undefined, optional + 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 + deletionGracePeriodSeconds : int, default is Undefined, optional + 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. + deletionTimestamp : str, default is Undefined, optional + 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 + finalizers : [str], default is Undefined, optional + 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. + generateName : str, default is Undefined, optional + 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 NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header). + + Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency + generation : int, default is Undefined, optional + A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. + labels : {str:str}, default is Undefined, optional + 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: http://kubernetes.io/docs/user-guide/labels + managedFields : [ManagedFieldsEntry], default is Undefined, optional + 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. + name : str, default is Undefined, optional + 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: http://kubernetes.io/docs/user-guide/identifiers#names + namespace : str, default is Undefined, optional + Namespace defines the space within 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: http://kubernetes.io/docs/user-guide/namespaces + ownerReferences : [OwnerReference], default is Undefined, optional + 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. + resourceVersion : str, default is Undefined, optional + 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 + selfLink : str, default is Undefined, optional + SelfLink is a URL representing this object. Populated by the system. Read-only. + + DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release. + uid : str, default is Undefined, optional + 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: http://kubernetes.io/docs/user-guide/identifiers#uids + """ + + + annotations?: {str:str} + + clusterName?: str + + creationTimestamp?: str + + deletionGracePeriodSeconds?: int + + deletionTimestamp?: str + + finalizers?: [str] + + generateName?: str + + generation?: int + + labels?: {str:str} + + managedFields?: [ManagedFieldsEntry] + + name?: str + + namespace?: str + + ownerReferences?: [OwnerReference] + + resourceVersion?: str + + selfLink?: str + + uid?: str + + diff --git a/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/owner_reference.k b/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/owner_reference.k new file mode 100644 index 0000000..8d4037b --- /dev/null +++ b/pkg/kube_resource/generator/testdata/all_of_pattern/models/k8s/apimachinery/pkg/apis/meta/v1/owner_reference.k @@ -0,0 +1,41 @@ +""" +This is the owner_reference module in k8s.apimachinery.pkg.apis.meta.v1 package. +This file was generated by the KCL auto-gen tool. DO NOT EDIT. +Editing this file might prove futile when you re-run the KCL auto-gen generate command. +""" + + +schema OwnerReference: + """ + OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. + + Attributes + ---------- + apiVersion : str, default is Undefined, required + API version of the referent. + blockOwnerDeletion : bool, default is Undefined, optional + 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. Defaults to false. To set this field, a user needs "delete" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. + controller : bool, default is Undefined, optional + If true, this reference points to the managing controller. + kind : str, default is Undefined, required + Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + name : str, default is Undefined, required + Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names + uid : str, default is Undefined, required + UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids + """ + + + apiVersion: str + + blockOwnerDeletion?: bool + + controller?: bool + + kind: str + + name: str + + uid: str + + diff --git a/pkg/kube_resource/generator/testdata/all_of_pattern/models/karpenter_k8s_aws_v1beta1_e_c2_node_class.k b/pkg/kube_resource/generator/testdata/all_of_pattern/models/karpenter_k8s_aws_v1beta1_e_c2_node_class.k new file mode 100644 index 0000000..38f83c7 --- /dev/null +++ b/pkg/kube_resource/generator/testdata/all_of_pattern/models/karpenter_k8s_aws_v1beta1_e_c2_node_class.k @@ -0,0 +1,398 @@ +""" +This file was generated by the KCL auto-gen tool. DO NOT EDIT. +Editing this file might prove futile when you re-run the KCL auto-gen generate command. +""" +import regex +import k8s.apimachinery.pkg.apis.meta.v1 + + +schema EC2NodeClass: + """ + EC2NodeClass is the Schema for the EC2NodeClass API + + Attributes + ---------- + apiVersion : str, default is "karpenter.k8s.aws/v1beta1", required + 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 + kind : str, default is "EC2NodeClass", required + 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 + metadata : v1.ObjectMeta, default is Undefined, optional + metadata + spec : KarpenterK8sAwsV1beta1EC2NodeClassSpec, default is Undefined, optional + spec + status : KarpenterK8sAwsV1beta1EC2NodeClassStatus, default is Undefined, optional + status + """ + + + apiVersion: "karpenter.k8s.aws/v1beta1" = "karpenter.k8s.aws/v1beta1" + + kind: "EC2NodeClass" = "EC2NodeClass" + + metadata?: v1.ObjectMeta + + spec?: KarpenterK8sAwsV1beta1EC2NodeClassSpec + + status?: KarpenterK8sAwsV1beta1EC2NodeClassStatus + + +schema KarpenterK8sAwsV1beta1EC2NodeClassSpec: + """ + EC2NodeClassSpec is the top level specification for the AWS Karpenter Provider. This will contain configuration necessary to launch instances in AWS. + + Attributes + ---------- + amiFamily : str, default is Undefined, required + AMIFamily is the AMI family that instances use. + amiSelectorTerms : [KarpenterK8sAwsV1beta1EC2NodeClassSpecAmiSelectorTermsItems0], default is Undefined, optional + AMISelectorTerms is a list of or ami selector terms. The terms are ORed. + blockDeviceMappings : [KarpenterK8sAwsV1beta1EC2NodeClassSpecBlockDeviceMappingsItems0], default is Undefined, optional + BlockDeviceMappings to be applied to provisioned nodes. + context : str, default is Undefined, optional + Context is a Reserved field in EC2 APIs https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet.html + detailedMonitoring : bool, default is Undefined, optional + DetailedMonitoring controls if detailed monitoring is enabled for instances that are launched + role : str, default is Undefined, required + Role is the AWS identity that nodes use. This field is immutable. Marking this field as immutable avoids concerns around terminating managed instance profiles from running instances. This field may be made mutable in the future, assuming the correct garbage collection and drift handling is implemented for the old instance profiles on an update. + securityGroupSelectorTerms : [KarpenterK8sAwsV1beta1EC2NodeClassSpecSecurityGroupSelectorTermsItems0], default is Undefined, required + SecurityGroupSelectorTerms is a list of or security group selector terms. The terms are ORed. + subnetSelectorTerms : [KarpenterK8sAwsV1beta1EC2NodeClassSpecSubnetSelectorTermsItems0], default is Undefined, required + SubnetSelectorTerms is a list of or subnet selector terms. The terms are ORed. + tags : {str:str}, default is Undefined, optional + Tags to be applied on ec2 resources like instances and launch templates. + userData : str, default is Undefined, optional + UserData to be applied to the provisioned nodes. It must be in the appropriate format based on the AMIFamily in use. Karpenter will merge certain fields into this UserData to ensure nodes are being provisioned with the correct configuration. + metadataOptions : KarpenterK8sAwsV1beta1EC2NodeClassSpecMetadataOptions, default is Undefined, optional + metadata options + """ + + + amiFamily: "AL2" | "Bottlerocket" | "Ubuntu" | "Custom" | "Windows2019" | "Windows2022" + + amiSelectorTerms?: [KarpenterK8sAwsV1beta1EC2NodeClassSpecAmiSelectorTermsItems0] + + blockDeviceMappings?: [KarpenterK8sAwsV1beta1EC2NodeClassSpecBlockDeviceMappingsItems0] + + context?: str + + detailedMonitoring?: bool + + role: str + + securityGroupSelectorTerms: [KarpenterK8sAwsV1beta1EC2NodeClassSpecSecurityGroupSelectorTermsItems0] + + subnetSelectorTerms: [KarpenterK8sAwsV1beta1EC2NodeClassSpecSubnetSelectorTermsItems0] + + tags?: {str:str} + + userData?: str + + metadataOptions?: KarpenterK8sAwsV1beta1EC2NodeClassSpecMetadataOptions + + + check: + len(amiSelectorTerms) <= 30 + len(blockDeviceMappings) <= 50 + len(securityGroupSelectorTerms) <= 30 + len(subnetSelectorTerms) <= 30 + + +schema KarpenterK8sAwsV1beta1EC2NodeClassSpecAmiSelectorTermsItems0: + """ + AMISelectorTerm defines selection logic for an ami used by Karpenter to launch nodes. If multiple fields are used for selection, the requirements are ANDed. + + Attributes + ---------- + id : str, default is Undefined, optional + ID is the ami id in EC2 + name : str, default is Undefined, optional + Name is the ami name in EC2. This value is the name field, which is different from the name tag. + owner : str, default is Undefined, optional + Owner is the owner for the ami. You can specify a combination of AWS account IDs, "self", "amazon", and "aws-marketplace" + tags : {str:str}, default is Undefined, optional + Tags is a map of key/value tags used to select subnets Specifying '*' for a value selects all values for a given tag key. + """ + + + id?: str + + name?: str + + owner?: str + + tags?: {str:str} + + + check: + regex.match(str(id), r"ami-[0-9a-z]+") if id + + +schema KarpenterK8sAwsV1beta1EC2NodeClassSpecBlockDeviceMappingsItems0: + """ + karpenter k8s aws v1beta1 e c2 node class spec block device mappings items0 + + Attributes + ---------- + deviceName : str, default is Undefined, optional + The device name (for example, /dev/sdh or xvdh). + ebs : KarpenterK8sAwsV1beta1EC2NodeClassSpecBlockDeviceMappingsItems0Ebs, default is Undefined, optional + ebs + rootVolume : bool, default is Undefined, optional + RootVolume is a flag indicating if this device is mounted as kubelet root dir. You can configure at most one root volume in BlockDeviceMappings. + """ + + + deviceName?: str + + ebs?: KarpenterK8sAwsV1beta1EC2NodeClassSpecBlockDeviceMappingsItems0Ebs + + rootVolume?: bool + + +schema KarpenterK8sAwsV1beta1EC2NodeClassSpecBlockDeviceMappingsItems0Ebs: + """ + EBS contains parameters used to automatically set up EBS volumes when an instance is launched. + + Attributes + ---------- + deleteOnTermination : bool, default is Undefined, optional + DeleteOnTermination indicates whether the EBS volume is deleted on instance termination. + encrypted : bool, default is Undefined, optional + Encrypted indicates whether the EBS volume is encrypted. Encrypted volumes can only be attached to instances that support Amazon EBS encryption. If you are creating a volume from a snapshot, you can't specify an encryption value. + iops : int, default is Undefined, optional + IOPS is the number of I/O operations per second (IOPS). For gp3, io1, and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + The following are the supported values for each volume type: + * gp3: 3,000-16,000 IOPS + * io1: 100-64,000 IOPS + * io2: 100-64,000 IOPS + For io1 and io2 volumes, we guarantee 64,000 IOPS only for Instances built on the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). Other instance families guarantee performance up to 32,000 IOPS. + This parameter is supported for io1, io2, and gp3 volumes only. This parameter is not supported for gp2, st1, sc1, or standard volumes. + kmsKeyID : str, default is Undefined, optional + KMSKeyID (ARN) of the symmetric Key Management Service (KMS) CMK used for encryption. + snapshotID : str, default is Undefined, optional + SnapshotID is the ID of an EBS snapshot + throughput : int, default is Undefined, optional + Throughput to provision for a gp3 volume, with a maximum of 1,000 MiB/s. Valid Range: Minimum value of 125. Maximum value of 1000. + volumeSize : int | str, default is Undefined, optional + VolumeSize in `Gi`, `G`, `Ti`, or `T`. You must specify either a snapshot ID or a volume size. The following are the supported volumes sizes for each volume type: + * gp2 and gp3: 1-16,384 + * io1 and io2: 4-16,384 + * st1 and sc1: 125-16,384 + * standard: 1-1,024 + volumeType : str, default is Undefined, optional + VolumeType of the block device. For more information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the Amazon Elastic Compute Cloud User Guide. + """ + + + deleteOnTermination?: bool + + encrypted?: bool + + iops?: int + + kmsKeyID?: str + + snapshotID?: str + + throughput?: int + + volumeSize?: int | str + + volumeType?: "standard" | "io1" | "io2" | "gp2" | "sc1" | "st1" | "gp3" + + + check: + regex.match(str(volumeSize), r"^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$") if volumeSize + regex.match(str(volumeSize), r"^((?:[1-9][0-9]{0,3}|[1-4][0-9]{4}|[5][0-8][0-9]{3}|59000)Gi|(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|[6][0-3][0-9]{3}|64000)G|([1-9]||[1-5][0-7]|58)Ti|([1-9]||[1-5][0-9]|6[0-3]|64)T)$") if volumeSize + + +schema KarpenterK8sAwsV1beta1EC2NodeClassSpecMetadataOptions: + """ + MetadataOptions for the generated launch template of provisioned nodes. + This specifies the exposure of the Instance Metadata Service to provisioned EC2 nodes. For more information, see Instance Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the Amazon Elastic Compute Cloud User Guide. + Refer to recommended, security best practices (https://aws.github.io/aws-eks-best-practices/security/docs/iam/#restrict-access-to-the-instance-profile-assigned-to-the-worker-node) for limiting exposure of Instance Metadata and User Data to pods. If omitted, defaults to httpEndpoint enabled, with httpProtocolIPv6 disabled, with httpPutResponseLimit of 2, and with httpTokens required. + + Attributes + ---------- + httpEndpoint : str, default is "enabled", optional + HTTPEndpoint enables or disables the HTTP metadata endpoint on provisioned nodes. If metadata options is non-nil, but this parameter is not specified, the default state is "enabled". + If you specify a value of "disabled", instance metadata will not be accessible on the node. + httpProtocolIPv6 : str, default is "disabled", optional + HTTPProtocolIPv6 enables or disables the IPv6 endpoint for the instance metadata service on provisioned nodes. If metadata options is non-nil, but this parameter is not specified, the default state is "disabled". + httpPutResponseHopLimit : int, default is 2, optional + HTTPPutResponseHopLimit is the desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. Possible values are integers from 1 to 64. If metadata options is non-nil, but this parameter is not specified, the default value is 2. + httpTokens : str, default is "required", optional + HTTPTokens determines the state of token usage for instance metadata requests. If metadata options is non-nil, but this parameter is not specified, the default state is "required". + If the state is optional, one can choose to retrieve instance metadata with or without a signed token header on the request. If one retrieves the IAM role credentials without a token, the version 1.0 role credentials are returned. If one retrieves the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + If the state is "required", one must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + """ + + + httpEndpoint?: "enabled" | "disabled" = "enabled" + + httpProtocolIPv6?: "enabled" | "disabled" = "disabled" + + httpPutResponseHopLimit?: int = 2 + + httpTokens?: "required" | "optional" = "required" + + + check: + httpPutResponseHopLimit <= 64 + httpPutResponseHopLimit >= 1 + + +schema KarpenterK8sAwsV1beta1EC2NodeClassSpecSecurityGroupSelectorTermsItems0: + """ + SecurityGroupSelectorTerm defines selection logic for a security group used by Karpenter to launch nodes. If multiple fields are used for selection, the requirements are ANDed. + + Attributes + ---------- + id : str, default is Undefined, optional + ID is the security group id in EC2 + name : str, default is Undefined, optional + Name is the security group name in EC2. This value is the name field, which is different from the name tag. + tags : {str:str}, default is Undefined, optional + Tags is a map of key/value tags used to select subnets Specifying '*' for a value selects all values for a given tag key. + """ + + + id?: str + + name?: str + + tags?: {str:str} + + + check: + regex.match(str(id), r"sg-[0-9a-z]+") if id + + +schema KarpenterK8sAwsV1beta1EC2NodeClassSpecSubnetSelectorTermsItems0: + """ + SubnetSelectorTerm defines selection logic for a subnet used by Karpenter to launch nodes. If multiple fields are used for selection, the requirements are ANDed. + + Attributes + ---------- + id : str, default is Undefined, optional + ID is the subnet id in EC2 + tags : {str:str}, default is Undefined, optional + Tags is a map of key/value tags used to select subnets Specifying '*' for a value selects all values for a given tag key. + """ + + + id?: str + + tags?: {str:str} + + + check: + regex.match(str(id), r"subnet-[0-9a-z]+") if id + + +schema KarpenterK8sAwsV1beta1EC2NodeClassStatus: + """ + EC2NodeClassStatus contains the resolved state of the EC2NodeClass + + Attributes + ---------- + amis : [KarpenterK8sAwsV1beta1EC2NodeClassStatusAmisItems0], default is Undefined, optional + AMI contains the current AMI values that are available to the cluster under the AMI selectors. + instanceProfile : str, default is Undefined, optional + InstanceProfile contains the resolved instance profile for the role + securityGroups : [KarpenterK8sAwsV1beta1EC2NodeClassStatusSecurityGroupsItems0], default is Undefined, optional + SecurityGroups contains the current Security Groups values that are available to the cluster under the SecurityGroups selectors. + subnets : [KarpenterK8sAwsV1beta1EC2NodeClassStatusSubnetsItems0], default is Undefined, optional + Subnets contains the current Subnet values that are available to the cluster under the subnet selectors. + """ + + + amis?: [KarpenterK8sAwsV1beta1EC2NodeClassStatusAmisItems0] + + instanceProfile?: str + + securityGroups?: [KarpenterK8sAwsV1beta1EC2NodeClassStatusSecurityGroupsItems0] + + subnets?: [KarpenterK8sAwsV1beta1EC2NodeClassStatusSubnetsItems0] + + +schema KarpenterK8sAwsV1beta1EC2NodeClassStatusAmisItems0: + """ + AMI contains resolved AMI selector values utilized for node launch + + Attributes + ---------- + id : str, default is Undefined, required + ID of the AMI + name : str, default is Undefined, optional + Name of the AMI + requirements : [KarpenterK8sAwsV1beta1EC2NodeClassStatusAmisItems0RequirementsItems0], default is Undefined, required + Requirements of the AMI to be utilized on an instance type + """ + + + id: str + + name?: str + + requirements: [KarpenterK8sAwsV1beta1EC2NodeClassStatusAmisItems0RequirementsItems0] + + +schema KarpenterK8sAwsV1beta1EC2NodeClassStatusAmisItems0RequirementsItems0: + """ + A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + + Attributes + ---------- + key : str, default is Undefined, required + The label key that the selector applies to. + operator : str, default is Undefined, required + Represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + values : [str], default is Undefined, optional + An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch. + """ + + + key: str + + operator: str + + values?: [str] + + +schema KarpenterK8sAwsV1beta1EC2NodeClassStatusSecurityGroupsItems0: + """ + SecurityGroup contains resolved SecurityGroup selector values utilized for node launch + + Attributes + ---------- + id : str, default is Undefined, required + ID of the security group + name : str, default is Undefined, optional + Name of the security group + """ + + + id: str + + name?: str + + +schema KarpenterK8sAwsV1beta1EC2NodeClassStatusSubnetsItems0: + """ + Subnet contains resolved Subnet selector values utilized for node launch + + Attributes + ---------- + id : str, default is Undefined, required + ID of the subnet + zone : str, default is Undefined, required + The associated availability zone + """ + + + id: str + + zone: str + + diff --git a/pkg/swagger/generator/model.go b/pkg/swagger/generator/model.go index be97e69..83a8cee 100644 --- a/pkg/swagger/generator/model.go +++ b/pkg/swagger/generator/model.go @@ -465,6 +465,18 @@ func (sg *schemaGenContext) NewCompositionBranch(schema spec.Schema, index int) return pg } +func (sg *schemaGenContext) NewBranch(schema spec.Schema) *schemaGenContext { + debugLog("new branch %s (parent: %s)", sg.Name, sg.Container) + pg := sg.shallowClone() + pg.Schema = schema + pg.Name = "" + if sg.Name != sg.TypeResolver.ModelName { + pg.Name = sg.Name + pg.Name + } + debugLog("made new branch %s (parent: %s)", pg.Name, pg.Container) + return pg +} + func (sg *schemaGenContext) NewAdditionalProperty(schema spec.Schema) *schemaGenContext { debugLog("new additional property %s (expr: %s)", sg.Name, sg.ValueExpr) pg := sg.shallowClone() @@ -722,7 +734,13 @@ func (sg *schemaGenContext) buildAllOf() error { continue } - comprop := sg.NewCompositionBranch(sch, i) + var comprop *schemaGenContext + // primitive type or int-or-str type + if (tpe.IsAnonymous || tpe.IsPrimitive) && tpe.IsMap && sch.Ref.String() == "" && !tpe.IsComplexObject { + comprop = sg.NewBranch(sch) + } else { + comprop = sg.NewCompositionBranch(sch, i) + } if err := comprop.makeGenSchema(); err != nil { return err } diff --git a/pkg/swagger/generator/shared.go b/pkg/swagger/generator/shared.go index 9c96a37..cb280a8 100644 --- a/pkg/swagger/generator/shared.go +++ b/pkg/swagger/generator/shared.go @@ -383,6 +383,15 @@ func sharedValidationsFromSchema(v spec.Schema, sg schemaGenContext) (sh sharedV if v.AdditionalProperties != nil && v.AdditionalProperties.Schema != nil && v.AdditionalProperties.Schema.Pattern != "" { sh.AdditionalPropertiesPattern = v.AdditionalProperties.Schema.Pattern } + for _, s := range v.AllOf { + sh.AllOf = append(sh.AllOf, sharedValidationsFromSchema(s, sg)) + } + for _, s := range v.AnyOf { + sh.AnyOf = append(sh.AnyOf, sharedValidationsFromSchema(s, sg)) + } + for _, s := range v.OneOf { + sh.OneOf = append(sh.OneOf, sharedValidationsFromSchema(s, sg)) + } sh.pruneEnums(sg) return } diff --git a/pkg/swagger/generator/structs.go b/pkg/swagger/generator/structs.go index afbc9d1..505c454 100644 --- a/pkg/swagger/generator/structs.go +++ b/pkg/swagger/generator/structs.go @@ -158,6 +158,10 @@ type sharedValidations struct { ItemPattern string AdditionalPropertiesPattern string + + AllOf []sharedValidations + AnyOf []sharedValidations + OneOf []sharedValidations } // pruneEnums omit nil from enum values diff --git a/pkg/swagger/generator/templates/schemavalidator.gotmpl b/pkg/swagger/generator/templates/schemavalidator.gotmpl index 17911d1..1052d9e 100644 --- a/pkg/swagger/generator/templates/schemavalidator.gotmpl +++ b/pkg/swagger/generator/templates/schemavalidator.gotmpl @@ -1,6 +1,6 @@ {{- define "schemavalidator" -}} {{- range . -}} -{{- if or .Maximum .Minimum .MaxLength .MinLength .Pattern .UniqueItems .MinItems .MaxItems .MultipleOf .ItemPattern .AdditionalPropertiesPattern }} +{{- if or .Maximum .Minimum .MaxLength .MinLength .Pattern .UniqueItems .MinItems .MaxItems .MultipleOf .ItemPattern .AdditionalPropertiesPattern .AllOf }} {{- if .Maximum }} {{ if .ExclusiveMaximum }}{{ .EscapedName }} < {{.Maximum}}{{- else }}{{ .EscapedName }} <= {{.Maximum}}{{ end }} {{- end }} @@ -28,12 +28,15 @@ {{- if .MultipleOf }} multiplyof(int({{ .EscapedName }}), int({{ .MultipleOf }})) {{- end }} - {{- if and .ItemPattern }} + {{- if .ItemPattern }} all n in {{ .EscapedName }} { regex.match(str(n), r"{{ .ItemPattern }}") }{{ if not .Required }} if {{ .EscapedName }}{{ end }} {{- end }} - {{- if and .AdditionalPropertiesPattern }} + {{- if .AdditionalPropertiesPattern }} all _, n in {{ .EscapedName }} { regex.match(str(n), r"{{ .AdditionalPropertiesPattern }}") }{{ if not .Required }} if {{ .EscapedName }}{{ end }} {{- end }} + {{- if .AllOf }} + {{- template "schemavalidator" .AllOf }} + {{- end }} {{- end -}} {{- end -}} {{- end -}}