Skip to content

Commit

Permalink
More resources from class generator (RedHatQE#2009)
Browse files Browse the repository at this point in the history
* create and convert resources using class generator script

* create and convert resources using class generator script

* create and convert resources using class generator script

* create and convert resources using class generator script
  • Loading branch information
myakove authored Aug 11, 2024
1 parent de96b1b commit 014af3b
Show file tree
Hide file tree
Showing 13 changed files with 3,033 additions and 82 deletions.
4 changes: 3 additions & 1 deletion class_generator/class_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from pyhelper_utils.shell import run_command
import pytest
from rich.console import Console
from rich.syntax import Syntax

from rich.prompt import Prompt
from ocp_resources.resource import Resource
Expand Down Expand Up @@ -377,7 +378,8 @@ def generate_resource_file_from_dict(
_output_file = temp_output_file

if dry_run:
Console().print(rendered)
_code = Syntax(code=rendered, lexer="python", line_numbers=True)
Console().print(_code)

else:
write_and_format_rendered(filepath=_output_file, data=rendered)
Expand Down
143 changes: 137 additions & 6 deletions ocp_resources/deployment.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,146 @@
# -*- coding: utf-8 -*-
from ocp_resources.constants import PROTOCOL_ERROR_EXCEPTION_DICT, TIMEOUT_4MINUTES
from ocp_resources.resource import NamespacedResource
# Generated using https://github.com/RedHatQE/openshift-python-wrapper/blob/main/scripts/resource/README.md

from typing import Any, Dict, Optional

from timeout_sampler import TimeoutSampler, TimeoutWatch
from ocp_resources.constants import PROTOCOL_ERROR_EXCEPTION_DICT, TIMEOUT_4MINUTES
from ocp_resources.resource import NamespacedResource, MissingRequiredArgumentError


class Deployment(NamespacedResource):
"""
OpenShift Deployment object.
Deployment enables declarative updates for Pods and ReplicaSets.
"""

api_group = NamespacedResource.ApiGroup.APPS
api_group: str = NamespacedResource.ApiGroup.APPS

def __init__(
self,
min_ready_seconds: Optional[int] = None,
paused: Optional[bool] = None,
progress_deadline_seconds: Optional[int] = None,
replicas: Optional[int] = None,
revision_history_limit: Optional[int] = None,
selector: Optional[Dict[str, Any]] = None,
strategy: Optional[Dict[str, Any]] = None,
template: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
"""
Args:
min_ready_seconds(int): Minimum number of seconds for which a newly created pod should be ready
without any of its container crashing, for it to be considered available.
Defaults to 0 (pod will be considered available as soon as it is ready)
paused(bool): Indicates that the deployment is paused.
progress_deadline_seconds(int): The maximum time in seconds for a deployment to make progress before it is
considered to be failed. The deployment controller will continue to process
failed deployments and a condition with a ProgressDeadlineExceeded reason
will be surfaced in the deployment status. Note that progress will not be
estimated during the time a deployment is paused. Defaults to 600s.
replicas(int): Number of desired pods. This is a pointer to distinguish between explicit
zero and not specified. Defaults to 1.
revision_history_limit(int): The number of old ReplicaSets to retain to allow rollback. This is a pointer
to distinguish between explicit zero and not specified. Defaults to 10.
selector(Dict[Any, Any]): Label selector for pods. Existing ReplicaSets whose pods are selected by
this will be the ones affected by this deployment. It must match the pod
template's labels.
A label selector is a label query over a set of resources. The result of
matchLabels and matchExpressions are ANDed. An empty label selector matches
all objects. A null label selector matches no objects.
FIELDS:
matchExpressions <[]LabelSelectorRequirement>
matchExpressions is a list of label selector requirements. The requirements
are ANDed.
matchLabels <map[string]string>
matchLabels is a map of {key,value} pairs. A single {key,value} in the
matchLabels map is equivalent to an element of matchExpressions, whose key
field is "key", the operator is "In", and the values array contains only
"value". The requirements are ANDed.
strategy(Dict[Any, Any]): The deployment strategy to use to replace existing pods with new ones.
DeploymentStrategy describes how to replace existing pods with new ones.
FIELDS:
rollingUpdate <RollingUpdateDeployment>
Rolling update config params. Present only if DeploymentStrategyType =
RollingUpdate.
type <string>
Type of deployment. Can be "Recreate" or "RollingUpdate". Default is
RollingUpdate.
Possible enum values:
- `"Recreate"` Kill all existing pods before creating new ones.
- `"RollingUpdate"` Replace the old ReplicaSets by new one using rolling
update i.e gradually scale down the old ReplicaSets and scale up the new
one.
template(Dict[Any, Any]): Template describes the pods that will be created. The only allowed
template.spec.restartPolicy value is "Always".
PodTemplateSpec describes the data a pod should have when created from a
template
FIELDS:
metadata <ObjectMeta>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
spec <PodSpec>
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
"""
super().__init__(**kwargs)

self.min_ready_seconds = min_ready_seconds
self.paused = paused
self.progress_deadline_seconds = progress_deadline_seconds
self.replicas = replicas
self.revision_history_limit = revision_history_limit
self.selector = selector
self.strategy = strategy
self.template = template

def to_dict(self) -> None:
super().to_dict()

if not self.yaml_file:
if not all([
self.selector,
self.template,
]):
raise MissingRequiredArgumentError(argument="selector, template")

self.res["spec"] = {}
_spec = self.res["spec"]

self.res["selector"] = self.selector
self.res["template"] = self.template

if self.min_ready_seconds:
_spec["minReadySeconds"] = self.min_ready_seconds

if self.paused is not None:
_spec["paused"] = self.paused

if self.progress_deadline_seconds:
_spec["progressDeadlineSeconds"] = self.progress_deadline_seconds

if self.replicas:
_spec["replicas"] = self.replicas

if self.revision_history_limit:
_spec["revisionHistoryLimit"] = self.revision_history_limit

if self.strategy:
_spec["strategy"] = self.strategy

def scale_replicas(self, replica_count=int):
"""
Expand All @@ -27,7 +158,7 @@ def scale_replicas(self, replica_count=int):
self.logger.info(f"Set deployment replicas: {replica_count}")
return self.update(resource_dict=self.res)

def wait_for_replicas(self, deployed=True, timeout=TIMEOUT_4MINUTES):
def wait_for_replicas(self, deployed: bool = True, timeout: int = TIMEOUT_4MINUTES):
"""
Wait until all replicas are updated.
Expand Down
47 changes: 29 additions & 18 deletions ocp_resources/namespace.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,42 @@
from ocp_resources.constants import TIMEOUT_4MINUTES
# Generated using https://github.com/RedHatQE/openshift-python-wrapper/blob/main/scripts/resource/README.md

from typing import Any, Dict, Optional
from ocp_resources.resource import Resource


class Namespace(Resource):
"""
Namespace object, inherited from Resource.
Namespace provides a scope for Names. Use of multiple namespaces is
optional.
"""

api_version = Resource.ApiVersion.V1
api_version: str = Resource.ApiVersion.V1

class Status(Resource.Status):
ACTIVE = "Active"

def __init__(
self,
name=None,
client=None,
teardown=True,
yaml_file=None,
delete_timeout=TIMEOUT_4MINUTES,
**kwargs,
):
super().__init__(
name=name,
client=client,
teardown=teardown,
yaml_file=yaml_file,
delete_timeout=delete_timeout,
**kwargs,
)
finalizers: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
"""
Args:
finalizers(Dict[Any, Any]): Finalizers is an opaque list of values that must be empty to permanently
remove object from storage. More info:
https://kubernetes.io/docs/tasks/administer-cluster/namespaces/
"""
super().__init__(**kwargs)

self.finalizers = finalizers

def to_dict(self) -> None:
super().to_dict()

if not self.yaml_file:
self.res["spec"] = {}
_spec = self.res["spec"]

if self.finalizers:
_spec["finalizers"] = self.finalizers
15 changes: 13 additions & 2 deletions ocp_resources/operator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
# https://docs.openshift.com/container-platform/4.12/operators/operator-reference.html
# Generated using https://github.com/RedHatQE/openshift-python-wrapper/blob/main/scripts/resource/README.md

from typing import Any
from ocp_resources.resource import Resource


class Operator(Resource):
api_group = Resource.ApiGroup.OPERATORS_COREOS_COM
"""
Operator represents a cluster operator.
"""

api_group: str = Resource.ApiGroup.OPERATORS_COREOS_COM

def __init__(
self,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
114 changes: 84 additions & 30 deletions ocp_resources/project.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,104 @@
from ocp_resources.constants import TIMEOUT_4MINUTES
# Generated using https://github.com/RedHatQE/openshift-python-wrapper/blob/main/scripts/resource/README.md

from typing import Any, Dict, Optional
from ocp_resources.resource import Resource


class Project(Resource):
"""
Project object.
This is openshift's object which represents Namespace
Projects are the unit of isolation and collaboration in OpenShift. A project
has one or more members, a quota on the resources that the project may
consume, and the security controls on the resources in the project. Within a
project, members may have different roles - project administrators can set
membership, editors can create and manage the resources, and viewers can see
but not access running containers. In a normal cluster project
administrators are not able to alter their quotas - that is restricted to
cluster administrators.
Listing or watching projects will return only projects the user has the
reader role on.
An OpenShift project is an alternative representation of a Kubernetes
namespace. Projects are exposed as editable to end users while namespaces
are not. Direct creation of a project is typically restricted to
administrators, while end users should use the requestproject resource.
Compatibility level 1: Stable within a major release for a minimum of 12
months or 3 minor releases (whichever is longer).
"""

api_group = Resource.ApiGroup.PROJECT_OPENSHIFT_IO
api_group: str = Resource.ApiGroup.PROJECT_OPENSHIFT_IO

class Status(Resource.Status):
ACTIVE = "Active"

def clean_up(self):
Project(name=self.name).delete(wait=True)
def __init__(
self,
finalizers: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
"""
Args:
finalizers(Dict[Any, Any]): Finalizers is an opaque list of values that must be empty to permanently
remove object from storage
"""
super().__init__(**kwargs)

self.finalizers = finalizers

def to_dict(self) -> None:
super().to_dict()

if not self.yaml_file:
self.res["spec"] = {}
_spec = self.res["spec"]

if self.finalizers:
_spec["finalizers"] = self.finalizers

def clean_up(self, wait: bool = True) -> bool:
return Project(name=self.name).delete(wait=wait)


class ProjectRequest(Resource):
"""
RequestProject object.
Resource which adds Project and grand
full access to user who originated this request
ProjectRequest is the set of options necessary to fully qualify a project
request
Compatibility level 1: Stable within a major release for a minimum of 12
months or 3 minor releases (whichever is longer).
"""

api_group = Resource.ApiGroup.PROJECT_OPENSHIFT_IO
api_group: str = Resource.ApiGroup.PROJECT_OPENSHIFT_IO

def __init__(
self,
name=None,
client=None,
teardown=True,
timeout=TIMEOUT_4MINUTES,
yaml_file=None,
delete_timeout=TIMEOUT_4MINUTES,
**kwargs,
):
super().__init__(
name=name,
client=client,
teardown=teardown,
timeout=timeout,
yaml_file=yaml_file,
delete_timeout=delete_timeout,
**kwargs,
)

def clean_up(self):
Project(name=self.name).delete(wait=True)
description: Optional[str] = "",
display_name: Optional[str] = "",
**kwargs: Any,
) -> None:
"""
Args:
description(str): Description is the description to apply to a project
display_name(str): DisplayName is the display name to apply to a project
"""
super().__init__(**kwargs)

self.description = description
self.display_name = display_name

def to_dict(self) -> None:
super().to_dict()

if not self.yaml_file:
if self.description:
self.res["description"] = self.description

if self.display_name:
self.res["displayName"] = self.display_name

def clean_up(self, wait: bool = True) -> bool:
return Project(name=self.name).delete(wait=wait)
Loading

0 comments on commit 014af3b

Please sign in to comment.